Merge branch 'master' into purring-basilisk

Signed-off-by: Iceman <iceman@iuse.se>
This commit is contained in:
Iceman 2024-04-22 17:41:01 +02:00 committed by GitHub
commit 9343014b68
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 7056 additions and 5149 deletions

View file

@ -3,9 +3,12 @@ All notable changes to this project will be documented in this file.
This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log...
## [unreleased][unreleased]
- Removed `save_restoreDB` - replaced by `buffer_savestate_t` implementation (@HACKhalo2)
- Removed `save_restoreGB` - replaced by `buffer_savestate_t` implementation (@HACKhalo2)
- Changed `lf hitag dump --nrar` - now supports attack 1 from "gone in 360 seconds" paper. Thanks @kevsecurity! (@iceman1001)
- Added `lf hitag selftest` - converted from RFIDLers selftest (@iceman1001)
- Added `lf hitag chk` - dictionary attack against card (@iceman1001)
- Added `lf hitag lookup` - verify collected challenges aginst dictionary (@iceman1001)
- Updated windows workflow to use latest setup-wsl script (@iceman1001)
- Added a micro second clock in the client (@iceman1001)
- Fix `hf mfdes read` - buffer overflow when reading large files (@iceman1001)

View file

@ -71,7 +71,7 @@ else
endif
ifneq (,$(findstring WITH_HITAG,$(APP_CFLAGS)))
SRC_HITAG = hitag2_crypto.c hitag2.c hitagS.c
SRC_HITAG = hitag2_crypto.c hitag2.c hitagS.c hitag2_crack.c
APP_CFLAGS += -I../common/hitag2
else
SRC_HITAG =

View file

@ -40,6 +40,7 @@
#include "thinfilm.h"
#include "felica.h"
#include "hitag2.h"
#include "hitag2_crack.h"
#include "hitagS.h"
#include "em4x50.h"
#include "em4x70.h"
@ -1131,7 +1132,7 @@ static void PacketReceived(PacketCommandNG *packet) {
#ifdef WITH_HITAG
case CMD_LF_HITAG_SNIFF: { // Eavesdrop Hitag tag, args = type
SniffHitag2(true);
// SniffHitag2(packet->oldarg[0]);
//hitag_sniff();
reply_ng(CMD_LF_HITAG_SNIFF, PM3_SUCCESS, NULL, 0);
break;
}
@ -1139,8 +1140,24 @@ static void PacketReceived(PacketCommandNG *packet) {
SimulateHitag2(true);
break;
}
case CMD_LF_HITAG2_CRACK: {
lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes;
ht2_crack(payload->NrAr);
break;
}
case CMD_LF_HITAG_READER: { // Reader for Hitag tags, args = type and function
ReaderHitag((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, true);
lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes;
switch (payload->cmd) {
case RHT2F_UID_ONLY: {
ht2_read_uid(NULL, true, true, false);
break;
}
default: {
ReaderHitag(payload, true);
break;
}
}
break;
}
case CMD_LF_HITAGS_SIMULATE: { // Simulate Hitag s tag, args = memory content
@ -1148,25 +1165,28 @@ static void PacketReceived(PacketCommandNG *packet) {
break;
}
case CMD_LF_HITAGS_TEST_TRACES: { // Tests every challenge within the given file
Hitag_check_challenges(packet->data.asBytes, packet->oldarg[0], true);
Hitag_check_challenges(packet->data.asBytes, packet->length, true);
break;
}
case CMD_LF_HITAGS_READ: { //Reader for only Hitag S tags, args = key or challenge
ReadHitagS((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, true);
case CMD_LF_HITAGS_READ: { // Reader for only Hitag S tags, args = key or challenge
lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes;
ReadHitagS(payload, true);
break;
}
case CMD_LF_HITAGS_WRITE: { //writer for Hitag tags args=data to write,page and key or challenge
if ((hitag_function)packet->oldarg[0] < 10) {
WritePageHitagS((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, packet->oldarg[2], true);
} else {
WriterHitag((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, packet->oldarg[2], true);
}
case CMD_LF_HITAGS_WRITE: {
lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes;
WritePageHitagS(payload, true);
break;
}
case CMD_LF_HITAG2_WRITE: {
lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes;
WriterHitag(payload, true);
break;
}
case CMD_LF_HITAG_ELOAD: {
lf_hitag_t *payload = (lf_hitag_t *) packet->data.asBytes;
uint8_t *mem = BigBuf_get_EM_addr();
memcpy((uint8_t *)mem, payload->data, payload->len);
memcpy(mem, payload->data, payload->len);
break;
}
#endif
@ -1371,7 +1391,7 @@ static void PacketReceived(PacketCommandNG *packet) {
struct p *payload = (struct p *) packet->data.asBytes;
SetTag15693Uid_v2(payload->uid);
break;
}
}
case CMD_HF_ISO15693_SLIX_DISABLE_EAS: {
struct p {
uint8_t pwd[4];

File diff suppressed because it is too large Load diff

View file

@ -23,8 +23,12 @@
#include "hitag.h"
void SniffHitag2(bool ledcontrol);
void hitag_sniff(void);
void SimulateHitag2(bool ledcontrol);
void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol);
void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol);
void EloadHitag(const uint8_t *data, uint16_t len);
void ReaderHitag(const lf_hitag_data_t *payload, bool ledcontrol);
void WriterHitag(const lf_hitag_data_t *payload, bool ledcontrol);
bool ht2_packbits(uint8_t *nrz_samples, size_t nrzs, uint8_t *rx, size_t *rxlen);
int ht2_read_uid(uint8_t *uid, bool ledcontrol, bool send_answer, bool keep_field_up);
int ht2_tx_rx(uint8_t *tx, size_t txlen, uint8_t *rx, size_t *rxlen, bool ledcontrol, bool keep_field_up);
#endif

View file

@ -14,7 +14,7 @@
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// This coode has been converted from RFIDler source code to work with Proxmark3.
// This coode has been converted from RFIDler source code to work with Proxmark3.
// https://github.com/AdamLaurie/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/hitag2crack.c
@ -32,7 +32,7 @@
const static uint8_t ERROR_RESPONSE[] = { 0xF4, 0x02, 0x88, 0x9C };
// #define READP0CMD "1100000111"
const static uint8_t read_p0_cmd[] = {1,1,0,0,0,0,0,1,1,1};
const static uint8_t read_p0_cmd[] = {1, 1, 0, 0, 0, 0, 0, 1, 1, 1};
// hitag2crack_xor XORs the source with the pad to produce the target.
// source, target and pad are binarrays of length len.
@ -121,7 +121,7 @@ static bool hitag2crack_read_page(uint8_t *resp, uint8_t pagenum, uint8_t *nrar,
uint8_t response[32];
// convert to binarray
hex2binarray((char*)e_response, (char*)e_resp);
hex2binarray((char *)e_response, (char *)e_resp);
// decrypt response
hitag2crack_xor(response, e_response, keybits + 10, 32);
@ -129,7 +129,7 @@ static bool hitag2crack_read_page(uint8_t *resp, uint8_t pagenum, uint8_t *nrar,
binarray2hex(response, 32, resp);
return true;
}
}
}
return false;
@ -200,7 +200,7 @@ static bool hitag2crack_find_e_page0_cmd(uint8_t *keybits, uint8_t *e_firstcmd,
// representing the inverted bit and the 3 page bits
// in both the non-inverted and inverted parts of the
// encrypted command.
uint8_t guess[10];
uint8_t guess[10];
memcpy(guess, e_firstcmd, 10);
if (a) {
guess[5] = !guess[5];
@ -231,7 +231,7 @@ static bool hitag2crack_find_e_page0_cmd(uint8_t *keybits, uint8_t *e_firstcmd,
// convert response to binarray
uint8_t e_uid[32];
hex2binarray((char*)e_uid, (char*)resp);
hex2binarray((char *)e_uid, (char *)resp);
// test if the guess was 'read page 0' command
if (hitag2crack_test_e_p0cmd(keybits, nrar, guess, uid, e_uid)) {
@ -299,13 +299,13 @@ static bool hitag2crack_find_valid_e_cmd(uint8_t *e_cmd, uint8_t *nrar) {
// hitag2_crack implements the first crack algorithm described in the paper,
// Gone In 360 Seconds by Verdult, Garcia and Balasch.
// response is a multi-line text response containing the 8 pages of the cracked tag
// nrarhex is a string containing hex representations of the 32 bit nR and aR values
// nrarhex is a string containing hex representations of the 32 bit nR and aR values
void ht2_crack(uint8_t *nrar_hex) {
clear_trace();
lf_hitag_crack_response_t packet;
memset((uint8_t*)&packet, 0x00, sizeof(lf_hitag_crack_response_t));
memset((uint8_t *)&packet, 0x00, sizeof(lf_hitag_crack_response_t));
int res = PM3_SUCCESS;
@ -319,7 +319,7 @@ void ht2_crack(uint8_t *nrar_hex) {
// convert to binarray
uint8_t nrar[64] = {0};
hex2binarray_n((char*)nrar, (char*)nrar_hex, 8);
hex2binarray_n((char *)nrar, (char *)nrar_hex, 8);
// find a valid encrypted command
uint8_t e_firstcmd[10];
@ -331,7 +331,7 @@ void ht2_crack(uint8_t *nrar_hex) {
// now we got a first encrypted command inside e_firstcmd
uint8_t uid[32];
hex2binarray_n((char*)uid, (char*)uid_hex, 4);
hex2binarray_n((char *)uid, (char *)uid_hex, 4);
// find the 'read page 0' command and recover key stream
uint8_t keybits[42];
@ -352,5 +352,5 @@ void ht2_crack(uint8_t *nrar_hex) {
packet.status = 1;
out:
reply_ng(CMD_LF_HITAG2_CRACK, res, (uint8_t*)&packet, sizeof(lf_hitag_crack_response_t));
reply_ng(CMD_LF_HITAG2_CRACK, res, (uint8_t *)&packet, sizeof(lf_hitag_crack_response_t));
}

View file

@ -52,7 +52,7 @@ static uint32_t temp_uid;
static int temp2 = 0;
static int sof_bits; // number of start-of-frame bits
static uint8_t pwdh0, pwdl0, pwdl1; // password bytes
static uint32_t rnd = 0x74124485; // randomnumber
static uint32_t rnd = 0x74124485; // random number
//#define SENDBIT_TEST
/* array index 3 2 1 0 // bytes in sim.bin file are 0 1 2 3
@ -125,12 +125,13 @@ static void calc_crc(unsigned char *crc, unsigned char data, unsigned char Bitco
}
static void hitag_send_bit(int bit, bool ledcontrol) {
if (ledcontrol) LED_A_ON();
// Reset clock for the next bit
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
switch (m) {
case AC2K:
case AC2K: {
if (bit == 0) {
// AC Coding --__
HIGH(GPIO_SSC_DOUT);
@ -156,7 +157,8 @@ static void hitag_send_bit(int bit, bool ledcontrol) {
}
if (ledcontrol) LED_A_OFF();
break;
case AC4K:
}
case AC4K: {
if (bit == 0) {
// AC Coding --__
HIGH(GPIO_SSC_DOUT);
@ -181,7 +183,8 @@ static void hitag_send_bit(int bit, bool ledcontrol) {
}
if (ledcontrol) LED_A_OFF();
break;
case MC4K:
}
case MC4K: {
if (bit == 0) {
// Manchester: Unloaded, then loaded |__--|
LOW(GPIO_SSC_DOUT);
@ -201,7 +204,8 @@ static void hitag_send_bit(int bit, bool ledcontrol) {
}
if (ledcontrol) LED_A_OFF();
break;
case MC8K:
}
case MC8K: {
if (bit == 0) {
// Manchester: Unloaded, then loaded |__--|
LOW(GPIO_SSC_DOUT);
@ -221,26 +225,33 @@ static void hitag_send_bit(int bit, bool ledcontrol) {
}
if (ledcontrol) LED_A_OFF();
break;
default:
}
default: {
break;
}
}
}
static void hitag_send_frame(const uint8_t *frame, size_t frame_len, bool ledcontrol) {
if (g_dbglevel >= DBG_EXTENDED)
if (g_dbglevel >= DBG_EXTENDED) {
Dbprintf("hitag_send_frame: (%i) %02X %02X %02X %02X", frame_len, frame[0], frame[1], frame[2], frame[3]);
}
// The beginning of the frame is hidden in some high level; pause until our bits will have an effect
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
HIGH(GPIO_SSC_DOUT);
switch (m) {
case AC4K:
case MC8K:
case MC8K: {
while (AT91C_BASE_TC0->TC_CV < T0 * 40) {}; //FADV
break;
}
case AC2K:
case MC4K:
case MC4K: {
while (AT91C_BASE_TC0->TC_CV < T0 * 20) {}; //STD + ADV
break;
}
}
// SOF - send start of frame
@ -317,43 +328,101 @@ static void hitag_reader_send_frame(const uint8_t *frame, size_t frame_len, bool
LOW(GPIO_SSC_DOUT);
}
static void hitagS_init_clock(void) {
// Enable Peripheral Clock for
// TIMER_CLOCK0, used to measure exact timing before answering
// TIMER_CLOCK1, used to capture edges of the tag frames
AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1);
AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
// Disable timer during configuration
AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
// TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers
AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK;
// TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
// external trigger rising edge, load RA on falling edge of TIOA.
AT91C_BASE_TC1->TC_CMR =
AT91C_TC_CLKS_TIMER_DIV1_CLOCK |
AT91C_TC_ETRGEDG_FALLING |
AT91C_TC_ABETRG |
AT91C_TC_LDRA_FALLING |
AT91C_TC_ACPA_CLEAR | // RA comperator clears TIOA (carry bit)
AT91C_TC_ASWTRG_SET; // SWTriger sets TIOA (carry bit)
AT91C_BASE_TC0->TC_RC = 0; // set TIOA (carry bit) on overflow, return to zero
AT91C_BASE_TC0->TC_RA = 1; // clear carry bit on next clock cycle
// Enable and reset counters
AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
// synchronized startup procedure
while (AT91C_BASE_TC0->TC_CV > 0); // wait until TC0 returned to zero
// while (AT91C_BASE_TC0->TC_CV < 2); // and has started (TC_CV > TC_RA, now TC1 is cleared)
// return to zero
AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
while (AT91C_BASE_TC0->TC_CV > 0);
}
static void hitagS_stop_clock(void) {
AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
}
/*
* to check if the right uid was selected
*/
static int check_select(const uint8_t *rx, uint32_t uid) {
unsigned char resp[48];
uint32_t ans = 0x0;
for (int i = 0; i < 48; i++)
resp[i] = (rx[i / 8] >> (7 - (i % 8))) & 0x1;
for (int i = 0; i < 32; i++)
for (int i = 0; i < 48; i++) {
resp[i] = (rx[i / 8] >> (7 - (i % 8))) & 0x1;
}
for (int i = 0; i < 32; i++) {
ans += resp[5 + i] << (31 - i);
}
// global var?
temp_uid = ans;
if (ans == tag.uid)
if (ans == tag.uid) {
return 1;
}
return 0;
}
static void hitagS_set_frame_modulation(void) {
switch (tag.mode) {
case HT_STANDARD:
case HT_STANDARD: {
sof_bits = 1;
m = MC4K;
break;
case HT_ADVANCED:
}
case HT_ADVANCED: {
sof_bits = 6;
m = MC4K;
break;
case HT_FAST_ADVANCED:
}
case HT_FAST_ADVANCED: {
sof_bits = 6;
m = MC8K;
break;
default:
}
default: {
break;
}
}
}
@ -411,16 +480,18 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
for (int i = 0; i < 4; i++) {
tx[i] = (tag.uid >> (24 - (i * 8))) & 0xFF;
}
break;
}
break;
case 45: {
//select command from reader received
if (g_dbglevel >= DBG_EXTENDED)
if (g_dbglevel >= DBG_EXTENDED) {
DbpString("SELECT");
}
if (check_select(rx, tag.uid) == 1) {
if (g_dbglevel >= DBG_EXTENDED)
if (g_dbglevel >= DBG_EXTENDED) {
DbpString("SELECT match");
}
//if the right tag was selected
*txlen = 32;
@ -434,8 +505,10 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
tx[3] = 0xff;
if (tag.mode != HT_STANDARD) {
*txlen = 40;
crc = CRC_PRESET;
for (int i = 0; i < 4; i++) {
calc_crc(&crc, tx[i], 8);
}
@ -443,8 +516,8 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
tx[4] = crc;
}
}
break;
}
break;
case 64: {
//challenge message received
Dbprintf("Challenge for UID: %X", temp_uid);
@ -499,9 +572,9 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
tag.pages[0][3] = 0x88;
}
*/
break;
}
break;
case 40:
case 40: {
if (g_dbglevel >= DBG_EXTENDED)
Dbprintf("WRITE");
//data received to be written
@ -535,6 +608,7 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
}
}
break;
}
case 20: {
//write page, write block, read page or read block command received
if ((rx[0] & 0xf0) == 0xc0) { //read page
@ -567,9 +641,12 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
sof_bits = 0;
*txlen = 0;
}
} else if ((rx[0] & 0xf0) == 0xd0) { //read block
uint8_t page = ((rx[0] & 0x0f) * 16) + ((rx[1] & 0xf0) / 16);
*txlen = 32 * 4;
//send page,...,page+3 data
for (int i = 0; i < 4; i++) {
tx[0 + i * 4] = tag.pages[page + 0 + i * 4][0];
@ -594,8 +671,11 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
sof_bits = 0;
*txlen = 0;
}
} else if ((rx[0] & 0xf0) == 0x80) { //write page
uint8_t page = ((rx[0] & 0x0f) * 16) + ((rx[1] & 0xf0) / 16);
if ((tag.LCON && page == 1)
|| (tag.LKP && (page == 2 || page == 3))) {
//deny
@ -609,8 +689,10 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
}
} else if ((rx[0] & 0xf0) == 0x90) { //write block
uint8_t page = ((rx[0] & 0x0f) * 6) + ((rx[1] & 0xf0) / 16);
hitagS_set_frame_modulation();
if (page % 4 != 0 || page == 0) {
//deny
*txlen = 0;
@ -623,12 +705,14 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen,
tag.tstate = HT_WRITING_BLOCK_DATA;
}
}
}
break;
default:
if (g_dbglevel >= DBG_EXTENDED)
Dbprintf("unknown rxlen: (%i) %02X %02X %02X %02X ...", rxlen, rx[0], rx[1], rx[2], rx[3]);
break;
}
default: {
if (g_dbglevel >= DBG_EXTENDED) {
Dbprintf("unknown rxlen: (%i) %02X %02X %02X %02X ...", rxlen, rx[0], rx[1], rx[2], rx[3]);
}
break;
}
}
}
@ -639,7 +723,6 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr
StopTicks();
// int frame_count = 0;
int response = 0, overflow = 0;
uint8_t rx[HITAG_FRAME_LEN];
size_t rxlen = 0;
@ -666,6 +749,7 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr
// read tag data into memory
if (tag_mem_supplied) {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 4; j++) {
tag.pages[i][j] = 0x0;
@ -700,7 +784,8 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr
tag.max_page = 0;
}
if (g_dbglevel >= DBG_EXTENDED)
if (g_dbglevel >= DBG_EXTENDED) {
for (int i = 0; i < tag.max_page; i++) {
Dbprintf("Page[%2d]: %02X %02X %02X %02X", i,
(tag.pages[i][3]) & 0xFF,
@ -709,6 +794,8 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr
tag.pages[i][0] & 0xFF
);
}
}
//con1
tag.auth = 0;
if ((tag.pages[1][1] & 0x80) == 0x80) {
@ -814,8 +901,10 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr
// Receive frame, watch for at most T0*EOF periods
while (AT91C_BASE_TC1->TC_CV < T0 * HITAG_T_EOF) {
// Check if rising edge in modulation is detected
if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
// Retrieve the new timing values
int ra = (AT91C_BASE_TC1->TC_RA / T0) + overflow;
overflow = 0;
@ -901,6 +990,7 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui
// Reset values for receiving frames
memset(rx, 0x00, sizeofrx);
*rxlen = 0;
int lastbit = 1;
bool bSkip = true;
*resptime = 0;
@ -914,8 +1004,8 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui
// Receive frame, watch for at most T0*EOF periods
while (AT91C_BASE_TC0->TC_CV + (overcount << 16) < (T0 * HITAG_T_PROG_MAX)) {
// detect and track counter overflows
// detect and track counter overflows
uint32_t tmpcv = AT91C_BASE_TC0->TC_CV;
if (tmpcv < prevcv) {
overcount++;
@ -924,10 +1014,13 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui
// Check if falling edge in tag modulation is detected
if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
// Retrieve the new timing values
uint32_t ra = (AT91C_BASE_TC1->TC_RA + (overcount << 16)) / T0;
// Reset timer every frame, we have to capture the last edge for timing
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
prevcv = 0;
overcount = 0;
@ -935,7 +1028,8 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui
// Capture tag frame (manchester decoding using only falling edges)
if (!bStarted) {
if (bStarted == false) {
if (ra >= HITAG_T_EOF) {
bStarted = true;
// Capture the T0 periods that have passed since last communication or field drop (reset)
@ -944,28 +1038,37 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui
} else {
errorCount++;
}
} else if (ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
// Manchester coding example |-_|_-|-_| (101)
rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8));
(*rxlen)++;
rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8));
(*rxlen)++;
} else if (ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
// Manchester coding example |_-|...|_-|-_| (0...01)
rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8));
(*rxlen)++;
// We have to skip this half period at start and add the 'one' the second time
if (!bSkip) {
if (bSkip == false) {
rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8));
(*rxlen)++;
}
lastbit = !lastbit;
bSkip = !bSkip;
} else if (ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
// Manchester coding example |_-|_-| (00) or |-_|-_| (11)
// bit is same as last bit
rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8));
(*rxlen)++;
} else {
// Ignore weird value, is to small to mean anything
errorCount++;
@ -973,11 +1076,13 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui
}
// if we saw over 100 weird values break it probably isn't hitag...
if (errorCount > 100) break;
if (errorCount > 100) {
break;
}
// We can break this loop if we received the last bit from a frame
if (AT91C_BASE_TC1->TC_CV > T0 * HITAG_T_EOF) {
if ((*rxlen) > 0) {
if (AT91C_BASE_TC1->TC_CV > (T0 * HITAG_T_EOF)) {
if ((*rxlen)) {
break;
}
}
@ -998,7 +1103,6 @@ static void sendReceiveHitagS(uint8_t *tx, size_t txlen, uint8_t *rx, size_t siz
// falling edge occurred halfway the period. with respect to this falling edge,
// we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'.
// All timer values are in terms of T0 units
while (AT91C_BASE_TC0->TC_CV < T0 * t_wait) {};
// Transmit the reader frame
@ -1011,48 +1115,82 @@ static void sendReceiveHitagS(uint8_t *tx, size_t txlen, uint8_t *rx, size_t siz
size_t rxlen = 0;
hitagS_receive_frame(rx, sizeofrx, &rxlen, &resptime, ledcontrol);
int k = 0;
// Check if frame was captured and store it
if (rxlen > 0) {
uint8_t response_bit[sizeofrx * 8];
for (int i = 0; i < rxlen; i++) {
for (size_t i = 0; i < rxlen; i++) {
response_bit[i] = (rx[i / 8] >> (7 - (i % 8))) & 1;
}
Dbprintf("htS: rxlen...... %zu", rxlen);
Dbprintf("htS: sizeofrx... %zu", sizeofrx);
memset(rx, 0x00, sizeofrx);
if (ac_seq) {
DbpString("htS: AntiCollision Sequence ( ac seq )");
Dbhexdump(rxlen, response_bit, false);
// Tag Response is AC encoded
// We used UID Request Advanced, meaning AC SEQ header is 111.
for (int i = 6; i < rxlen; i += 2) {
rx[k / 8] |= response_bit[i] << (7 - (k % 8));
k++;
if (k >= 8 * sizeofrx)
if (k > 8 * sizeofrx) {
break;
}
}
DbpString("htS: ac sequence compress");
Dbhexdump(k / 8, rx, false);
} else {
for (int i = 5; i < rxlen; i++) { // ignore first 5 bits: SOF (actually 1 or 6 depending on response protocol)
DbpString("htS: skipping 5 bit header");
// ignore first 5 bits: SOF (actually 1 or 6 depending on response protocol)
// or rather a header.
for (size_t i = 5; i < rxlen; i++) {
rx[k / 8] |= response_bit[i] << (7 - (k % 8));
k++;
if (k >= 8 * sizeofrx)
if (k > 8 * sizeofrx) {
break;
}
}
}
LogTraceBits(rx, k, resptime, resptime, false);
}
*prxbits = k;
}
static size_t concatbits(uint8_t *dstbuf, size_t dstbufskip, const uint8_t *srcbuf, size_t srcbufstart, size_t srcbuflen) {
static size_t concatbits(uint8_t *dst, size_t dstskip, const uint8_t *src, size_t srcstart, size_t srclen) {
// erase dstbuf bits that will be overriden
dstbuf[dstbufskip / 8] &= 0xFF - ((1 << (7 - (dstbufskip % 8) + 1)) - 1);
for (size_t i = (dstbufskip / 8) + 1; i <= (dstbufskip + srcbuflen) / 8; i++) {
dstbuf[i] = 0;
dst[dstskip / 8] &= 0xFF - ((1 << (7 - (dstskip % 8) + 1)) - 1);
for (size_t i = (dstskip / 8) + 1; i <= (dstskip + srclen) / 8; i++) {
dst[i] = 0;
}
for (size_t i = 0; i < srcbuflen; i++) {
for (size_t i = 0; i < srclen; i++) {
// equiv of dstbufbits[dstbufskip + i] = srcbufbits[srcbufstart + i]
dstbuf[(dstbufskip + i) / 8] |= ((srcbuf[(srcbufstart + i) / 8] >> (7 - ((srcbufstart + i) % 8))) & 1) << (7 - ((dstbufskip + i) % 8));
dst[(dstskip + i) / 8] |= ((src[(srcstart + i) / 8] >> (7 - ((srcstart + i) % 8))) & 1) << (7 - ((dstskip + i) % 8));
}
return dstbufskip + srcbuflen;
return dstskip + srclen;
}
static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, size_t sizeoftx, uint8_t *rx, size_t sizeofrx, int t_wait, bool ledcontrol) {
static int selectHitagS(const lf_hitag_data_t *packet, uint8_t *tx, size_t sizeoftx, uint8_t *rx, size_t sizeofrx, int t_wait, bool ledcontrol) {
StopTicks();
FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
@ -1075,50 +1213,28 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx,
// Disable modulation at default, which means enable the field
LOW(GPIO_SSC_DOUT);
// Enable Peripheral Clock for
// TIMER_CLOCK0, used to measure exact timing before answering
// TIMER_CLOCK1, used to capture edges of the tag frames
AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1);
hitagS_init_clock();
AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
// Disable timer during configuration
AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS;
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
// TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers
AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK;
// TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
// external trigger rising edge, load RA on falling edge of TIOA.
AT91C_BASE_TC1->TC_CMR =
AT91C_TC_CLKS_TIMER_DIV1_CLOCK |
AT91C_TC_ETRGEDG_FALLING |
AT91C_TC_ABETRG |
AT91C_TC_LDRA_FALLING;
// Enable and reset counters
AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
// synchronized startup procedure
while (AT91C_BASE_TC0->TC_CV > 0); // wait until TC0 returned to zero
//start authentication
// UID request standard 00110
// UID request Advanced 1100x
// UID request FAdvanced 11010
size_t txlen = 0;
size_t rxlen = 0;
uint8_t cmd = 0x18;
uint8_t cmd = 0x18; // 11000 UID Request Advanced
txlen = concatbits(tx, txlen, &cmd, 8 - 5, 5);
sendReceiveHitagS(tx, txlen, rx, sizeofrx, &rxlen, t_wait, ledcontrol, true);
if (rxlen != 32) {
Dbprintf("UID Request failed!");
DbpString("UID Request failed!");
return -1;
}
tag.uid = (rx[3] << 24 | rx[2] << 16 | rx[1] << 8 | rx[0]);
if (g_dbglevel >= DBG_EXTENDED)
if (g_dbglevel >= DBG_EXTENDED) {
Dbprintf("UID: %02X %02X %02X %02X", rx[0], rx[1], rx[2], rx[3]);
}
//select uid
txlen = 0;
cmd = 0x00;
@ -1165,25 +1281,29 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx,
tag.LCK1 = (conf_pages[2] >> 1) & 0x1;
tag.LCK0 = (conf_pages[2] >> 0) & 0x1;
if (g_dbglevel >= DBG_EXTENDED)
Dbprintf("conf0: %02X conf1: %02X conf2: %02X", conf_pages[0], conf_pages[1], conf_pages[2]);
if (g_dbglevel >= DBG_EXTENDED) {
Dbprintf("conf 0: %02X conf 1: %02X conf 2: %02X", conf_pages[0], conf_pages[1], conf_pages[2]);
}
if (tag.auth == 1) {
uint64_t key = 0;
//if the tag is in authentication mode try the key or challenge
if (htf == RHTSF_KEY || htf == WHTSF_KEY) {
if (packet->cmd == RHTSF_KEY || packet->cmd == WHTSF_KEY) {
if (g_dbglevel >= DBG_EXTENDED) {
DbpString("Authenticating using key:");
Dbhexdump(6, htd->crypto.key, false);
Dbhexdump(6, packet->key, false);
}
key = ((uint64_t)htd->crypto.key[0]) << 0 |
((uint64_t)htd->crypto.key[1]) << 8 |
((uint64_t)htd->crypto.key[2]) << 16 |
((uint64_t)htd->crypto.key[3]) << 24 |
((uint64_t)htd->crypto.key[4]) << 32 |
((uint64_t)htd->crypto.key[5]) << 40
key = ((uint64_t)packet->key[0]) << 0 |
((uint64_t)packet->key[1]) << 8 |
((uint64_t)packet->key[2]) << 16 |
((uint64_t)packet->key[3]) << 24 |
((uint64_t)packet->key[4]) << 32 |
((uint64_t)packet->key[5]) << 40
;
uint64_t state = ht2_hitag2_init(REV64(key), REV32(tag.uid), REV32(rnd));
uint8_t auth_ks[4];
for (int i = 0; i < 4; i++) {
auth_ks[i] = ht2_hitag2_byte(&state) ^ 0xff;
@ -1194,37 +1314,44 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx,
txlen = concatbits(tx, txlen, revrnd, 0, 32);
txlen = concatbits(tx, txlen, auth_ks, 0, 32);
if (g_dbglevel >= DBG_EXTENDED)
Dbprintf("%02X %02X %02X %02X %02X %02X %02X %02X", tx[0],
tx[1], tx[2], tx[3], tx[4], tx[5], tx[6], tx[7]);
if (g_dbglevel >= DBG_EXTENDED) {
Dbprintf("%02X %02X %02X %02X %02X %02X %02X %02X"
, tx[0], tx[1], tx[2], tx[3]
, tx[4], tx[5], tx[6], tx[7]
);
}
} else if (packet->cmd == RHTSF_CHALLENGE || packet->cmd == WHTSF_CHALLENGE) {
} else if (htf == RHTSF_CHALLENGE || htf == WHTSF_CHALLENGE) {
if (g_dbglevel >= DBG_EXTENDED) {
DbpString("Authenticating using nr,ar pair:");
Dbhexdump(8, htd->auth.NrAr, false);
Dbhexdump(8, packet->NrAr, false);
}
uint64_t NrAr = 0;
NrAr = ((uint64_t)htd->auth.NrAr[7]) << 0 |
((uint64_t)htd->auth.NrAr[6]) << 8 |
((uint64_t)htd->auth.NrAr[5]) << 16 |
((uint64_t)htd->auth.NrAr[4]) << 24 |
((uint64_t)htd->auth.NrAr[3]) << 32 |
((uint64_t)htd->auth.NrAr[2]) << 40 |
((uint64_t)htd->auth.NrAr[1]) << 48 |
((uint64_t)htd->auth.NrAr[0]) << 56;
NrAr = ((uint64_t)packet->NrAr[7]) << 0 |
((uint64_t)packet->NrAr[6]) << 8 |
((uint64_t)packet->NrAr[5]) << 16 |
((uint64_t)packet->NrAr[4]) << 24 |
((uint64_t)packet->NrAr[3]) << 32 |
((uint64_t)packet->NrAr[2]) << 40 |
((uint64_t)packet->NrAr[1]) << 48 |
((uint64_t)packet->NrAr[0]) << 56;
txlen = 64;
for (int i = 0; i < 8; i++) {
tx[i] = ((NrAr >> (56 - (i * 8))) & 0xFF);
}
} else {
Dbprintf("Error , unknown function: %d", htf);
Dbprintf("Error , unknown function: " _RED_("%d"), packet->cmd);
return -1;
}
sendReceiveHitagS(tx, txlen, rx, sizeofrx, &rxlen, t_wait, ledcontrol, false);
if (rxlen != 40) {
Dbprintf("Authenticate failed! %i", rxlen);
Dbprintf("Authenticate failed! " _RED_("%i"), rxlen);
return -1;
}
@ -1238,19 +1365,21 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx,
pwdh0 = 0;
pwdl0 = 0;
pwdl1 = 0;
if (htf == RHTSF_KEY || htf == WHTSF_KEY) {
if (packet->cmd == RHTSF_KEY || packet->cmd == WHTSF_KEY) {
uint64_t state = ht2_hitag2_init(REV64(key), REV32(tag.uid), REV32(rnd));
for (int i = 0; i < 4; i++) {
ht2_hitag2_byte(&state);
}
uint8_t con2 = rx[0] ^ ht2_hitag2_byte(&state);
pwdh0 = rx[1] ^ ht2_hitag2_byte(&state);
pwdl0 = rx[2] ^ ht2_hitag2_byte(&state);
pwdl1 = rx[3] ^ ht2_hitag2_byte(&state);
if (g_dbglevel >= DBG_EXTENDED)
if (g_dbglevel >= DBG_EXTENDED) {
Dbprintf("con2 %02X pwdh0 %02X pwdl0 %02X pwdl1 %02X", con2, pwdh0, pwdl0, pwdl1);
}
//Dbprintf("%X %02X", rnd, ((rx[4] & 0x0f) * 16) + ((rx[5] & 0xf0) / 16));
//rnd += 1;
}
@ -1263,21 +1392,26 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx,
* If the key was given the password will be decrypted.
* Reads every page of a hitag S transpoder.
*/
void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol) {
void ReadHitagS(const lf_hitag_data_t *payload, bool ledcontrol) {
uint8_t rx[HITAG_FRAME_LEN];
size_t rxlen = 0;
uint8_t tx[HITAG_FRAME_LEN];
int t_wait = HITAG_T_WAIT_MAX;
if (selectHitagS(payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) {
if (selectHitagS(htf, htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) {
hitagS_stop_clock();
set_tracing(false);
lf_finalize(ledcontrol);
reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
reply_ng(CMD_LF_HITAGS_READ, PM3_ERFTRANS, NULL, 0);
return;
}
int pageNum = 0;
while ((BUTTON_PRESS() == false) && (data_available() == false)) {
WDT_HIT();
@ -1319,18 +1453,18 @@ void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol) {
pageNum++;
//display key and password if possible
if (pageNum == 2 && tag.auth == 1 && tag.LKP) {
if (htf == RHTSF_KEY) {
if (payload->cmd == RHTSF_KEY) {
Dbprintf("Page[ 2]: %02X %02X %02X %02X",
htd->crypto.key[1],
htd->crypto.key[0],
payload->key[1],
payload->key[0],
pwdl1,
pwdl0
);
Dbprintf("Page[ 3]: %02X %02X %02X %02X",
htd->crypto.key[5],
htd->crypto.key[4],
htd->crypto.key[3],
htd->crypto.key[2]
payload->key[5],
payload->key[4],
payload->key[3],
payload->key[2]
);
} else {
//if the authentication is done with a challenge the key and password are unknown
@ -1344,78 +1478,89 @@ void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol) {
break;
}
}
hitagS_stop_clock();
set_tracing(false);
lf_finalize(ledcontrol);
// TODO reply_mix(CMD_ACK, 1, 0, 0, 0, 0); and send dump as well, to be decoded in the client
reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
reply_ng(CMD_LF_HITAGS_READ, PM3_SUCCESS, (uint8_t *)tag.pages, sizeof(tag.pages));
}
/*
* Authenticates to the Tag with the given Key or Challenge.
* Writes the given 32Bit data into page_
*/
void WritePageHitagS(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol) {
void WritePageHitagS(const lf_hitag_data_t *payload, bool ledcontrol) {
bool bSuccessful = false;
//check for valid input
if (page == 0) {
if (payload->page == 0) {
Dbprintf("Error, invalid page");
reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0);
reply_ng(CMD_LF_HITAGS_WRITE, PM3_EINVARG, NULL, 0);
return;
}
uint8_t rx[HITAG_FRAME_LEN];
size_t rxlen = 0;
uint8_t tx[HITAG_FRAME_LEN];
size_t txlen = 0;
int t_wait = HITAG_T_WAIT_MAX;
if (selectHitagS(htf, htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) {
int res = PM3_ESOFT;
if (selectHitagS(payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) {
res = PM3_ERFTRANS;
goto write_end;
}
//check if the given page exists
if (page > tag.max_page) {
Dbprintf("page number too big for this tag");
if (payload->page > tag.max_page) {
Dbprintf("Error, page number too large");
res = PM3_EINVARG;
goto write_end;
}
//send write page request
txlen = 0;
uint8_t cmd = 0x08;
txlen = concatbits(tx, txlen, &cmd, 8 - 4, 4);
uint8_t addr = page;
uint8_t addr = payload->page;
txlen = concatbits(tx, txlen, &addr, 0, 8);
uint8_t crc = CRC8Hitag1Bits(tx, txlen);
txlen = concatbits(tx, txlen, &crc, 0, 8);
sendReceiveHitagS(tx, txlen, rx, ARRAYLEN(rx), &rxlen, t_wait, ledcontrol, false);
if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x1)) {
Dbprintf("no write access on page %d", page);
Dbprintf("no write access on page " _YELLOW_("%d"), payload->page);
res = PM3_ESOFT;
goto write_end;
}
//ACK received to write the page. send data
uint8_t data[4] = {0, 0, 0, 0};
switch (htf) {
switch (payload->cmd) {
case WHTSF_CHALLENGE:
data[0] = htd->auth.data[3];
data[1] = htd->auth.data[2];
data[2] = htd->auth.data[1];
data[3] = htd->auth.data[0];
data[0] = payload->data[3];
data[1] = payload->data[2];
data[2] = payload->data[1];
data[3] = payload->data[0];
break;
case WHTSF_KEY:
data[0] = htd->crypto.data[3];
data[1] = htd->crypto.data[2];
data[2] = htd->crypto.data[1];
data[3] = htd->crypto.data[0];
data[0] = payload->data[3];
data[1] = payload->data[2];
data[2] = payload->data[1];
data[3] = payload->data[0];
break;
default:
default: {
res = PM3_EINVARG;
return;
}
}
txlen = 0;
txlen = concatbits(tx, txlen, data, 0, 32);
crc = CRC8Hitag1Bits(tx, txlen);
@ -1424,16 +1569,16 @@ void WritePageHitagS(hitag_function htf, const hitag_data *htd, int page, bool l
sendReceiveHitagS(tx, txlen, rx, ARRAYLEN(rx), &rxlen, t_wait, ledcontrol, false);
if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x1)) {
Dbprintf("write on page %d failed", page);
res = PM3_ESOFT; // write failed
} else {
Dbprintf("write on page %d successful", page);
bSuccessful = true;
res = PM3_SUCCESS;
}
write_end:
hitagS_stop_clock();
set_tracing(false);
lf_finalize(ledcontrol);
reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0);
reply_ng(CMD_LF_HITAGS_WRITE, res, NULL, 0);
}
/*
@ -1444,10 +1589,11 @@ write_end:
* detects these challenges.
*/
void Hitag_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontrol) {
//check for valid input
if (datalen < 8) {
Dbprintf("Error, need chals");
reply_mix(CMD_ACK, 0, 0, 0, 0, 0);
Dbprintf("Error, missing challenges");
reply_ng(CMD_LF_HITAGS_TEST_TRACES, PM3_EINVARG, NULL, 0);
return;
}
uint32_t dataoffset = 0;
@ -1460,38 +1606,42 @@ void Hitag_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontr
// Watchdog hit
WDT_HIT();
hitag_data htd;
memset(&htd, 0, sizeof(htd));
lf_hitag_data_t payload;
memset(&payload, 0, sizeof(payload));
payload.cmd = RHTSF_CHALLENGE;
memcpy(htd.auth.NrAr, data + dataoffset, 8);
memcpy(payload.NrAr, data + dataoffset, 8);
int res = selectHitagS(RHTSF_CHALLENGE, &htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol);
int res = selectHitagS(&payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol);
Dbprintf("Challenge %s: %02X %02X %02X %02X %02X %02X %02X %02X",
res == -1 ? "failed " : "success",
htd.auth.NrAr[0], htd.auth.NrAr[1],
htd.auth.NrAr[2], htd.auth.NrAr[3],
htd.auth.NrAr[4], htd.auth.NrAr[5],
htd.auth.NrAr[6], htd.auth.NrAr[7]
payload.NrAr[0], payload.NrAr[1],
payload.NrAr[2], payload.NrAr[3],
payload.NrAr[4], payload.NrAr[5],
payload.NrAr[6], payload.NrAr[7]
);
if (res == -1) {
// Need to do a dummy UID select that will fail
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
SpinDelay(2);
selectHitagS(RHTSF_CHALLENGE, &htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol);
selectHitagS(&payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol);
}
dataoffset += 8;
if (dataoffset >= datalen - 8)
if (dataoffset >= datalen - 8) {
break;
}
// reset field
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
// min t_reset = 2ms
SpinDelay(2);
}
hitagS_stop_clock();
set_tracing(false);
lf_finalize(ledcontrol);
reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
reply_ng(CMD_ACK, PM3_SUCCESS, NULL, 0);
return;
}

View file

@ -22,11 +22,10 @@
#define _HITAGS_H_
#include "common.h"
#include "hitag.h"
void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontrol);
void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol);
void WritePageHitagS(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol);
void ReadHitagS(const lf_hitag_data_t *payload, bool ledcontrol);
void WritePageHitagS(const lf_hitag_data_t *payload, bool ledcontrol);
void Hitag_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontrol);
#endif

View file

@ -2941,14 +2941,11 @@ void SetTag15693Uid_v2(const uint8_t *uid) {
{ ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x47, 0x3f, 0x03, 0x8b, 0x00, 0x00, 0x00 },
{ ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
// hf 15 raw -wac -d 02 e0 09 41 + uid first four bytes
{ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x41, uid[7], uid[6], uid[5], uid[4], 0x00, 0x00},
{ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x40, uid[7], uid[6], uid[5], uid[4], 0x00, 0x00},
// hf 15 raw -wac -d 02 e0 09 40 + uid last four bytes
{ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x40, uid[3], uid[2], uid[1], uid[0], 0x00, 0x00}
{ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x41, uid[3], uid[2], uid[1], uid[0], 0x00, 0x00}
};
AddCrc15(cmd[0], 8);
AddCrc15(cmd[1], 8);
uint8_t buf[ISO15693_MAX_RESPONSE_LENGTH] = {0x00};
uint32_t start_time = 0;
@ -2958,6 +2955,8 @@ void SetTag15693Uid_v2(const uint8_t *uid) {
int res = PM3_SUCCESS;
for (int i = 0; i < 4; i++) {
AddCrc15(cmd[i], 8);
res = SendDataTag(
cmd[i],
sizeof(cmd[i]),

View file

@ -91,7 +91,7 @@ int hex2binarray_n(char *target, char *source, int sourcelen) {
// process 4 bits (1 hex digit) at a time
while (sourcelen--) {
char x = *(source++);
*(target++) = (x >> 7) & 1;
@ -102,7 +102,7 @@ int hex2binarray_n(char *target, char *source, int sourcelen) {
*(target++) = (x >> 2) & 1;
*(target++) = (x >> 1) & 1;
*(target++) = (x & 1);
count += 8;
}
return count;
@ -122,9 +122,9 @@ int binarray2hex(const uint8_t *bs, int bs_len, uint8_t *hex) {
if (bs[i] == 1) {
hex[byte_index] |= (1 << (7 - (count % 8)));
}
count++;
// Move to the next byte if 8 bits have been filled
if (count % 8 == 0) {
byte_index++;

View file

@ -263,6 +263,7 @@ set (TARGET_SOURCES
${PM3_ROOT}/common/cardhelper.c
${PM3_ROOT}/common/generator.c
${PM3_ROOT}/common/bruteforce.c
${PM3_ROOT}/common/hitag2/hitag2_crypto.c
${PM3_ROOT}/client/src/crypto/asn1dump.c
${PM3_ROOT}/client/src/crypto/asn1utils.c
${PM3_ROOT}/client/src/crypto/libpcrypto.c

View file

@ -1,13 +1,25 @@
#
# Mifare Default Keys
# -- Iceman version --
# -- contribute to this list, sharing is caring --
#
# Lets see how long it takes before other project takes this file
# and claim they created it.
#
# factory HT2 pwd
4D494B52
# factory HT2 crypto key
4F4E4D494B52
#
# GE HT2 reader
#
# TSPL
5453504C
05040202
25293C2F
# Gone in 360 seconds
FFFF814632FF
#
# Paxton HT2
BDF5E846
#
#
# GE HT2 reader
# TSPL
5453504C
05040202
25293C2F

View file

@ -125,4 +125,4 @@ local function main(args)
end
end
main(args)
main(args)

View file

@ -1719,12 +1719,12 @@ static int CmdSetGraphMarkers(const char *Cmd) {
g_MarkerC.pos = arg_get_u32_def(ctx, 4, (keep ? g_MarkerC.pos : 0));
g_MarkerD.pos = arg_get_u32_def(ctx, 5, (keep ? g_MarkerD.pos : 0));
CLIParserFree(ctx);
PrintAndLogEx(INFO, "Setting markers " _BRIGHT_YELLOW_("A") "=%u, "_BRIGHT_MAGENTA_("B") "=%u, "_RED_("C") "=%u, "_BLUE_("D") "=%u",
g_MarkerA.pos,
g_MarkerB.pos,
g_MarkerC.pos,
g_MarkerD.pos
);
PrintAndLogEx(INFO, "Setting markers " _BRIGHT_YELLOW_("A") "=%u, "_BRIGHT_MAGENTA_("B") "=%u, "_RED_("C") "=%u, "_BLUE_("D") "=%u",
g_MarkerA.pos,
g_MarkerB.pos,
g_MarkerC.pos,
g_MarkerD.pos
);
RepaintGraphWindow();
return PM3_SUCCESS;
}
@ -3847,7 +3847,7 @@ static command_t CommandTable[] = {
{"save", CmdSave, AlwaysAvailable, "Save signal trace data"},
{"setdebugmode", CmdSetDebugMode, AlwaysAvailable, "Set Debugging Level on client side"},
{"xor", CmdXor, AlwaysAvailable, "Xor a input string"},
{"-----------", CmdHelp, AlwaysAvailable, "------------------------- " _CYAN_("Modulation") "-------------------------"},
{"biphaserawdecode", CmdBiphaseDecodeRaw, AlwaysAvailable, "Biphase decode bin stream in DemodBuffer"},
{"detectclock", CmdDetectClockRate, AlwaysAvailable, "Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer"},

View file

@ -2737,7 +2737,7 @@ static int CmdHF15CSetUID(const char *Cmd) {
"Set UID for magic Chinese card (only works with such cards)\n",
"hf 15 csetuid -u E011223344556677 -> use gen1 command\n"
"hf 15 csetuid -u E011223344556677 --v2 -> use gen2 command"
);
);
void *argtable[] = {
arg_param_begin,

View file

@ -355,7 +355,7 @@ static int CmdHFMFPInfo(const char *Cmd) {
if (supportVersion) {
int cardtype = getCardType(version[1], version[3], version[4]);
switch(cardtype) {
switch (cardtype) {
case PLUS_EV1: {
if (supportSignature) {
PrintAndLogEx(INFO, "Tech..... " _GREEN_("MIFARE Plus EV1"));

File diff suppressed because it is too large Load diff

View file

@ -22,6 +22,7 @@
#include "common.h"
#define HITAG_NRAR_SIZE 8
#define HITAG_CRYPTOKEY_SIZE 6
#define HITAG_PASSWORD_SIZE 4
#define HITAG_UID_SIZE 4
@ -37,16 +38,18 @@
#define HITAG2_CONFIG_BLOCK 3
#define HITAG2_CONFIG_OFFSET (HITAG_BLOCK_SIZE * HITAG2_CONFIG_BLOCK)
#define HITAG_DICTIONARY "ht2_default"
int CmdLFHitag(const char *Cmd);
int readHitagUid(void);
void annotateHitag1(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, bool is_response);
void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits, bool is_response);
void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits, bool is_response, const uint64_t *keys, uint32_t keycount, bool isdecrypted);
void annotateHitagS(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, bool is_response);
void annotateHitag2_init(void);
bool hitag2_get_plain(uint8_t *plain, uint8_t *plen);
void hitag2_annotate_plain(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits);
uint8_t hitag1_CRC_check(uint8_t *d, uint32_t nbit);
#endif

View file

@ -501,7 +501,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
uint32_t end_of_transmission_timestamp = 0;
uint8_t topaz_reader_command[9];
char explanation[40] = {0};
char explanation[60] = {0};
tracelog_hdr_t *first_hdr = (tracelog_hdr_t *)(trace);
tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos);
@ -774,10 +774,9 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
end_of_transmission_timestamp = hdr->timestamp + duration;
if (prev_eot)
if (prev_eot) {
*prev_eot = end_of_transmission_timestamp;
}
// Always annotate these protocols both reader/tag messages
switch (protocol) {
@ -793,7 +792,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
annotateHitag1(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
break;
case PROTO_HITAG2:
annotateHitag2(explanation, sizeof(explanation), frame, data_len, parityBytes[0], hdr->isResponse);
annotateHitag2(explanation, sizeof(explanation), frame, data_len, parityBytes[0], hdr->isResponse, mfDicKeys, mfDicKeysCount, false);
break;
case PROTO_HITAGS:
annotateHitagS(explanation, sizeof(explanation), frame, data_len, hdr->isResponse);
@ -979,6 +978,71 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
}
}
if (protocol == PROTO_HITAG2) {
uint8_t ht2plain[9] = {0};
uint8_t n = 0;
if (hitag2_get_plain(ht2plain, &n)) {
memset(explanation, 0x00, sizeof(explanation));
// handle partial bytes. The parity array[0] is used to store number of left over bits from NBYTES
// This part prints the number of bits in the trace entry for hitag.
uint8_t nbits = parityBytes[0];
annotateHitag2(explanation, sizeof(explanation), ht2plain, n, nbits, hdr->isResponse, NULL, 0, true);
// iceman: colorise crc bytes here will need a refactor of code from above.
for (int j = 0; j < n && (j / TRACE_MAX_HEX_BYTES) < TRACE_MAX_HEX_BYTES; j++) {
if (j == 0) {
// only apply this to lesser than one byte
if (n == 1) {
if (nbits == 5) {
snprintf(line[0], 120, "%2u: %02X ", nbits, ht2plain[0] >> (8 - nbits));
} else {
snprintf(line[0], 120, "%2u: %02X ", nbits, ht2plain[0] >> (8 - nbits));
}
} else {
if (nbits == 0) {
snprintf(line[0], 120, "%2u: %02X ", (n * 8), ht2plain[0]);
} else {
snprintf(line[0], 120, "%2u: %02X ", ((n - 1) * 8) + nbits, ht2plain[0]);
}
}
offset = 4;
} else {
snprintf(line[j / 18] + ((j % 18) * 4) + offset, 120, "%02X ", ht2plain[j]);
}
}
num_lines = MIN((n - 1) / TRACE_MAX_HEX_BYTES + 1, TRACE_MAX_HEX_BYTES);
for (int j = 0; j < num_lines ; j++) {
if (hdr->isResponse) {
PrintAndLogEx(NORMAL, " | | * |%-*s | %-4s| %s",
str_padder,
line[j],
" ",
explanation);
} else {
PrintAndLogEx(NORMAL, " | | * |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"),
str_padder,
line[j],
" ",
explanation);
}
}
}
}
if (is_last_record(tracepos, traceLen)) {
return traceLen;
}
@ -1436,6 +1500,30 @@ int CmdTraceList(const char *Cmd) {
}
}
if (protocol == PROTO_HITAG2) {
if (strlen(dictionary) == 0) {
snprintf(dictionary, sizeof(dictionary), HITAG_DICTIONARY);
}
// load keys
uint8_t *keyBlock = NULL;
int res = loadFileDICTIONARY_safe(dictionary, (void **) &keyBlock, HITAG_CRYPTOKEY_SIZE, &dicKeysCount);
if (res != PM3_SUCCESS || dicKeysCount == 0 || keyBlock == NULL) {
PrintAndLogEx(FAILED, "An error occurred while loading the dictionary!");
} else {
dicKeys = calloc(dicKeysCount, sizeof(uint64_t));
for (int i = 0; i < dicKeysCount; i++) {
uint64_t key = bytes_to_num(keyBlock + i * HITAG_CRYPTOKEY_SIZE, HITAG_CRYPTOKEY_SIZE);
memcpy((uint8_t *) &dicKeys[i], &key, sizeof(uint64_t));
}
dictionaryLoad = true;
}
if (keyBlock != NULL) {
free(keyBlock);
}
}
PrintAndLogEx(NORMAL, "");
if (use_relative) {
PrintAndLogEx(NORMAL, " Gap | Duration | Src | Data (! denotes parity error, ' denotes short bytes) | CRC | Annotation");
@ -1463,16 +1551,19 @@ int CmdTraceList(const char *Cmd) {
while (tracepos < gs_traceLen) {
tracepos = printTraceLine(tracepos, gs_traceLen, gs_trace, protocol, show_wait_cycles, mark_crc, prev_EOT, use_us, dicKeys, dicKeysCount);
if (kbd_enter_pressed())
if (kbd_enter_pressed()) {
break;
}
}
if (dictionaryLoad)
if (dictionaryLoad) {
free((void *) dicKeys);
}
}
if (show_hex)
if (show_hex) {
PrintAndLogEx(HINT, "syntax to use: " _YELLOW_("`text2pcap -t \"%%S.\" -l 264 -n <input-text-file> <output-pcapng-file>`"));
}
return PM3_SUCCESS;
}

View file

@ -127,34 +127,38 @@ void des3_decrypt(void *out, const void *in, const void *key, uint8_t keycount)
// NIST Special Publication 800-38A — Recommendation for block cipher modes of operation: methods and techniques, 2001.
int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length) {
uint8_t iiv[16] = {0};
if (iv)
if (iv) {
memcpy(iiv, iv, 16);
}
mbedtls_aes_context aes;
mbedtls_aes_init(&aes);
if (mbedtls_aes_setkey_enc(&aes, key, 128))
if (mbedtls_aes_setkey_enc(&aes, key, 128)) {
return 1;
if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, length, iiv, input, output))
}
if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, length, iiv, input, output)) {
return 2;
}
mbedtls_aes_free(&aes);
return 0;
return PM3_SUCCESS;
}
int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length) {
uint8_t iiv[16] = {0};
if (iv)
if (iv) {
memcpy(iiv, iv, 16);
}
mbedtls_aes_context aes;
mbedtls_aes_init(&aes);
if (mbedtls_aes_setkey_dec(&aes, key, 128))
if (mbedtls_aes_setkey_dec(&aes, key, 128)) {
return 1;
if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, length, iiv, input, output))
}
if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, length, iiv, input, output)) {
return 2;
}
mbedtls_aes_free(&aes);
return 0;
return PM3_SUCCESS;
}
// NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication.
@ -171,13 +175,14 @@ int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int lengt
memset(mac, 0x00, 8);
int res = aes_cmac(iv, key, input, cmac_tmp, length);
if (res)
if (res) {
return res;
}
for (int i = 0; i < 8; i++)
for (int i = 0; i < 8; i++) {
mac[i] = cmac_tmp[i * 2 + 1];
return 0;
}
return PM3_SUCCESS;
}
static uint8_t fixed_rand_value[250] = {0};
@ -188,21 +193,23 @@ static int fixed_rand(void *rng_state, unsigned char *output, size_t len) {
memset(output, 0x00, len);
}
return 0;
return PM3_SUCCESS;
}
int sha1hash(uint8_t *input, int length, uint8_t *hash) {
if (!hash || !input)
if (!hash || !input) {
return 1;
}
mbedtls_sha1(input, length, hash);
return 0;
return PM3_SUCCESS;
}
int sha256hash(uint8_t *input, int length, uint8_t *hash) {
if (!hash || !input)
if (!hash || !input) {
return 1;
}
mbedtls_sha256_context sctx;
mbedtls_sha256_init(&sctx);
@ -211,12 +218,13 @@ int sha256hash(uint8_t *input, int length, uint8_t *hash) {
mbedtls_sha256_finish(&sctx, hash);
mbedtls_sha256_free(&sctx);
return 0;
return PM3_SUCCESS;
}
int sha512hash(uint8_t *input, int length, uint8_t *hash) {
if (!hash || !input)
if (!hash || !input) {
return 1;
}
mbedtls_sha512_context sctx;
mbedtls_sha512_init(&sctx);
@ -225,33 +233,35 @@ int sha512hash(uint8_t *input, int length, uint8_t *hash) {
mbedtls_sha512_finish(&sctx, hash);
mbedtls_sha512_free(&sctx);
return 0;
return PM3_SUCCESS;
}
static int ecdsa_init_str(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id curveid, const char *key_d, const char *key_x, const char *key_y) {
if (!ctx)
if (!ctx) {
return 1;
int res;
}
mbedtls_ecdsa_init(ctx);
res = mbedtls_ecp_group_load(&ctx->grp, curveid);
if (res)
int res = mbedtls_ecp_group_load(&ctx->grp, curveid);
if (res) {
return res;
}
if (key_d) {
res = mbedtls_mpi_read_string(&ctx->d, 16, key_d);
if (res)
if (res) {
return res;
}
}
if (key_x && key_y) {
res = mbedtls_ecp_point_read_string(&ctx->Q, 16, key_x, key_y);
if (res)
if (res) {
return res;
}
}
return 0;
return PM3_SUCCESS;
}
static int ecdsa_init(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id curveid, uint8_t *key_d, uint8_t *key_xy) {
@ -278,7 +288,7 @@ static int ecdsa_init(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id curveid,
return res;
}
return 0;
return PM3_SUCCESS;
}
int ecdsa_key_create(mbedtls_ecp_group_id curveid, uint8_t *key_d, uint8_t *key_xy) {
@ -519,8 +529,9 @@ int ecdsa_nist_test(bool verbose) {
size_t siglen = 0;
// NIST ecdsa test
if (verbose)
PrintAndLogEx(INFO, " ECDSA NIST test: " NOLF);
if (verbose) {
PrintAndLogEx(INFO, "ECDSA NIST test " NOLF);
}
// make signature
res = ecdsa_signature_create_test(curveid, T_PRIVATE_KEY, T_Q_X, T_Q_Y, T_K, input, length, signature, &siglen);
// PrintAndLogEx(INFO, "res: %x signature[%x]: %s", (res < 0)? -res : res, siglen, sprint_hex(signature, siglen));
@ -540,15 +551,16 @@ int ecdsa_nist_test(bool verbose) {
uint8_t sval_s[33] = {0};
param_gethex_to_eol(T_S, 0, sval_s, sizeof(sval_s), &slen);
if (strncmp((char *)rval, (char *)rval_s, 32) || strncmp((char *)sval, (char *)sval_s, 32)) {
PrintAndLogEx(INFO, "R or S check error");
PrintAndLogEx(NORMAL, "( " _RED_("R or S check error") " )");
res = 100;
goto exit;
}
// verify signature
res = ecdsa_signature_verify_keystr(curveid, T_Q_X, T_Q_Y, input, length, signature, siglen, true);
if (res)
if (res) {
goto exit;
}
// verify wrong signature
input[0] ^= 0xFF;
@ -559,8 +571,8 @@ int ecdsa_nist_test(bool verbose) {
}
if (verbose) {
PrintAndLogEx(NORMAL, _GREEN_("passed"));
PrintAndLogEx(INFO, " ECDSA binary signature create/check test: " NOLF);
PrintAndLogEx(NORMAL, "( " _GREEN_("ok") " )");
PrintAndLogEx(INFO, "ECDSA binary signature create/check test " NOLF);
}
// random ecdsa test
@ -587,12 +599,12 @@ int ecdsa_nist_test(bool verbose) {
goto exit;
if (verbose)
PrintAndLogEx(NORMAL, _GREEN_("passed\n"));
PrintAndLogEx(NORMAL, "( " _GREEN_("ok") " )");
return PM3_SUCCESS;
exit:
if (verbose)
PrintAndLogEx(NORMAL, _RED_("failed\n"));
PrintAndLogEx(NORMAL, "( " _RED_("fail") " )");
return res;
}

View file

@ -136,7 +136,7 @@ size_t getFromGraphBufferEx(uint8_t *dest, size_t maxLen) {
}
//TODO: In progress function to get chunks of data from the GB w/o modifying the GB
//Currently seems like it doesn't work correctly?
//Currently seems like it doesn't work correctly?
size_t getGraphBufferChunk(uint8_t *dest, size_t start, size_t end) {
if (dest == NULL) return 0;
if (g_GraphTraceLen == 0) return 0;

View file

@ -742,7 +742,7 @@ static int DesfireExchangeISONative(bool activate_field, DesfireContext_t *ctx,
pos += buflen;
if (enable_chaining == false) {
if (sw == DESFIRE_GET_ISO_STATUS(MFDES_S_OPERATION_OK) ||
sw == DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) {
sw == DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) {
if (resplen) {
*resplen = pos;

View file

@ -626,13 +626,13 @@ static void DesfireSecureChannelDecodeEV1(DesfireContext_t *ctx, uint8_t *srcdat
PrintAndLogEx(INFO, " calculated MAC: %s", sprint_hex(cmac, DesfireGetMACLength(ctx)));
} else {
if (GetAPDULogging()) {
PrintAndLogEx(INFO, "Received MAC OK");
}
}
} else if (ctx->commMode == DCMEncrypted || ctx->commMode == DCMEncryptedWithPadding) {
} else if (ctx->commMode == DCMEncrypted || ctx->commMode == DCMEncryptedWithPadding) {
if (srcdatalen < desfire_get_key_block_length(ctx->keyType)) {
memcpy(dstdata, srcdata, srcdatalen);

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -75,6 +75,15 @@ const static vocabulary_t vocabulary[] = {
{ 1, "analyse foo" },
{ 1, "analyse units" },
{ 1, "data help" },
{ 1, "data clear" },
{ 1, "data hide" },
{ 1, "data load" },
{ 1, "data num" },
{ 1, "data plot" },
{ 1, "data print" },
{ 1, "data save" },
{ 1, "data setdebugmode" },
{ 1, "data xor" },
{ 1, "data biphaserawdecode" },
{ 1, "data detectclock" },
{ 1, "data fsktonrz" },
@ -83,43 +92,32 @@ const static vocabulary_t vocabulary[] = {
{ 1, "data rawdemod" },
{ 1, "data askedgedetect" },
{ 1, "data autocorr" },
{ 1, "data convertbitstream" },
{ 1, "data cthreshold" },
{ 1, "data dirthreshold" },
{ 1, "data decimate" },
{ 1, "data envelope" },
{ 1, "data undecimate" },
{ 1, "data hide" },
{ 1, "data grid" },
{ 1, "data getbitstream" },
{ 1, "data hpf" },
{ 1, "data iir" },
{ 1, "data grid" },
{ 1, "data ltrim" },
{ 1, "data mtrim" },
{ 1, "data norm" },
{ 1, "data plot" },
{ 1, "data cthreshold" },
{ 1, "data rtrim" },
{ 1, "data setgraphmarkers" },
{ 1, "data shiftgraphzero" },
{ 1, "data timescale" },
{ 1, "data undecimate" },
{ 1, "data zerocrossings" },
{ 1, "data convertbitstream" },
{ 1, "data getbitstream" },
{ 1, "data asn1" },
{ 1, "data atr" },
{ 1, "data bin2hex" },
{ 0, "data bitsamples" },
{ 1, "data bmap" },
{ 1, "data clear" },
{ 1, "data crypto" },
{ 1, "data diff" },
{ 0, "data hexsamples" },
{ 1, "data hex2bin" },
{ 1, "data load" },
{ 1, "data num" },
{ 1, "data print" },
{ 0, "data samples" },
{ 1, "data save" },
{ 1, "data setdebugmode" },
{ 1, "data xor" },
{ 1, "emv help" },
{ 1, "emv list" },
{ 1, "emv test" },
@ -558,11 +556,11 @@ const static vocabulary_t vocabulary[] = {
{ 0, "lf sniff" },
{ 0, "lf tune" },
{ 1, "lf awid help" },
{ 0, "lf awid brute" },
{ 0, "lf awid clone" },
{ 1, "lf awid demod" },
{ 0, "lf awid reader" },
{ 0, "lf awid clone" },
{ 0, "lf awid sim" },
{ 0, "lf awid brute" },
{ 0, "lf awid watch" },
{ 1, "lf cotag help" },
{ 1, "lf cotag demod" },
@ -647,16 +645,19 @@ const static vocabulary_t vocabulary[] = {
{ 1, "lf hitag help" },
{ 1, "lf hitag list" },
{ 0, "lf hitag info" },
{ 1, "lf hitag selftest" },
{ 0, "lf hitag dump" },
{ 0, "lf hitag read" },
{ 0, "lf hitag sniff" },
{ 1, "lf hitag view" },
{ 0, "lf hitag wrbl" },
{ 0, "lf hitag sniff" },
{ 0, "lf hitag cc" },
{ 0, "lf hitag ta" },
{ 0, "lf hitag eload" },
{ 0, "lf hitag eview" },
{ 0, "lf hitag sim" },
{ 0, "lf hitag cc" },
{ 0, "lf hitag chk" },
{ 1, "lf hitag lookup" },
{ 0, "lf hitag ta" },
{ 1, "lf idteck help" },
{ 1, "lf idteck demod" },
{ 0, "lf idteck reader" },

View file

@ -138,12 +138,12 @@ extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, char
}
void add_temporary_marker(uint32_t position, const char *label) {
if(g_TempMarkerSize == 0) { //Initialize the marker array
g_TempMarkers = (marker_t*)calloc(1, sizeof(marker_t));
if (g_TempMarkerSize == 0) { //Initialize the marker array
g_TempMarkers = (marker_t *)calloc(1, sizeof(marker_t));
} else { //add more space to the marker array using realloc()
marker_t *temp = (marker_t*)realloc(g_TempMarkers, ((g_TempMarkerSize + 1) * sizeof(marker_t)));
marker_t *temp = (marker_t *)realloc(g_TempMarkers, ((g_TempMarkerSize + 1) * sizeof(marker_t)));
if(temp == NULL) { //Unable to reallocate memory for a new marker
if (temp == NULL) { //Unable to reallocate memory for a new marker
PrintAndLogEx(FAILED, "Unable to allocate memory for a new temporary marker!");
free(temp);
return;
@ -155,10 +155,10 @@ void add_temporary_marker(uint32_t position, const char *label) {
g_TempMarkers[g_TempMarkerSize].pos = position;
char *markerLabel = (char*)calloc(1, strlen(label) + 1);
char *markerLabel = (char *)calloc(1, strlen(label) + 1);
strcpy(markerLabel, label);
if(strlen(markerLabel) > 30) {
if (strlen(markerLabel) > 30) {
PrintAndLogEx(WARNING, "Label for temporary marker too long! Trunicating...");
markerLabel[30] = '\0';
}
@ -171,7 +171,7 @@ void add_temporary_marker(uint32_t position, const char *label) {
}
void remove_temporary_markers(void) {
if(g_TempMarkerSize == 0) return;
if (g_TempMarkerSize == 0) return;
memset(g_TempMarkers, 0x00, (g_TempMarkerSize * sizeof(marker_t)));
free(g_TempMarkers);

View file

@ -598,7 +598,7 @@ void Plot::setMaxAndStart(int *buffer, size_t len, QRect plotRect) {
}
void Plot::appendMax(int *buffer, size_t len, QRect plotRect) {
if(len == 0) {
if (len == 0) {
return;
}
@ -750,12 +750,12 @@ void Plot::PlotGraph(int *buffer, size_t len, QRect plotRect, QRect annotationRe
painter->drawPath(penPath);
char str[200];
snprintf(str, sizeof(str), "max=%d min=%d mean=%" PRId64 " n=%u/%zu",
vMax,
vMin,
vMean,
g_GraphStop - g_GraphStart,
len
);
vMax,
vMin,
vMean,
g_GraphStop - g_GraphStart,
len
);
painter->drawText(20, annotationRect.bottom() - (48 - (12 * graphNum)), str);
}
@ -781,37 +781,37 @@ void Plot::drawAnnotations(QRect annotationRect, QPainter *painter) {
//Print the Graph Information
char graphText[] = "@%u..%u dt=%i %s zoom=%2.3f";
length = ((sizeof(graphText))+(sizeof(uint32_t)*3)+sizeof(scalestr)+sizeof(float_t));
length = ((sizeof(graphText)) + (sizeof(uint32_t) * 3) + sizeof(scalestr) + sizeof(float_t));
annotation = (char*)calloc(1, length);
annotation = (char *)calloc(1, length);
snprintf(annotation, length, graphText,
g_GraphStart,
g_GraphStop,
g_MarkerB.pos - g_MarkerA.pos,
scalestr,
g_GraphPixelsPerPoint
);
g_GraphStart,
g_GraphStop,
g_MarkerB.pos - g_MarkerA.pos,
scalestr,
g_GraphPixelsPerPoint
);
painter->setPen(GREEN);
painter->drawText(82, annotationRect.bottom() - 62, annotation);
//Print Grid Information if the grid is enabled
if(g_PlotGridX > 0) {
if (g_PlotGridX > 0) {
free(annotation);
const char *gridLocked = (g_GridLocked ? "Locked" : "Unlocked");
char gridText[] = "GridX=%lf GridY=%lf (%s) GridXoffset=%lf";
length = (sizeof(gridText) + (sizeof(double)*3) + sizeof(gridLocked));
length = (sizeof(gridText) + (sizeof(double) * 3) + sizeof(gridLocked));
annotation = (char*)calloc(1, length);
annotation = (char *)calloc(1, length);
snprintf(annotation, length, gridText,
g_DefaultGridX,
g_DefaultGridY,
gridLocked,
g_GridOffset
);
g_DefaultGridX,
g_DefaultGridY,
gridLocked,
g_GridOffset
);
painter->setPen(WHITE);
painter->drawText(800, annotationRect.bottom() - 62, annotation);
@ -822,21 +822,21 @@ void Plot::drawAnnotations(QRect annotationRect, QPainter *painter) {
uint32_t pos = 0, loc = 375;
painter->setPen(WHITE);
if(g_MarkerA.pos > 0) {
if (g_MarkerA.pos > 0) {
free(annotation);
length = (sizeof(markerText) + (sizeof(uint32_t)*3) + sizeof(" ") + 1);
length = (sizeof(markerText) + (sizeof(uint32_t) * 3) + sizeof(" ") + 1);
pos = g_MarkerA.pos;
bool flag = false;
size_t value;
annotation = (char*)calloc(1, length);
char *textA = (char*)calloc(1, length);
annotation = (char *)calloc(1, length);
char *textA = (char *)calloc(1, length);
strcat(textA, markerText);
strcat(textA, " (%s%u)");
if(g_GraphBuffer[pos] <= g_OperationBuffer[pos]) {
if (g_GraphBuffer[pos] <= g_OperationBuffer[pos]) {
flag = true;
value = (g_OperationBuffer[pos] - g_GraphBuffer[pos]);
} else {
@ -844,65 +844,65 @@ void Plot::drawAnnotations(QRect annotationRect, QPainter *painter) {
}
snprintf(annotation, length, textA,
"A",
pos,
g_GraphBuffer[pos],
flag ? "+" : "-",
value
);
"A",
pos,
g_GraphBuffer[pos],
flag ? "+" : "-",
value
);
painter->drawText(loc, annotationRect.bottom() - 48, annotation);
free(textA);
}
if(g_MarkerB.pos > 0) {
if (g_MarkerB.pos > 0) {
free(annotation);
length = ((sizeof(markerText))+(sizeof(uint32_t)*2)+1);
length = ((sizeof(markerText)) + (sizeof(uint32_t) * 2) + 1);
pos = g_MarkerB.pos;
annotation = (char*)calloc(1, length);
annotation = (char *)calloc(1, length);
snprintf(annotation, length, markerText,
"B",
pos,
g_GraphBuffer[pos]
);
"B",
pos,
g_GraphBuffer[pos]
);
painter->drawText(loc, annotationRect.bottom() - 36, annotation);
}
if(g_MarkerC.pos > 0) {
if (g_MarkerC.pos > 0) {
free(annotation);
length = ((sizeof(markerText))+(sizeof(uint32_t)*2)+1);
length = ((sizeof(markerText)) + (sizeof(uint32_t) * 2) + 1);
pos = g_MarkerC.pos;
annotation = (char*)calloc(1, length);
annotation = (char *)calloc(1, length);
snprintf(annotation, length, markerText,
"C",
pos,
g_GraphBuffer[pos]
);
"C",
pos,
g_GraphBuffer[pos]
);
painter->drawText(loc, annotationRect.bottom() - 24, annotation);
}
if(g_MarkerD.pos > 0) {
if (g_MarkerD.pos > 0) {
free(annotation);
length = ((sizeof(markerText))+(sizeof(uint32_t)*2)+1);
length = ((sizeof(markerText)) + (sizeof(uint32_t) * 2) + 1);
pos = g_MarkerD.pos;
annotation = (char*)calloc(1, length);
annotation = (char *)calloc(1, length);
snprintf(annotation, length, markerText,
"D",
pos,
g_GraphBuffer[pos]
);
"D",
pos,
g_GraphBuffer[pos]
);
painter->drawText(loc, annotationRect.bottom() - 12, annotation);
}
@ -951,7 +951,7 @@ void Plot::plotGridLines(QPainter *painter, QRect r) {
}
void Plot::plotOperations(int *buffer, size_t len, QPainter *painter, QRect plotRect) {
if(len == 0) {
if (len == 0) {
return;
}
@ -973,10 +973,10 @@ void Plot::plotOperations(int *buffer, size_t len, QPainter *painter, QRect plot
y = yCoordOf(current, plotRect, gs_absVMax);
//We only want to graph changes between the Graph Buffer and the Operation Buffer
if(current == g_GraphBuffer[pos]) {
if (current == g_GraphBuffer[pos]) {
//If this point is the same, but the last point is different, we want to plot that line
//as well
if((pos == 0) || (prev == g_GraphBuffer[pos - 1])) {
if ((pos == 0) || (prev == g_GraphBuffer[pos - 1])) {
continue;
}
} else {
@ -1045,8 +1045,8 @@ void Plot::paintEvent(QPaintEvent *event) {
// End graph drawing
//Draw the markers
if(g_TempMarkerSize > 0) {
for(int i = 0; i < g_TempMarkerSize; i++) {
if (g_TempMarkerSize > 0) {
for (int i = 0; i < g_TempMarkerSize; i++) {
draw_marker(g_TempMarkers[i], plotRect, GRAY100, &painter);
}
}
@ -1074,15 +1074,15 @@ void Plot::draw_marker(marker_t marker, QRect plotRect, QColor color, QPainter *
painter->setPen(color);
//If the marker is outside the buffer length, reset
if(marker.pos > g_GraphTraceLen) {
if (marker.pos > g_GraphTraceLen) {
marker.pos = 0;
}
//Make sure the marker is inside the current plot view to render
if(marker.pos > g_GraphStart && xCoordOf(marker.pos, plotRect) < plotRect.right()) {
if (marker.pos > g_GraphStart && xCoordOf(marker.pos, plotRect) < plotRect.right()) {
painter->drawLine(xCoordOf(marker.pos, plotRect), plotRect.top(), xCoordOf(marker.pos, plotRect), plotRect.bottom());
if(strlen(marker.label) > 0) {
if (strlen(marker.label) > 0) {
painter->drawText(xCoordOf(marker.pos, plotRect) + 1, plotRect.top() + 12, marker.label);
}
}
@ -1295,7 +1295,7 @@ void Plot::keyPressEvent(QKeyEvent *event) {
offset = 1;
} else {
offset = int(ZOOM_LIMIT / g_GraphPixelsPerPoint);
}
}
}
switch (event->key()) {
@ -1393,9 +1393,9 @@ void Plot::keyPressEvent(QKeyEvent *event) {
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("[ ") "/" _RED_(" ]"), "Move yellow marker left/right by 1 sample");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("{ ") "/" _RED_(" }"), "Move pink marker left/right by 1 sample");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, " + " _RED_("Ctrl"), "... by 5 samples");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 +9, _RED_("= ") "/" _RED_(" -"), "Add/Subtract to the plot point (Operation Buffer) over the yellow marker by 1");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("= ") "/" _RED_(" -"), "Add/Subtract to the plot point (Operation Buffer) over the yellow marker by 1");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, " + " _RED_("Ctrl"), "... by 5");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 +9, _RED_("+ ") "/" _RED_(" _"), "Add/Subtract to the plot point (Graph Buffer) over the yellow marker by 1");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("+ ") "/" _RED_(" _"), "Add/Subtract to the plot point (Graph Buffer) over the yellow marker by 1");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, " + " _RED_("Ctrl"), "... by 5");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, _RED_("h"), "Show this help");
PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, _RED_("q"), "Close plot window");
@ -1441,9 +1441,9 @@ void Plot::keyPressEvent(QKeyEvent *event) {
if (g_GraphStart > startMax)
g_GraphStart = startMax;
break;
case Qt::Key_Equal:
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_OperationBuffer[g_MarkerA.pos] += 5;
} else {
g_OperationBuffer[g_MarkerA.pos] += 1;
@ -1451,9 +1451,9 @@ void Plot::keyPressEvent(QKeyEvent *event) {
RepaintGraphWindow();
break;
case Qt::Key_Minus:
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_OperationBuffer[g_MarkerA.pos] -= 5;
} else {
g_OperationBuffer[g_MarkerA.pos] -= 1;
@ -1463,7 +1463,7 @@ void Plot::keyPressEvent(QKeyEvent *event) {
break;
case Qt::Key_Plus:
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_GraphBuffer[g_MarkerA.pos] += 5;
} else {
g_GraphBuffer[g_MarkerA.pos] += 1;
@ -1471,9 +1471,9 @@ void Plot::keyPressEvent(QKeyEvent *event) {
RepaintGraphWindow();
break;
case Qt::Key_Underscore:
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_GraphBuffer[g_MarkerA.pos] -= 5;
} else {
g_GraphBuffer[g_MarkerA.pos] -= 1;
@ -1483,77 +1483,77 @@ void Plot::keyPressEvent(QKeyEvent *event) {
break;
case Qt::Key_BracketLeft: {
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_MarkerA.pos -= 5;
} else {
g_MarkerA.pos -= 1;
}
if((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) {
if ((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) {
uint32_t halfway = PageWidth / 2;
if((g_MarkerA.pos - halfway) > g_GraphTraceLen) {
if ((g_MarkerA.pos - halfway) > g_GraphTraceLen) {
g_GraphStart = 0;
} else {
g_GraphStart = g_MarkerA.pos - halfway;
}
}
if(g_MarkerA.pos < g_GraphStart) {
if (g_MarkerA.pos < g_GraphStart) {
g_MarkerA.pos = g_GraphStart;
}
RepaintGraphWindow();
break;
}
case Qt::Key_BracketRight: {
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_MarkerA.pos += 5;
} else {
g_MarkerA.pos += 1;
}
if((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) {
if ((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) {
uint32_t halfway = PageWidth / 2;
if((g_MarkerA.pos + halfway) >= g_GraphTraceLen) {
if ((g_MarkerA.pos + halfway) >= g_GraphTraceLen) {
g_GraphStart = g_GraphTraceLen - halfway;
} else {
g_GraphStart = g_MarkerA.pos - halfway;
}
}
if(g_MarkerA.pos >= g_GraphTraceLen) {
if (g_MarkerA.pos >= g_GraphTraceLen) {
g_MarkerA.pos = g_GraphTraceLen;
}
RepaintGraphWindow();
break;
}
case Qt::Key_BraceLeft:
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_MarkerB.pos -= 5;
} else {
g_MarkerB.pos -= 1;
}
if(g_MarkerB.pos < g_GraphStart) {
if (g_MarkerB.pos < g_GraphStart) {
g_MarkerB.pos = g_GraphStart;
}
RepaintGraphWindow();
break;
case Qt::Key_BraceRight:
if(event->modifiers() & Qt::ControlModifier) {
if (event->modifiers() & Qt::ControlModifier) {
g_MarkerB.pos += 5;
} else {
g_MarkerB.pos += 1;
}
if(g_MarkerB.pos >= g_GraphTraceLen) {
if (g_MarkerB.pos >= g_GraphTraceLen) {
g_MarkerB.pos = g_GraphTraceLen;
}

View file

@ -16,10 +16,15 @@
// Hitag2 Crypto
//-----------------------------------------------------------------------------
#include "hitag2_crypto.h"
#include <inttypes.h>
#include "util.h"
#include "string.h"
#include "commonutil.h"
#include "pm3_cmd.h"
#ifndef ON_DEVICE
#include "ui.h"
#endif
/* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
// Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
@ -27,39 +32,337 @@
// No warranties or guarantees of any kind.
// This code is released into the public domain by its author.
// Single bit Hitag2 functions:
#ifndef i4
#define i4(x,a,b,c,d) ((uint32_t)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
#define i4(x,a,b,c,d) ((uint32_t)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
#endif
static const uint32_t ht2_f4a = 0x2C79; // 0010 1100 0111 1001
static const uint32_t ht2_f4b = 0x6671; // 0110 0110 0111 0001
static const uint32_t ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
static uint32_t ht2_f20(const uint64_t x) {
uint32_t i5;
static uint32_t ht2_f20(const uint64_t state) {
i5 = ((ht2_f4a >> i4(x, 1, 2, 4, 5)) & 1) * 1
+ ((ht2_f4b >> i4(x, 7, 11, 13, 14)) & 1) * 2
+ ((ht2_f4b >> i4(x, 16, 20, 22, 25)) & 1) * 4
+ ((ht2_f4b >> i4(x, 27, 28, 30, 32)) & 1) * 8
+ ((ht2_f4a >> i4(x, 33, 42, 43, 45)) & 1) * 16;
uint32_t i5 = ((ht2_f4a >> i4(state, 1, 2, 4, 5)) & 1) * 1
+ ((ht2_f4b >> i4(state, 7, 11, 13, 14)) & 1) * 2
+ ((ht2_f4b >> i4(state, 16, 20, 22, 25)) & 1) * 4
+ ((ht2_f4b >> i4(state, 27, 28, 30, 32)) & 1) * 8
+ ((ht2_f4a >> i4(state, 33, 42, 43, 45)) & 1) * 16;
return (ht2_f5c >> i5) & 1;
}
uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV) {
uint32_t i;
// return a single bit from a value
static int ht2_bitn(uint64_t x, int bit) {
const uint64_t bitmask = (uint64_t)(1) << bit;
return (x & bitmask) ? 1 : 0;
}
// the sub-function R that rollback depends upon
int ht2_fnR(uint64_t state) {
// renumbered bits because my state is 0-47, not 1-48
return (
ht2_bitn(state, 1) ^ ht2_bitn(state, 2) ^ ht2_bitn(state, 5) ^
ht2_bitn(state, 6) ^ ht2_bitn(state, 7) ^ ht2_bitn(state, 15) ^
ht2_bitn(state, 21) ^ ht2_bitn(state, 22) ^ ht2_bitn(state, 25) ^
ht2_bitn(state, 29) ^ ht2_bitn(state, 40) ^ ht2_bitn(state, 41) ^
ht2_bitn(state, 42) ^ ht2_bitn(state, 45) ^ ht2_bitn(state, 46) ^
ht2_bitn(state, 47)
);
}
/*
static void ht2_rollback(hitag_state_t *hstate, unsigned int steps) {
for (int i = 0; i < steps; i++) {
hstate->shiftreg = ((hstate->shiftreg << 1) & 0xffffffffffff) | ht2_fnR(hstate->shiftreg);
}
}
*/
// the rollback function that lets us go backwards in time
void ht2_rollback(hitag_state_t *hstate, uint32_t steps) {
for (uint32_t i = 0; i < steps; i++) {
hstate->shiftreg = ((hstate->shiftreg << 1) & 0xffffffffffff) | ht2_fnR(hstate->shiftreg);
hstate->lfsr = LFSR_INV(hstate->lfsr);
}
}
// the three filter sub-functions that feed fnf
#define ht2_fa(x) ht2_bitn(0x2C79, (x))
#define ht2_fb(x) ht2_bitn(0x6671, (x))
#define ht2_fc(x) ht2_bitn(0x7907287B, (x))
// the filter function that generates a bit of output from the prng state
int ht2_fnf(uint64_t state) {
uint32_t x1 = (ht2_bitn(state, 2) << 0) | (ht2_bitn(state, 3) << 1) | (ht2_bitn(state, 5) << 2) | (ht2_bitn(state, 6) << 3);
uint32_t x2 = (ht2_bitn(state, 8) << 0) | (ht2_bitn(state, 12) << 1) | (ht2_bitn(state, 14) << 2) | (ht2_bitn(state, 15) << 3);
uint32_t x3 = (ht2_bitn(state, 17) << 0) | (ht2_bitn(state, 21) << 1) | (ht2_bitn(state, 23) << 2) | (ht2_bitn(state, 26) << 3);
uint32_t x4 = (ht2_bitn(state, 28) << 0) | (ht2_bitn(state, 29) << 1) | (ht2_bitn(state, 31) << 2) | (ht2_bitn(state, 33) << 3);
uint32_t x5 = (ht2_bitn(state, 34) << 0) | (ht2_bitn(state, 43) << 1) | (ht2_bitn(state, 44) << 2) | (ht2_bitn(state, 46) << 3);
uint32_t x6 = (ht2_fa(x1) << 0) | (ht2_fb(x2) << 1) | (ht2_fb(x3) << 2) | (ht2_fb(x4) << 3) | (ht2_fa(x5) << 4);
return ht2_fc(x6);
}
// builds the lfsr for the prng (quick calcs for hitag2_nstep())
/*
static void ht2_buildlfsr(hitag_state_t *hstate) {
if (hstate == NULL) {
return;
}
uint64_t state = hstate->shiftreg;
uint64_t temp = state ^ (state >> 1);
hstate->lfsr = state ^ (state >> 6) ^ (state >> 16)
^ (state >> 26) ^ (state >> 30) ^ (state >> 41)
^ (temp >> 2) ^ (temp >> 7) ^ (temp >> 22)
^ (temp >> 42) ^ (temp >> 46);
}
*/
#ifndef ON_DEVICE
#include <stdio.h>
#endif
uint64_t ht2_recoverkey(hitag_state_t *hstate, uint32_t uid, uint32_t nRenc) {
// hstate->shiftreg = (uint64_t)(((hstate->shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate->shiftreg));
// hstate->shiftreg = (uint64_t)(((hstate->shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate->shiftreg));
#ifndef ON_DEVICE
PrintAndLogEx(INFO, "shiftreg.... %" PRIx64, hstate->shiftreg);
#endif
// key lower 16 bits are lower 16 bits of prng state
uint64_t key = hstate->shiftreg & 0xffff;
uint32_t nRxork = (hstate->shiftreg >> 16) & 0xffffffff;
// rollback and extract bits b
uint32_t b = 0;
for (uint8_t i = 0; i < 32; i++) {
hstate->shiftreg = ((hstate->shiftreg) << 1) | ((uid >> (31 - i)) & 0x1);
b = (b << 1) | (unsigned int) ht2_fnf(hstate->shiftreg);
}
uint32_t nR = nRenc ^ b;
uint64_t keyupper = nRxork ^ nR;
key = key | (keyupper << 16);
#ifndef ON_DEVICE
PrintAndLogEx(INFO, "b..... %08" PRIx32 " %08" PRIx32 " %012" PRIx64, b, nRenc, hstate->shiftreg);
PrintAndLogEx(INFO, "key... %012" PRIx64 " %012" PRIx64 "\n", key, REV64(key));
#endif
return key;
}
/*
* Parameters:
* Hitag_State* pstate - output, internal state after initialisation
* uint64_t sharedkey - 48 bit key shared between reader & tag
* uint32_t serialnum - 32 bit tag serial number
* uint32_t iv - 32 bit random IV from reader, part of tag authentication
*/
void ht2_hitag2_init_ex(hitag_state_t *hstate, uint64_t sharedkey, uint32_t serialnum, uint32_t iv) {
// init state, from serial number and lowest 16 bits of shared key
uint64_t state = ((sharedkey & 0xFFFF) << 32) | serialnum;
// mix the initialisation vector and highest 32 bits of the shared key
iv ^= (uint32_t)(sharedkey >> 16);
// move 16 bits from (IV xor Shared Key) to top of uint64_t state
// these will be XORed in turn with output of the crypto function
state |= (uint64_t) iv << 48;
iv >>= 16;
// unrolled loop is faster on PIC32 (MIPS), do 32 times
// shift register, then calc new bit
state >>= 1;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
// highest 16 bits of IV XOR Shared Key
state |= (uint64_t) iv << 47;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46;
state ^= (uint64_t) ht2_f20(state) << 47;
// LSFR
hstate->shiftreg = state;
/* naive version for reference, LFSR has 16 taps
pstate->lfsr = state ^ (state >> 2) ^ (state >> 3) ^ (state >> 6)
^ (state >> 7) ^ (state >> 8) ^ (state >> 16) ^ (state >> 22)
^ (state >> 23) ^ (state >> 26) ^ (state >> 30) ^ (state >> 41)
^ (state >> 42) ^ (state >> 43) ^ (state >> 46) ^ (state >> 47);
*/
{
// optimise with one 64-bit intermediate
uint64_t temp = state ^ (state >> 1);
hstate->lfsr = state ^ (state >> 6) ^ (state >> 16)
^ (state >> 26) ^ (state >> 30) ^ (state >> 41)
^ (temp >> 2) ^ (temp >> 7) ^ (temp >> 22)
^ (temp >> 42) ^ (temp >> 46);
}
}
/*
* Return up to 32 crypto bits.
* Last bit is in least significant bit, earlier bits are shifted left.
* Note that the Hitag transmission protocol is least significant bit,
* so we may want to change this, or add a function, that returns the
* crypto output bits in the other order.
*
* Parameters:
* Hitag_State* pstate - in/out, internal cipher state after initialisation
* uint32_t steps - number of bits requested, (capped at 32)
*/
uint32_t ht2_hitag2_nstep(hitag_state_t *hstate, uint32_t steps) {
uint64_t state = hstate->shiftreg;
uint32_t result = 0;
uint64_t lfsr = hstate->lfsr;
if (steps == 0) {
return 0;
}
do {
// update shift registers
if (lfsr & 1) {
state = (state >> 1) | 0x800000000000;
lfsr = (lfsr >> 1) ^ 0xB38083220073;
// accumulate next bit of crypto
result = (result << 1) | ht2_f20(state);
} else {
state >>= 1;
lfsr >>= 1;
result = (result << 1) | ht2_f20(state);
}
} while (--steps);
hstate->shiftreg = state;
hstate->lfsr = lfsr;
return result;
}
uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t iv) {
uint64_t x = ((key & 0xFFFF) << 32) + serial;
for (i = 0; i < 32; i++) {
for (uint32_t i = 0; i < 32; i++) {
x >>= 1;
x += (uint64_t)(ht2_f20(x) ^ (((IV >> i) ^ (key >> (i + 16))) & 1)) << 47;
x += (uint64_t)(ht2_f20(x) ^ (((iv >> i) ^ (key >> (i + 16))) & 1)) << 47;
}
return x;
}
uint64_t ht2_hitag2_round(uint64_t *state) {
int ht2_try_state(uint64_t s, uint32_t uid, uint32_t aR2, uint32_t nR1, uint32_t nR2, uint64_t *key) {
hitag_state_t hstate;
hstate.shiftreg = s;
hstate.lfsr = 0;
hstate.shiftreg = (uint64_t)(((hstate.shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate.shiftreg));
hstate.shiftreg = (uint64_t)(((hstate.shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate.shiftreg));
#ifndef ON_DEVICE
hitag_state_t hs2;
hs2.shiftreg = s;
hs2.lfsr = 0;
ht2_rollback(&hs2, 2);
PrintAndLogEx(INFO, "hstate shiftreg.... %" PRIx64 " lfsr... %" PRIx64, hstate.shiftreg, hstate.lfsr);
PrintAndLogEx(INFO, "hstate shiftreg.... %" PRIx64 " lfsr... %" PRIx64, hs2.shiftreg, hs2.lfsr);
#endif
// recover key
uint64_t keyrev = hstate.shiftreg & 0xffff;
uint64_t nR1xk = (hstate.shiftreg >> 16) & 0xffffffff;
#ifndef ON_DEVICE
PrintAndLogEx(INFO, "keyrev...... %012" PRIx64 " nR1xk... %08" PRIx64, keyrev, nR1xk);
#endif
uint32_t b = 0;
for (uint8_t i = 0; i < 32; i++) {
hstate.shiftreg = ((hstate.shiftreg) << 1) | ((uid >> (31 - i)) & 0x1);
b = (b << 1) | (unsigned int) ht2_fnf(hstate.shiftreg);
}
#ifndef ON_DEVICE
PrintAndLogEx(INFO, "b..... %08" PRIx32 " %08" PRIx32 " %012" PRIx64, b, nR1, hstate.shiftreg);
#endif
keyrev |= (nR1xk ^ nR1 ^ b) << 16;
#ifndef ON_DEVICE
PrintAndLogEx(INFO, "key... %012" PRIx64 " %012" PRIx64, keyrev, REV64(keyrev));
#endif
// test key
ht2_hitag2_init_ex(&hstate, keyrev, uid, nR2);
if ((aR2 ^ ht2_hitag2_nstep(&hstate, 32)) == 0xFFFFFFFF) {
*key = REV64(keyrev);
return PM3_SUCCESS;
}
return PM3_ESOFT;
}
// "MIKRON" = O N M I K R
// Key = 4F 4E 4D 49 4B 52 - Secret 48-bit key
// Serial = 49 43 57 69 - Serial number of the tag, transmitted in clear
// Random = 65 6E 45 72 - Random IV, transmitted in clear
//~28~DC~80~31 = D7 23 7F CE - Authenticator value = inverted first 4 bytes of the keystream
// The code below must print out "D7 23 7F CE 8C D0 37 A9 57 49 C1 E6 48 00 8A B6".
// The inverse of the first 4 bytes is sent to the tag to authenticate.
// The rest is encrypted by XORing it with the subsequent keystream.
/*
* Return 8 crypto bits.
* Last bit is in least significant bit, earlier bits are shifted left.
* Note that the Hitag transmission protocol is least significant bit,
* so we may want to change this, or add a function, that returns the
* crypto output bits in the other order.
*
* Parameters:
* uint64_t *state - in/out, internal cipher state after initialisation
*/
uint64_t ht2_hitag2_bit(uint64_t *state) {
uint64_t x = *state;
x = (x >> 1) +
@ -72,21 +375,25 @@ uint64_t ht2_hitag2_round(uint64_t *state) {
return ht2_f20(x);
}
// "MIKRON" = O N M I K R
// Key = 4F 4E 4D 49 4B 52 - Secret 48-bit key
// Serial = 49 43 57 69 - Serial number of the tag, transmitted in clear
// Random = 65 6E 45 72 - Random IV, transmitted in clear
//~28~DC~80~31 = D7 23 7F CE - Authenticator value = inverted first 4 bytes of the keystream
// Take a state and create one byte (8bits) of crypto
uint32_t ht2_hitag2_byte(uint64_t *state) {
uint32_t c = 0;
c += (uint32_t) ht2_hitag2_bit(state) << 7; // 7
c += (uint32_t) ht2_hitag2_bit(state) << 6; // 6
c += (uint32_t) ht2_hitag2_bit(state) << 5; // 5
c += (uint32_t) ht2_hitag2_bit(state) << 4;
c += (uint32_t) ht2_hitag2_bit(state) << 3;
c += (uint32_t) ht2_hitag2_bit(state) << 2;
c += (uint32_t) ht2_hitag2_bit(state) << 1;
c += (uint32_t) ht2_hitag2_bit(state) << 0;
return c;
}
// The code below must print out "D7 23 7F CE 8C D0 37 A9 57 49 C1 E6 48 00 8A B6".
// The inverse of the first 4 bytes is sent to the tag to authenticate.
// The rest is encrypted by XORing it with the subsequent keystream.
uint32_t ht2_hitag2_byte(uint64_t *x) {
uint32_t i, c;
for (i = 0, c = 0; i < 8; i++) {
c += (uint32_t) ht2_hitag2_round(x) << (i ^ 7);
}
uint32_t ht2_hitag2_word(uint64_t *state, uint32_t steps) {
uint32_t c = 0;
do {
c += (uint32_t) ht2_hitag2_bit(state) << (steps - 1);
} while (--steps);
return c;
}
@ -108,19 +415,23 @@ void ht2_hitag2_cipher_reset(hitag2_t *tag, const uint8_t *iv) {
tag->cs = ht2_hitag2_init(REV64(key), REV32(uid), REV32(iv_));
}
int ht2_hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is) {
int ht2_hitag2_cipher_authenticate(uint64_t *state, const uint8_t *authenticator_is) {
uint8_t authenticator_should[4];
authenticator_should[0] = ~ht2_hitag2_byte(cs);
authenticator_should[1] = ~ht2_hitag2_byte(cs);
authenticator_should[2] = ~ht2_hitag2_byte(cs);
authenticator_should[3] = ~ht2_hitag2_byte(cs);
authenticator_should[0] = ~ht2_hitag2_byte(state);
authenticator_should[1] = ~ht2_hitag2_byte(state);
authenticator_should[2] = ~ht2_hitag2_byte(state);
authenticator_should[3] = ~ht2_hitag2_byte(state);
return (memcmp(authenticator_should, authenticator_is, 4) == 0);
}
int ht2_hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, uint16_t bytes, uint16_t bits) {
void ht2_hitag2_cipher_transcrypt(uint64_t *state, uint8_t *data, uint16_t bytes, uint16_t bits) {
int i;
for (i = 0; i < bytes; i++) data[i] ^= ht2_hitag2_byte(cs);
for (i = 0; i < bits; i++) data[bytes] ^= ht2_hitag2_round(cs) << (7 - i);
return 0;
for (i = 0; i < bytes; i++) {
data[i] ^= ht2_hitag2_byte(state);
}
for (i = 0; i < bits; i++) {
data[bytes] ^= ht2_hitag2_bit(state) << (7 - i);
}
}

View file

@ -17,6 +17,12 @@
#define __HITAG2_CRYPTO_H
#include "common.h"
#include <stdbool.h>
#ifndef LFSR_INV
#define LFSR_INV(state) (((state) << 1) | (__builtin_parityll((state) & ((0xce0044c101cd >> 1) | (1ull << 47)))))
#endif
typedef struct {
uint32_t uid;
@ -32,11 +38,27 @@ typedef struct {
uint8_t sectors[12][4];
} hitag2_t;
uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV);
uint64_t ht2_hitag2_round(uint64_t *state);
uint32_t ht2_hitag2_byte(uint64_t *x);
void ht2_hitag2_cipher_reset(hitag2_t *tag, const uint8_t *iv);
int ht2_hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is);
int ht2_hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, uint16_t bytes, uint16_t bits) ;
typedef struct {
uint64_t shiftreg; // naive shift register, required for nonlinear fn input
uint64_t lfsr; // fast lfsr, used to make software faster
} hitag_state_t;
void ht2_hitag2_init_ex(hitag_state_t *hstate, uint64_t sharedkey, uint32_t serialnum, const uint32_t iv);
void ht2_rollback(hitag_state_t *hstate, uint32_t steps);
uint64_t ht2_recoverkey(hitag_state_t *hstate, uint32_t uid, uint32_t nRenc);
uint32_t ht2_hitag2_nstep(hitag_state_t *hstate, uint32_t steps);
uint32_t ht2_hitag_acid(hitag_state_t *hstate, uint32_t steps);
int ht2_try_state(uint64_t s, uint32_t uid, uint32_t aR2, uint32_t nR1, uint32_t nR2, uint64_t *key);
uint32_t ht2_hitag2_word(uint64_t *state, uint32_t steps);
uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t iv);
uint64_t ht2_hitag2_bit(uint64_t *state);
uint32_t ht2_hitag2_byte(uint64_t *state);
void ht2_hitag2_cipher_reset(hitag2_t *tag, const uint8_t *iv);
int ht2_hitag2_cipher_authenticate(uint64_t *state, const uint8_t *authenticator_is);
void ht2_hitag2_cipher_transcrypt(uint64_t *state, uint8_t *data, uint16_t bytes, uint16_t bits) ;
int ht2_fnf(uint64_t state);
int ht2_fnR(uint64_t state);
#endif

View file

@ -42,10 +42,8 @@ static const uint8_t g_odd_byte_parity[256] = {
1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
};
//extern const uint8_t OddByteParity[256];
#define ODD_PARITY8(x) { g_odd_byte_parity[x] }
#define EVEN_PARITY8(x) { !g_odd_byte_parity[x] }
#define ODD_PARITY8(x) g_odd_byte_parity[x]
#define EVEN_PARITY8(x) !g_odd_byte_parity[x]
static inline uint8_t oddparity8(const uint8_t x) {
return g_odd_byte_parity[x];
@ -60,7 +58,7 @@ static inline uint8_t evenparity16(uint16_t x) {
x ^= x >> 8;
return EVEN_PARITY8(x) ;
#else
return (__builtin_parity(x) & 0xFF);
return __builtin_parity(x);
#endif
}
@ -77,9 +75,9 @@ static inline uint8_t evenparity32(uint32_t x) {
#if !defined __GNUC__
x ^= x >> 16;
x ^= x >> 8;
return EVEN_PARITY8(x);
return EVEN_PARITY8(x) ;
#else
return (__builtin_parity(x) & 0xFF);
return __builtin_parity(x);
#endif
}

View file

@ -189,7 +189,7 @@
"options": [
"-h, --help This help",
"-d <hex> ASN1 encoded byte array",
"-t, --test perform selftest"
"-t, --test perform self test"
],
"usage": "data asn1 [-ht] [-d <hex>]"
},
@ -221,18 +221,21 @@
],
"usage": "data autocorr [-hg] [-w <dec>]"
},
"data bin2hex": {
"command": "data bin2hex",
"description": "This function converts binary to hexadecimal. It will ignore all characters not 1 or 0 but stop reading on whitespace",
"data biphaserawdecode": {
"command": "data biphaserawdecode",
"description": "Biphase decode binary stream in DemodBuffer Converts 10 or 01 -> 1 and 11 or 00 -> 0 - must have binary sequence in DemodBuffer (run `data rawdemod --ar` before) - invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester",
"notes": [
"data bin2hex -d 0101111001010"
"data biphaserawdecode -> decode biphase bitstream from the DemodBuffer",
"data biphaserawdecode -oi -> decode biphase bitstream from the DemodBuffer, adjust offset, and invert output"
],
"offline": true,
"options": [
"-h, --help This help",
"-d, --data <bin> binary string to convert"
"-o, --offset set to adjust decode start position",
"-i, --inv invert output",
"--err <dec> set max errors tolerated (def 20)"
],
"usage": "data bin2hex [-h] -d <bin>"
"usage": "data biphaserawdecode [-hoi] [--err <dec>]"
},
"data bitsamples": {
"command": "data bitsamples",
@ -261,18 +264,6 @@
],
"usage": "data bmap [-h] [-d <hex>] [-m <str>]"
},
"data clear": {
"command": "data clear",
"description": "This function clears the bigbuff on deviceside and graph window",
"notes": [
"data clear"
],
"offline": true,
"options": [
"-h, --help This help"
],
"usage": "data clear [-h]"
},
"data convertbitstream": {
"command": "data convertbitstream",
"description": "Convert GraphBuffer's 0|1 values to 127|-127",
@ -444,32 +435,15 @@
},
"data help": {
"command": "data help",
"description": "----------- ------------------------- General------------------------- help This help ----------- ------------------------- Modulation------------------------- biphaserawdecode Biphase decode bin stream in DemodBuffer detectclock Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer fsktonrz Convert fsk2 to nrz wave for alternate fsk demodulating (for weak fsk) manrawdecode Manchester decode binary stream in DemodBuffer modulation Identify LF signal for clock and modulation rawdemod Demodulate the data in the GraphBuffer and output binary ----------- ------------------------- Graph------------------------- askedgedetect Adjust Graph for manual ASK demod autocorr Autocorrelation over window dirthreshold Max rising higher up-thres/ Min falling lower down-thres decimate Decimate samples envelope Generate square envelope of samples undecimate Un-decimate samples hide Hide graph window hpf Remove DC offset from trace iir Apply IIR buttersworth filter on plot data grid overlay grid on graph window ltrim Trim samples from left of trace mtrim Trim out samples from the specified start to the specified stop norm Normalize max/min to +/-128 plot Show graph window cthreshold Average out all values between rtrim Trim samples from right of trace setgraphmarkers Set blue and orange marker in graph window shiftgraphzero Shift 0 for Graphed wave + or - shift value timescale Set cursor display timescale zerocrossings Count time between zero-crossings convertbitstream Convert GraphBuffer's 0/1 values to 127 / -127 getbitstream Convert GraphBuffer's >=1 values to 1 and <1 to 0 ----------- ------------------------- Operations------------------------- asn1 ASN1 decoder atr ATR lookup bin2hex Converts binary to hexadecimal bmap Convert hex value according a binary template clear Clears bigbuf on deviceside and graph window crypto Encrypt and decrypt data diff Diff of input files hex2bin Converts hexadecimal to binary load Load contents of file into graph window num Converts dec/hex/bin print Print the data in the DemodBuffer save Save signal trace data ( GraphBuffer ) setdebugmode Set Debugging Level on client side xor Xor a input string --------------------------------------------------------------------------------------- data biphaserawdecode available offline: yes Biphase decode binary stream in DemodBuffer Converts 10 or 01 -> 1 and 11 or 00 -> 0 - must have binary sequence in DemodBuffer (run `data rawdemod --ar` before) - invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester",
"description": "help This help ----------- ------------------------- General------------------------- clear Clears various buffers used by the graph window hide Hide the graph window load Load contents of file into graph window num Converts dec/hex/bin plot Show the graph window print Print the data in the DemodBuffer save Save signal trace data setdebugmode Set Debugging Level on client side xor Xor a input string ----------- ------------------------- Modulation------------------------- biphaserawdecode Biphase decode bin stream in DemodBuffer detectclock Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer fsktonrz Convert fsk2 to nrz wave for alternate fsk demodulating (for weak fsk) manrawdecode Manchester decode binary stream in DemodBuffer modulation Identify LF signal for clock and modulation rawdemod Demodulate the data in the GraphBuffer and output binary ----------- ------------------------- Graph------------------------- askedgedetect Adjust Graph for manual ASK demod autocorr Autocorrelation over window convertbitstream Convert GraphBuffer's 0/1 values to 127 / -127 cthreshold Average out all values between dirthreshold Max rising higher up-thres/ Min falling lower down-thres decimate Decimate samples envelope Generate square envelope of samples grid overlay grid on graph window getbitstream Convert GraphBuffer's >=1 values to 1 and <1 to 0 hpf Remove DC offset from trace iir Apply IIR buttersworth filter on plot data ltrim Trim samples from left of trace mtrim Trim out samples from the specified start to the specified stop norm Normalize max/min to +/-128 rtrim Trim samples from right of trace setgraphmarkers Set the markers in the graph window shiftgraphzero Shift 0 for Graphed wave + or - shift value timescale Set cursor display timescale undecimate Un-decimate samples zerocrossings Count time between zero-crossings ----------- ------------------------- Operations------------------------- asn1 ASN1 decoder atr ATR lookup bmap Convert hex value according a binary template crypto Encrypt and decrypt data diff Diff of input files --------------------------------------------------------------------------------------- data clear available offline: yes This function clears the BigBuf on device side and graph window ( graphbuffer )",
"notes": [
"data biphaserawdecode -> decode biphase bitstream from the DemodBuffer",
"data biphaserawdecode -oi -> decode biphase bitstream from the DemodBuffer, adjust offset, and invert output"
"data clear"
],
"offline": true,
"options": [
"-h, --help This help",
"-o, --offset set to adjust decode start position",
"-i, --inv invert output",
"--err <dec> set max errors tolerated (def 20)"
"-h, --help This help"
],
"usage": "data biphaserawdecode [-hoi] [--err <dec>]"
},
"data hex2bin": {
"command": "data hex2bin",
"description": "This function converts hexadecimal to binary. It will ignore all non-hexadecimal characters but stop reading on whitespace",
"notes": [
"data hex2bin -d 01020304"
],
"offline": true,
"options": [
"-h, --help This help",
"-d, --data <hex> bytes to convert"
],
"usage": "data hex2bin [-h] [-d <hex>]"
"usage": "data clear [-h]"
},
"data hexsamples": {
"command": "data hexsamples",
@ -735,18 +709,22 @@
},
"data setgraphmarkers": {
"command": "data setgraphmarkers",
"description": "Set blue and orange marker in graph window",
"description": "Set the locations of the markers in the graph window",
"notes": [
"data setgraphmarkers -> turn off",
"data setgraphmarkers -a 64 -b 50"
"data setgraphmarkers -> reset the markers",
"data setgraphmarkers -a 64 -> set A, reset the rest",
"data setgraphmarkers -d --keep -> set D, keep the rest"
],
"offline": true,
"options": [
"-h, --help This help",
"-a <dec> orange marker",
"-b <dec> blue marker"
"--keep keep the current values of the markers",
"-a <dec> yellow marker",
"-b <dec> pink marker",
"-c <dec> orange marker",
"-d <dec> blue marker"
],
"usage": "data setgraphmarkers [-h] [-a <dec>] [-b <dec>]"
"usage": "data setgraphmarkers [-h] [--keep] [-a <dec>] [-b <dec>] [-c <dec>] [-d <dec>]"
},
"data shiftgraphzero": {
"command": "data shiftgraphzero",
@ -1621,14 +1599,16 @@
"command": "hf 15 csetuid",
"description": "Set UID for magic Chinese card (only works with such cards)",
"notes": [
"hf 15 csetuid -u E011223344556677"
"hf 15 csetuid -u E011223344556677 -> use gen1 command",
"hf 15 csetuid -u E011223344556677 --v2 -> use gen2 command"
],
"offline": false,
"options": [
"-h, --help This help",
"-u, --uid <hex> UID, 8 hex bytes"
"-u, --uid <hex> UID, 8 hex bytes",
"-2, --v2 Use gen2 magic command"
],
"usage": "hf 15 csetuid [-h] -u <hex>"
"usage": "hf 15 csetuid [-h2] -u <hex>"
},
"hf 15 demod": {
"command": "hf 15 demod",
@ -3329,7 +3309,7 @@
},
"hf iclass help": {
"command": "hf iclass help",
"description": "----------- --------------------- General --------------------- help This help list List iclass history view Display content from tag dump file ----------- --------------------- Recovery -------------------- loclass Use loclass to perform bruteforce reader attack lookup Uses authentication trace to check for key in dictionary file ----------- ---------------------- Utils ---------------------- calcnewkey Calc diversified keys (blocks 3 & 4) to write new keys encode Encode binary wiegand to block 7 encrypt Encrypt given block data decrypt Decrypt given block data or tag dump file managekeys Manage keys to use with iclass commands permutekey Permute function from 'heart of darkness' paper --------------------------------------------------------------------------------------- hf iclass list available offline: yes Alias of `trace list -t iclass -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol",
"description": "help This help list List iclass history view Display content from tag dump file ----------- --------------------- Recovery -------------------- loclass Use loclass to perform bruteforce reader attack lookup Uses authentication trace to check for key in dictionary file ----------- ---------------------- Utils ---------------------- calcnewkey Calc diversified keys (blocks 3 & 4) to write new keys encode Encode binary wiegand to block 7 encrypt Encrypt given block data decrypt Decrypt given block data or tag dump file managekeys Manage keys to use with iclass commands permutekey Permute function from 'heart of darkness' paper --------------------------------------------------------------------------------------- hf iclass list available offline: yes Alias of `trace list -t iclass -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol",
"notes": [
"hf iclass list --frame -> show frame delay times",
"hf iclass list -1 -> use trace buffer"
@ -3372,14 +3352,14 @@
"options": [
"-h, --help This help",
"-f, --file <fn> filename with nr/mac data from `hf iclass sim -t 2`",
"--test Perform self-test",
"--long Perform self-test, including long ones"
"--test Perform self test",
"--long Perform self test, including long ones"
],
"usage": "hf iclass loclass [-h] [-f <fn>] [--test] [--long]"
},
"hf iclass lookup": {
"command": "hf iclass lookup",
"description": "Lookup keys takes some sniffed trace data and tries to verify what key was used against a dictionary file",
"description": "This command take sniffed trace data and try to recovery a iCLASS Standard or iCLASS Elite key.",
"notes": [
"hf iclass lookup --csn 9655a400f8ff12e0 --epurse f0ffffffffffffff --macs 0000000089cb984b -f iclass_default_keys.dic",
"hf iclass lookup --csn 9655a400f8ff12e0 --epurse f0ffffffffffffff --macs 0000000089cb984b -f iclass_default_keys.dic --elite"
@ -3670,7 +3650,7 @@
"-h, --help This help",
"-u, --uid <hex> uid bytes",
"-r read uid from tag instead",
"-t selftest",
"-t self test",
"-v, --verbose verbose output",
"--dragon figurine type",
"--fox figurine type",
@ -8219,11 +8199,12 @@
],
"usage": "lf awid clone [-h] --fmt <dec> --fc <dec> --cn <dec> [--q5] [--em]"
},
"lf awid help": {
"command": "lf awid help",
"description": "help this help demod demodulate an AWID FSK tag from the GraphBuffer --------------------------------------------------------------------------------------- lf awid demod available offline: yes Try to find AWID Prox preamble, if found decode / descramble data",
"lf awid demod": {
"command": "lf awid demod",
"description": "Try to find AWID Prox preamble, if found decode / descramble data",
"notes": [
"lf awid demod"
"lf awid demod",
"lf awid demod --raw"
],
"offline": true,
"options": [
@ -8231,6 +8212,25 @@
],
"usage": "lf awid demod [-h]"
},
"lf awid help": {
"command": "lf awid help",
"description": "help this help demod demodulate an AWID FSK tag from the GraphBuffer --------------------------------------------------------------------------------------- lf awid brute available offline: no Enables bruteforce of AWID reader with specified facility-code. This is a attack against reader. if cardnumber is given, it starts with it and goes up / down one step if cardnumber is not given, it starts with 1 and goes up to 65535",
"notes": [
"lf awid brute --fmt 26 --fc 224",
"lf awid brute --fmt 50 --fc 2001 --delay 2000",
"lf awid brute --fmt 50 --fc 2001 --cn 200 --delay 2000 -v"
],
"offline": true,
"options": [
"-h, --help This help",
"--fmt <dec> format length 26|50",
"--fc <dec> 8|16bit value facility code",
"--cn <dec> optional - card number to start with, max 65535",
"--delay <dec> optional - delay betweens attempts in ms. Default 1000ms",
"-v, --verbose verbose output"
],
"usage": "lf awid brute [-hv] --fmt <dec> --fc <dec> [--cn <dec>] [--delay <dec>]"
},
"lf awid reader": {
"command": "lf awid reader",
"description": "read a AWID Prox tag",
@ -9426,20 +9426,32 @@
],
"usage": "lf hitag cc [-h] -f <fn>"
},
"lf hitag chk": {
"command": "lf hitag chk",
"description": "Run dictionary key or password recovery against Hitag card.",
"notes": [
"lf hitag chk",
"-> checks for both pwd / crypto keyslf hitag chk --crypto -> use def dictionary",
"lf hitag chk --pwd -f my.dic -> pwd mode, custom dictionary"
],
"offline": false,
"options": [
"-h, --help This help",
"-f, --file <fn> specify dictionary filename",
"--pwd password mode",
"--crypto crypto mode"
],
"usage": "lf hitag chk [-h] [-f <fn>] [--pwd] [--crypto]"
},
"lf hitag dump": {
"command": "lf hitag dump",
"description": "Read all Hitag 2 card memory and save to file Crypto mode key format: ISK high + ISK low",
"description": "Read all Hitag 2 card memory and save to file Crypto mode key format: ISK high + ISK low, 4F4E4D494B52 (ONMIKR) Password mode, default key 4D494B52 (MIKR)",
"notes": [
"Password mode => use default key 4D494B52 (MIKR)",
"lf hitag dump --pwd",
"Short key = password mode",
"lf hitag dump -k 4D494B52",
"Challenge mode",
"lf hitag dump --nrar 0102030411223344",
"Crypto mode => use default key 4F4E4D494B52 (ONMIKR)",
"lf hitag dump --crypto",
"Long key = crypto mode",
"lf hitag dump -k 4F4E4D494B52"
"lf hitag dump --pwd -> use def pwd",
"lf hitag dump -k 4D494B52 -> pwd mode",
"lf hitag dump --crypto -> use def crypto",
"lf hitag dump -k 4F4E4D494B52 -> crypto mode",
"lf hitag dump --nrar 0102030411223344"
],
"offline": false,
"options": [
@ -9485,7 +9497,7 @@
},
"lf hitag help": {
"command": "lf hitag help",
"description": "help This help list List Hitag trace history view Display content from tag dump file --------------------------------------------------------------------------------------- lf hitag list available offline: yes Alias of `trace list -t hitag2` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol",
"description": "help This help list List Hitag trace history selftest Perform self test view Display content from tag dump file lookup Uses authentication trace to check for key in dictionary file --------------------------------------------------------------------------------------- lf hitag list available offline: yes Alias of `trace list -t hitag2` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol",
"notes": [
"lf hitag list --frame -> show frame delay times",
"lf hitag list -1 -> use trace buffer"
@ -9516,29 +9528,41 @@
],
"usage": "lf hitag info [-h]"
},
"lf hitag lookup": {
"command": "lf hitag lookup",
"description": "This command take sniffed trace data and try to recovery a Hitag2 crypto key. You can either - verify that NR/AR matches a known crypto key - verify if NR/AR matches a known 6 byte crypto key in a dictionary",
"notes": [
"lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -k 010203040506 -> check key",
"lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -> use def dictionary",
"lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -f my.dic -> use custom dictionary",
"lf hitag lookup --uid 11223344 --nrar 73AA5A62EAB8529C"
],
"offline": true,
"options": [
"-h, --help This help",
"-f, --file <fn> specify dictionary filename",
"-k, --key <hex> specify known cryptokey as 6 bytes",
"-u, --uid <hex> specify UID as 4 hex bytes",
"--nr <hex> specify nonce as 4 hex bytes",
"--ar <hex> specify answer as 4 hex bytes",
"--nrar <hex> specify nonce / answer as 8 hex bytes"
],
"usage": "lf hitag lookup [-h] [-f <fn>] [-k <hex>] -u <hex> [--nr <hex>] [--ar <hex>] [--nrar <hex>]"
},
"lf hitag read": {
"command": "lf hitag read",
"description": "Read Hitag memory Crypto mode key format: ISK high + ISK low",
"description": "Read Hitag memory. It support HitagS and Hitag 2 Password mode: - default key 4D494B52 (MIKR) Crypto mode: - key format ISK high + ISK low - default key 4F4E4D494B52 (ONMIKR)",
"notes": [
"Hitag S, plain mode",
"lf hitag read --hts",
"Hitag S, challenge mode",
"lf hitag read --hts --nrar 0102030411223344",
"Hitag S, crypto mode => use default key 4F4E4D494B52 (ONMIKR)",
"lf hitag read --hts --crypto",
"Hitag S, long key = crypto mode",
"lf hitag read --hts -k 4F4E4D494B52",
"lf hitag read --hts -> HitagS, plain mode",
"lf hitag read --hts --nrar 0102030411223344 -> HitagS, challenge mode",
"lf hitag read --hts --crypto -> HitagS, crypto mode, def key",
"lf hitag read --hts -k 4F4E4D494B52 -> HitagS, crypto mode",
"",
"Hitag 2, password mode => use default key 4D494B52 (MIKR)",
"lf hitag read --ht2 --pwd",
"Hitag 2, providing a short key = password mode",
"lf hitag read --ht2 -k 4D494B52",
"Hitag 2, challenge mode",
"lf hitag read --ht2 --nrar 0102030411223344",
"Hitag 2, crypto mode => use default key 4F4E4D494B52 (ONMIKR)",
"lf hitag read --ht2 --crypto",
"Hitag 2, providing a long key = crypto mode",
"lf hitag read --ht2 -k 4F4E4D494B52"
"lf hitag read --ht2 --pwd -> Hitag 2, pwd mode, def key",
"lf hitag read --ht2 -k 4D494B52 -> Hitag 2, pwd mode",
"lf hitag read --ht2 --nrar 0102030411223344 -> Hitag 2, challenge mode",
"lf hitag read --ht2 --crypto -> Hitag 2, crypto mode, def key",
"lf hitag read --ht2 -k 4F4E4D494B52 -> Hitag 2, crypto mode"
],
"offline": false,
"options": [
@ -9552,6 +9576,18 @@
],
"usage": "lf hitag read [-hs2] [--pwd] [--nrar <hex>] [--crypto] [-k <hex>]"
},
"lf hitag selftest": {
"command": "lf hitag selftest",
"description": "Perform selftest of Hitag crypto engine",
"notes": [
"lf hitag selftest"
],
"offline": true,
"options": [
"-h, --help This help"
],
"usage": "lf hitag selftest [-h]"
},
"lf hitag sim": {
"command": "lf hitag sim",
"description": "Simulate Hitag transponder You need to `lf hitag eload` first",
@ -9595,27 +9631,18 @@
},
"lf hitag wrbl": {
"command": "lf hitag wrbl",
"description": "Write a page in Hitag memory Crypto mode key format: ISK high + ISK low",
"description": "Write a page in Hitag memory. It support HitagS and Hitag 2 Password mode: - default key 4D494B52 (MIKR) Crypto mode: - key format ISK high + ISK low - default key 4F4E4D494B52 (ONMIKR)",
"notes": [
"Hitag S, plain mode",
"lf hitag wrbl --hts -p 6 -d 01020304",
"Hitag S, challenge mode",
"lf hitag wrbl --hts --nrar 0102030411223344 -p 6 -d 01020304",
"Hitag S, crypto mode => use default key 4F4E4D494B52 (ONMIKR)",
"lf hitag wrbl --hts --crypto -p 6 -d 01020304",
"Hitag S, long key = crypto mode",
"lf hitag wrbl --hts -k 4F4E4D494B52 -p 6 -d 01020304",
"lf hitag wrbl --hts -p 6 -d 01020304 -> HitagS, plain mode",
"lf hitag wrbl --hts -p 6 -d 01020304 --nrar 0102030411223344 -> HitagS, challenge mode",
"lf hitag wrbl --hts -p 6 -d 01020304 --crypto -> HitagS, crypto mode, def key",
"lf hitag wrbl --hts -p 6 -d 01020304 -k 4F4E4D494B52 -> HitagS, crypto mode",
"",
"Hitag 2, password mode => use default key 4D494B52 (MIKR)",
"lf hitag wrbl --ht2 --pwd -p 6 -d 01020304",
"Hitag 2, providing a short key = password mode",
"lf hitag wrbl --ht2 -k 4D494B52 -p 6 -d 01020304",
"Hitag 2, challenge mode",
"lf hitag wrbl --ht2 --nrar 0102030411223344 -p 6 -d 01020304",
"Hitag 2, crypto mode => use default key 4F4E4D494B52 (ONMIKR)",
"lf hitag wrbl --ht2 --crypto -p 6 -d 01020304",
"Hitag 2, providing a long key = crypto mode",
"lf hitag wrbl --ht2 -k 4F4E4D494B52 -p 6 -d 01020304"
"lf hitag wrbl --ht2 -p 6 -d 01020304 --pwd -> Hitag 2, pwd mode, def key",
"lf hitag wrbl --ht2 -p 6 -d 01020304 -k 4D494B52 -> Hitag 2, pwd mode",
"lf hitag wrbl --ht2 -p 6 -d 01020304 --nrar 0102030411223344 -> Hitag 2, challenge mode",
"lf hitag wrbl --ht2 -p 6 -d 01020304 --crypto -> Hitag 2, crypto mode, def key",
"lf hitag wrbl --ht2 -p 6 -d 01020304 -k 4F4E4D494B52 -> Hitag 2, crypto mode"
],
"offline": false,
"options": [
@ -12595,8 +12622,8 @@
}
},
"metadata": {
"commands_extracted": 727,
"commands_extracted": 729,
"extracted_by": "PM3Help2JSON v1.00",
"extracted_on": "2024-04-07T09:37:51"
"extracted_on": "2024-04-22T14:35:02"
}
}

View file

@ -94,6 +94,15 @@ Check column "offline" for their availability.
|command |offline |description
|------- |------- |-----------
|`data help `|Y |`This help`
|`data clear `|Y |`Clears various buffers used by the graph window`
|`data hide `|Y |`Hide the graph window`
|`data load `|Y |`Load contents of file into graph window`
|`data num `|Y |`Converts dec/hex/bin`
|`data plot `|Y |`Show the graph window`
|`data print `|Y |`Print the data in the DemodBuffer`
|`data save `|Y |`Save signal trace data`
|`data setdebugmode `|Y |`Set Debugging Level on client side`
|`data xor `|Y |`Xor a input string`
|`data biphaserawdecode `|Y |`Biphase decode bin stream in DemodBuffer`
|`data detectclock `|Y |`Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer`
|`data fsktonrz `|Y |`Convert fsk2 to nrz wave for alternate fsk demodulating (for weak fsk)`
@ -102,43 +111,32 @@ Check column "offline" for their availability.
|`data rawdemod `|Y |`Demodulate the data in the GraphBuffer and output binary`
|`data askedgedetect `|Y |`Adjust Graph for manual ASK demod`
|`data autocorr `|Y |`Autocorrelation over window`
|`data convertbitstream `|Y |`Convert GraphBuffer's 0/1 values to 127 / -127`
|`data cthreshold `|Y |`Average out all values between`
|`data dirthreshold `|Y |`Max rising higher up-thres/ Min falling lower down-thres`
|`data decimate `|Y |`Decimate samples`
|`data envelope `|Y |`Generate square envelope of samples`
|`data undecimate `|Y |`Un-decimate samples`
|`data hide `|Y |`Hide graph window`
|`data grid `|Y |`overlay grid on graph window`
|`data getbitstream `|Y |`Convert GraphBuffer's >=1 values to 1 and <1 to 0`
|`data hpf `|Y |`Remove DC offset from trace`
|`data iir `|Y |`Apply IIR buttersworth filter on plot data`
|`data grid `|Y |`overlay grid on graph window`
|`data ltrim `|Y |`Trim samples from left of trace`
|`data mtrim `|Y |`Trim out samples from the specified start to the specified stop`
|`data norm `|Y |`Normalize max/min to +/-128`
|`data plot `|Y |`Show graph window`
|`data cthreshold `|Y |`Average out all values between`
|`data rtrim `|Y |`Trim samples from right of trace`
|`data setgraphmarkers `|Y |`Set blue and orange marker in graph window`
|`data setgraphmarkers `|Y |`Set the markers in the graph window`
|`data shiftgraphzero `|Y |`Shift 0 for Graphed wave + or - shift value`
|`data timescale `|Y |`Set cursor display timescale`
|`data undecimate `|Y |`Un-decimate samples`
|`data zerocrossings `|Y |`Count time between zero-crossings`
|`data convertbitstream `|Y |`Convert GraphBuffer's 0/1 values to 127 / -127`
|`data getbitstream `|Y |`Convert GraphBuffer's >=1 values to 1 and <1 to 0`
|`data asn1 `|Y |`ASN1 decoder`
|`data atr `|Y |`ATR lookup`
|`data bin2hex `|Y |`Converts binary to hexadecimal`
|`data bitsamples `|N |`Get raw samples as bitstring`
|`data bmap `|Y |`Convert hex value according a binary template`
|`data clear `|Y |`Clears bigbuf on deviceside and graph window`
|`data crypto `|Y |`Encrypt and decrypt data`
|`data diff `|Y |`Diff of input files`
|`data hexsamples `|N |`Dump big buffer as hex bytes`
|`data hex2bin `|Y |`Converts hexadecimal to binary`
|`data load `|Y |`Load contents of file into graph window`
|`data num `|Y |`Converts dec/hex/bin`
|`data print `|Y |`Print the data in the DemodBuffer`
|`data samples `|N |`Get raw samples for graph window ( GraphBuffer )`
|`data save `|Y |`Save signal trace data ( GraphBuffer )`
|`data setdebugmode `|Y |`Set Debugging Level on client side`
|`data xor `|Y |`Xor a input string`
### emv
@ -857,9 +855,10 @@ Check column "offline" for their availability.
|command |offline |description
|------- |------- |-----------
|`lf awid help `|Y |`this help`
|`lf awid brute `|N |`bruteforce card number against reader`
|`lf awid clone `|N |`clone AWID tag to T55x7, Q5/T5555 or EM4305/4469`
|`lf awid demod `|Y |`demodulate an AWID FSK tag from the GraphBuffer`
|`lf awid reader `|N |`attempt to read and extract tag data`
|`lf awid clone `|N |`clone AWID tag to T55x7, Q5/T5555 or EM4305/4469`
|`lf awid sim `|N |`simulate AWID tag`
|`lf awid brute `|N |`bruteforce card number against reader`
|`lf awid watch `|N |`continuously watch for cards. Reader mode`
@ -923,7 +922,7 @@ Check column "offline" for their availability.
|`lf em 4x05 help `|Y |`This help`
|`lf em 4x05 clonehelp `|N |`Shows the available clone commands`
|`lf em 4x05 brute `|N |`Bruteforce password`
|`lf em 4x05 chk `|N |`Check passwords from dictionary`
|`lf em 4x05 chk `|N |`Check passwords`
|`lf em 4x05 config `|Y |`Create common configuration words`
|`lf em 4x05 demod `|Y |`Demodulate a EM4x05/EM4x69 tag from the GraphBuffer`
|`lf em 4x05 dump `|N |`Dump EM4x05/EM4x69 tag`
@ -944,7 +943,7 @@ Check column "offline" for their availability.
|------- |------- |-----------
|`lf em 4x50 help `|Y |`This help`
|`lf em 4x50 brute `|N |`Bruteforce attack to find password`
|`lf em 4x50 chk `|N |`Check passwords from dictionary`
|`lf em 4x50 chk `|N |`Check passwords`
|`lf em 4x50 dump `|N |`Dump EM4x50 tag`
|`lf em 4x50 info `|N |`Tag information`
|`lf em 4x50 login `|N |`Login into EM4x50 tag`
@ -1042,16 +1041,19 @@ Check column "offline" for their availability.
|`lf hitag help `|Y |`This help`
|`lf hitag list `|Y |`List Hitag trace history`
|`lf hitag info `|N |`Hitag 2 tag information`
|`lf hitag selftest `|Y |`Perform self test`
|`lf hitag dump `|N |`Dump Hitag 2 tag`
|`lf hitag read `|N |`Read Hitag memory`
|`lf hitag sniff `|N |`Eavesdrop Hitag communication`
|`lf hitag view `|Y |`Display content from tag dump file`
|`lf hitag wrbl `|N |`Write a block (page) in Hitag memory`
|`lf hitag sniff `|N |`Eavesdrop Hitag communication`
|`lf hitag cc `|N |`Hitag S: test all provided challenges`
|`lf hitag ta `|N |`Hitag 2: test all recorded authentications`
|`lf hitag eload `|N |`Upload file into emulator memory`
|`lf hitag eview `|N |`View emulator memory`
|`lf hitag sim `|N |`Simulate Hitag transponder`
|`lf hitag cc `|N |`Hitag S: test all provided challenges`
|`lf hitag chk `|N |`Check keys`
|`lf hitag lookup `|Y |`Uses authentication trace to check for key in dictionary file`
|`lf hitag ta `|N |`Hitag 2: test all recorded authentications`
### lf idteck
@ -1285,7 +1287,7 @@ Check column "offline" for their availability.
|`lf t55xx wakeup `|N |`Send AOR wakeup command`
|`lf t55xx write `|N |`Write T55xx block data`
|`lf t55xx bruteforce `|N |`Simple bruteforce attack to find password`
|`lf t55xx chk `|N |`Check passwords from dictionary/flash`
|`lf t55xx chk `|N |`Check passwords`
|`lf t55xx protect `|N |`Password protect tag`
|`lf t55xx recoverpw `|N |`Try to recover from bad password write from a cloner`
|`lf t55xx sniff `|Y |`Attempt to recover T55xx commands from sample buffer`

View file

@ -127,6 +127,17 @@ extern bool g_tearoff_enabled;
#endif
#endif
// endian change for 48bit
#ifndef BSWAP_48
#define BSWAP_48(x) \
(((uint64_t)(x) << 40) & 0x0000ff0000000000ULL) | \
(((uint64_t)(x) << 24) & 0x000000ff00000000ULL) | \
(((uint64_t)(x) << 8) & 0x00000000ff000000ULL) | \
(((uint64_t)(x) >> 8) & 0x000000000ff0000ULL) | \
(((uint64_t)(x) >> 24) & 0x00000000000ff00ULL) | \
(((uint64_t)(x) >> 40) & 0x0000000000000ffULL)
#endif
// endian change for 32bit
#ifdef __GNUC__
#ifndef BSWAP_32

View file

@ -39,37 +39,28 @@ typedef enum {
RHT2F_UID_ONLY = 26,
WHT2F_PASSWORD = 27,
HT2_LAST_CMD = WHT2F_PASSWORD,
} hitag_function;
typedef struct {
uint8_t password[4];
} PACKED rht2d_password;
} PACKED hitag_function;
typedef struct {
hitag_function cmd;
int16_t page;
uint8_t data[4];
uint8_t NrAr[8];
uint8_t data[4];
} PACKED rht2d_authenticate;
typedef struct {
uint8_t key[6];
uint8_t data[4];
} PACKED rht2d_crypto;
uint8_t pwd[4];
typedef struct {
// Hitag 1 section.
// will reuse pwd or key field.
uint8_t key_no;
uint8_t logdata_0[4];
uint8_t logdata_1[4];
uint8_t nonce[4];
uint8_t key[4];
} PACKED rht1d_authenticate;
typedef union {
rht2d_password pwd;
rht1d_authenticate ht1auth;
rht2d_authenticate auth;
rht2d_crypto crypto;
} hitag_data;
} PACKED lf_hitag_data_t;
typedef struct {
int status;
uint8_t data[48];
} PACKED lf_hitag_crack_response_t;
//---------------------------------------------------------
// Hitag S

View file

@ -67,9 +67,9 @@ def hitag2_init(key, uid, nonce):
#print '%012x' % state
#print '%012x' % (int("{0:048b}".format(state)[::-1],2))
for i in range(0, 32):
nonce_bit = (f20(state) ^ ((nonce >> (31-i)) & 1))
nonce_bit = (f20(state) ^ ((nonce >> (31 - i)) & 1))
#print nonce_bit
state = (state >> 1) | (((nonce_bit ^ (key >> (31-i))) & 1) << 47)
state = (state >> 1) | (((nonce_bit ^ (key >> (31 - i))) & 1) << 47)
#print '%012x' % state
#print '%012x' % (int("{0:048b}".format(state)[::-1],2))
return state
@ -81,6 +81,7 @@ def lfsr_feedback(state):
^ (state >> 26) ^ (state >> 30) ^ (state >> 41)
^ (state >> 42) ^ (state >> 43) ^ (state >> 46)
^ (state >> 47)) & 1)
def lfsr(state):
return (state >> 1) + (lfsr_feedback(state) << 47)
@ -93,15 +94,17 @@ def lfsr_feedback_inv(state):
^ (state >> 46)) & 1)
def lfsr_inv(state):
return ((state << 1) + (lfsr_feedback_inv(state))) & ((1<<48)-1)
return ((state << 1) + (lfsr_feedback_inv(state))) & ((1 << 48) - 1)
def hitag2(state, length=48):
c = 0
for i in range(0, length):
c = (c << 1) | f20(state)
#print '%012x' % state
#print '%012x' % (int("{0:048b}".format(state)[::-1],2))
#print ('%012x' % state)
state = lfsr(state)
#print ('%012x' % (int("{0:048b}".format(state)[::-1],2)))
#print('%08X %08X' % (c, state))
#print('final: %08X %08X' % (c, state))
return c
if __name__ == "__main__":
@ -111,8 +114,15 @@ if __name__ == "__main__":
uid = int(sys.argv[2], 16)
n = int(sys.argv[3])
for i in range(n):
nonce = random.randrange(2**32)
state = hitag2_init(key, uid, nonce)
print('%08X %08X' % (nonce, hitag2(state, 32)^0xffffffff))
nonceA = random.randrange(2**32)
stateA = hitag2_init(key, uid, nonceA)
csA = hitag2(stateA, 32) ^ 0xffffffff
# print('%08X %08X' % (nonceA, csA))
nonceB = random.randrange(2**32)
stateB = hitag2_init(key, uid, nonceB)
csB = hitag2(stateB, 32) ^ 0xffffffff
print('./ht2crack5opencl %08X %08X %08X %08X %08X' % (uid, nonceA, csA, nonceB, csB))
print('lf hitag lookup --uid %08X --nr %08X --ar %08X --key %012X' % (uid, nonceA, csA, key))
else:
print("Usage: python %s <key> <uid> <nr of nRaR to generate>" % sys.argv[0])

View file

@ -414,6 +414,7 @@ while true; do
if ! CheckExecute "nfc decode test - signature" "$CLIENTBIN -c 'nfc decode -d 03FF010194113870696C65742E65653A656B616172743A3266195F26063132303832325904202020205F28033233335F2701316E1B5A13333038363439303039303030323636343030355304EBF2CE704103000000AC536967010200803A2448FCA7D354A654A81BD021150D1A152D1DF4D7A55D2B771F12F094EAB6E5E10F2617A2F8DAD4FD38AFF8EA39B71C19BD42618CDA86EE7E144636C8E0E7CFC4096E19C3680E09C78A0CDBC05DA2D698E551D5D709717655E56FE3676880B897D2C70DF5F06ECE07C71435255144F8EE41AF110E7B180DA0E6C22FB8FDEF61800025687474703A2F2F70696C65742E65652F6372742F33303836343930302D303030312E637274FE'" "30864900-0001.crt"; then break; fi
echo -e "\n${C_BLUE}Testing LF:${C_NC}"
if ! CheckExecute "lf hitag2 test" "$CLIENTBIN -c 'lf hitag selftest'" "Tests \( ok"; then break; fi
if ! CheckExecute "lf cotag demod test" "$CLIENTBIN -c 'data load -f traces/lf_cotag_220_8331.pm3; data norm; data cthreshold -u 50 -d -20; data envelope; data raw --ar -c 272; lf cotag demod'" \
"COTAG Found: FC 220, CN: 8331 Raw: FFB841170363FFFE00001E7F00000000"; then break; fi
if ! CheckExecute "lf AWID test" "$CLIENTBIN -c 'data load -f traces/lf_AWID-15-259.pm3;lf search -1'" "AWID ID found"; then break; fi