diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f15617c0..f32ea1497 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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] + - Updates `hf mfdes` functions, improved logging and added new commands (@bkerler) - Updated 'legic.lua' and 'legic_clone.lua' script - works with current command set (@Pizza_4u) - Rewrote `hf mfdes` functions and added apdu debugging (@bkerler) - Add Mifare Desfire GetDFNames and improve HF MFDES Enum output (@bkerler) diff --git a/Makefile.platform.sample b/Makefile.platform.sample index 9d0e2d965..8d587e3b7 100644 --- a/Makefile.platform.sample +++ b/Makefile.platform.sample @@ -5,3 +5,4 @@ PLATFORM=PM3RDV4 # If you want more than one PLATFORM_EXTRAS option, separate them by spaces: #PLATFORM_EXTRAS=BTADDON #STANDALONE=LF_SAMYRUN +STANDALONE=LF_ICEHID diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 23b3a2239..f789d87c6 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -2672,8 +2672,10 @@ void ReaderIso14443a(PacketCommandNG *c) { uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; uint8_t par[MAX_PARITY_SIZE] = {0x00}; - if ((param & ISO14A_CONNECT)) + if ((param & ISO14A_CONNECT)) { + iso14_pcb_blocknum = 0; clear_trace(); + } set_tracing(true); diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 31f2cae58..10beb4489 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -29,7 +29,7 @@ # define FWT_TIMEOUT_14B 35312 #endif #ifndef ISO14443B_DMA_BUFFER_SIZE -# define ISO14443B_DMA_BUFFER_SIZE 256 +# define ISO14443B_DMA_BUFFER_SIZE 512 //changed this from 256 #endif #ifndef RECEIVE_MASK # define RECEIVE_MASK (ISO14443B_DMA_BUFFER_SIZE-1) @@ -37,7 +37,7 @@ // Guard Time (per 14443-2) #ifndef TR0 -# define TR0 0 +# define TR0 32 //this value equals 8 ETU = 32 ssp clk (w/ 424 khz) #endif // Synchronization time (per 14443-2) @@ -261,6 +261,10 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { // 80/fs < TR1 < 200/fs // 10 ETU < TR1 < 24 ETU + // Send TR1. + // 10-11 ETU * 4times samples ONES + for (int i = 0; i < 10; i++) { SEND4STUFFBIT(1); } + // Send SOF. // 10-11 ETU * 4times samples ZEROS for (int i = 0; i < 10; i++) { SEND4STUFFBIT(0); } @@ -307,7 +311,7 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { //for(i = 0; i < 10; i++) { ToSendStuffBit(0); } // why this? - for (int i = 0; i < 40; i++) { SEND4STUFFBIT(1); } + for (int i = 0; i < 2; i++) { SEND4STUFFBIT(1); } //for(i = 0; i < 40; i++) { ToSendStuffBit(1); } // Convert from last byte pos to length diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index b2f45d117..aa70e5ccb 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -16,6 +16,7 @@ #include "commonutil.h" #include "util.h" #include "mifare.h" +#include "ticks.h" #define MAX_APPLICATION_COUNT 28 #define MAX_FILE_COUNT 16 @@ -103,7 +104,7 @@ void MifareDesfireGetInformation() { uint8_t versionSW[7]; uint8_t details[14]; } PACKED payload; - + /* 1 = PCB 1 2 = cid 2 @@ -116,6 +117,9 @@ void MifareDesfireGetInformation() { clear_trace(); set_tracing(true); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + // reset the pcb_blocknum, + pcb_blocknum = 0; // card select - information if (!iso14443a_select_card(NULL, &card, NULL, true, 0, false)) { @@ -137,7 +141,7 @@ void MifareDesfireGetInformation() { memcpy(payload.uid, card.uid, sizeof(payload.uid)); LED_A_ON(); - uint8_t cmd[] = {GET_VERSION, 0x00, 0x00, 0x00}; + uint8_t cmd[] = {0x90, GET_VERSION, 0x00, 0x00, 0x00}; size_t cmd_len = sizeof(cmd); len = DesfireAPDU(cmd, cmd_len, resp); @@ -152,7 +156,7 @@ void MifareDesfireGetInformation() { memcpy(payload.versionHW, resp + 1, sizeof(payload.versionHW)); // ADDITION_FRAME 1 - cmd[0] = ADDITIONAL_FRAME; + cmd[1] = ADDITIONAL_FRAME; len = DesfireAPDU(cmd, cmd_len, resp); if (!len) { print_result("ERROR <--: ", resp, len); @@ -178,7 +182,7 @@ void MifareDesfireGetInformation() { LED_B_ON(); reply_ng(CMD_HF_DESFIRE_INFO, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload)); LED_B_OFF(); - + // reset the pcb_blocknum, pcb_blocknum = 0; OnSuccess(); @@ -246,9 +250,15 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) else if (arg1 == 1) Desfire_des_key_new(keybytes, key); - cmd[0] = AUTHENTICATE; - cmd[1] = arg2; //keynumber - len = DesfireAPDU(cmd, 2, resp); + cmd[0] = 0x90; + cmd[1] = AUTHENTICATE; + cmd[2] = 0x0; + cmd[3] = 0x0; + cmd[4] = 0x1; + cmd[5] = arg2; //keynumber + cmd[6] = 0x0; + len = DesfireAPDU(cmd, 7, resp); + if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -257,14 +267,13 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if (resp[2] == 0xaf) { - } else { + if (resp[2] == (uint8_t)0xaf) { DbpString("Authentication failed. Invalid key number."); OnError(3); return; } - memcpy(encRndB, resp + 3, 8); + memcpy(encRndB, resp + 1, 8); if (arg1 == 2) tdes_dec(&decRndB, &encRndB, key->data); else if (arg1 == 1) @@ -275,6 +284,11 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) // This should be random uint8_t decRndA[8] = {0x00}; + uint32_t value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[0]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[4]); + memcpy(RndA, decRndA, 8); uint8_t encRndA[8] = {0x00}; @@ -297,10 +311,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) memcpy(both + 8, encRndB, 8); - cmd[0] = ADDITIONAL_FRAME; - memcpy(cmd + 1, both, 16); - - len = DesfireAPDU(cmd, 17, resp); + cmd[0] = 0x90; + cmd[1] = ADDITIONAL_FRAME; + cmd[2] = 0x00; + cmd[3] = 0x00; + cmd[4] = 0x10; + memcpy(cmd + 5, both, 16); + cmd[16 + 5] = 0x0; + len = DesfireAPDU(cmd, 5 + 16 + 1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -309,14 +327,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if (resp[2] == 0x00) { + if (resp[len - 3] == 0x00) { struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; Desfire_session_key_new(RndA, RndB, key, skey); //print_result("SESSION : ", skey->data, 8); - memcpy(encRndA, resp + 3, 8); + memcpy(encRndA, resp + 1, 8); if (arg1 == 2) tdes_dec(&encRndA, &encRndA, key->data); @@ -326,19 +344,20 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) rol(decRndA, 8); for (int x = 0; x < 8; x++) { if (decRndA[x] != encRndA[x]) { - DbpString("Authentication failed. Cannot varify PICC."); + DbpString("Authentication failed. Cannot verify PICC."); OnError(4); return; } } //Change the selected key to a new value. - /* + /* // Current key is a 3DES key, change it to a DES key if (arg1 == 2) { - cmd[0] = CHANGE_KEY; - cmd[1] = arg2; + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = arg2; uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; @@ -367,20 +386,21 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) buff3[x] = buff3[x] ^ buff2[x]; } tdes_dec(&buff3, &buff3, skey->data); - memcpy(cmd+18,buff3,8); + memcpy(cmd+19,buff3,8); // The command always times out on the first attempt, this will retry until a response // is recieved. len = 0; while(!len) { - len = DesfireAPDU(cmd,26,resp); + len = DesfireAPDU(cmd,27,resp); } } else { // Current key is a DES key, change it to a 3DES key if (arg1 == 1) { - cmd[0] = CHANGE_KEY; - cmd[1] = arg2; + cmd[0] = 0x90; + cmd[1] = CHANGE_KEY; + cmd[2] = arg2; uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; @@ -397,31 +417,31 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) memcpy(buff3 + 1, &second, 1); des_dec(&buff1, &buff1, skey->data); - memcpy(cmd+2,buff1,8); + memcpy(cmd+3,buff1,8); for (int x = 0; x < 8; x++) { buff2[x] = buff2[x] ^ buff1[x]; } des_dec(&buff2, &buff2, skey->data); - memcpy(cmd+10,buff2,8); + memcpy(cmd+11,buff2,8); for (int x = 0; x < 8; x++) { buff3[x] = buff3[x] ^ buff2[x]; } des_dec(&buff3, &buff3, skey->data); - memcpy(cmd+18,buff3,8); + memcpy(cmd+19,buff3,8); // The command always times out on the first attempt, this will retry until a response // is recieved. len = 0; while(!len) { - len = DesfireAPDU(cmd,26,resp); + len = DesfireAPDU(cmd,27,resp); } } } */ - OnSuccess(); + //OnSuccess(); if (arg1 == 2) reply_old(CMD_ACK, 1, 0, 0, skey->data, 16); else if (arg1 == 1) @@ -433,11 +453,139 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } } break; - case 2: + case 2: { //SendDesfireCommand(AUTHENTICATE_ISO, &arg2, resp); - break; - case 3: { + uint8_t keybytes[16]; + uint8_t RndA[8] = {0x00}; + uint8_t RndB[8] = {0x00}; + if (arg1 == 2) { + if (datain[1] == 0xff) { + memcpy(keybytes, PICC_MASTER_KEY16, 16); + } else { + memcpy(keybytes, datain + 1, datalen); + } + } else { + if (arg1 == 1) { + if (datain[1] == 0xff) { + uint8_t null_key_data8[8] = {0x00}; + memcpy(keybytes, null_key_data8, 8); + } else { + memcpy(keybytes, datain + 1, datalen); + } + } + } + + struct desfire_key defaultkey = {0}; + desfirekey_t key = &defaultkey; + + if (arg1 == 2) + Desfire_3des_key_new_with_version(keybytes, key); + else if (arg1 == 1) + Desfire_des_key_new(keybytes, key); + + cmd[0] = AUTHENTICATE; + cmd[1] = arg2; //keynumber + len = DesfireAPDU(cmd, 2, resp); + + if (!len) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if (resp[2] == (uint8_t)0xaf) { + DbpString("Authentication failed. Invalid key number."); + OnError(3); + return; + } + + memcpy(encRndB, resp + 2, 8); + if (arg1 == 2) + tdes_dec(&decRndB, &encRndB, key->data); + else if (arg1 == 1) + des_dec(&decRndB, &encRndB, key->data); + + memcpy(RndB, decRndB, 8); + rol(decRndB, 8); + + // This should be random + uint8_t decRndA[8] = {0x00}; + uint32_t value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[0]); + value = prng_successor(GetTickCount(), 32); + num_to_bytes(value, 4, &decRndA[4]); + + memcpy(RndA, decRndA, 8); + uint8_t encRndA[8] = {0x00}; + + if (arg1 == 2) + tdes_dec(&encRndA, &decRndA, key->data); + else if (arg1 == 1) + des_dec(&encRndA, &decRndA, key->data); + + memcpy(both, encRndA, 8); + + for (int x = 0; x < 8; x++) { + decRndB[x] = decRndB[x] ^ encRndA[x]; + + } + + if (arg1 == 2) + tdes_dec(&encRndB, &decRndB, key->data); + else if (arg1 == 1) + des_dec(&encRndB, &decRndB, key->data); + + memcpy(both + 8, encRndB, 8); + + cmd[0] = ADDITIONAL_FRAME; + memcpy(cmd + 1, both, 16); + len = DesfireAPDU(cmd, 1 + 16, resp); + if (!len) { + if (DBGLEVEL >= DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if (resp[1] == 0x00) { + struct desfire_key sessionKey = {0}; + desfirekey_t skey = &sessionKey; + Desfire_session_key_new(RndA, RndB, key, skey); + //print_result("SESSION : ", skey->data, 8); + + memcpy(encRndA, resp + 2, 8); + + if (arg1 == 2) + tdes_dec(&encRndA, &encRndA, key->data); + else if (arg1 == 1) + des_dec(&encRndA, &encRndA, key->data); + + rol(decRndA, 8); + for (int x = 0; x < 8; x++) { + if (decRndA[x] != encRndA[x]) { + DbpString("Authentication failed. Cannot verify PICC."); + OnError(4); + return; + } + } + + //OnSuccess(); + if (arg1 == 2) + reply_old(CMD_ACK, 1, 0, 0, skey->data, 16); + else if (arg1 == 1) + reply_old(CMD_ACK, 1, 0, 0, skey->data, 8); + } else { + DbpString("Authentication failed."); + OnError(6); + return; + } + } + break; + case 3: { //defaultkey uint8_t keybytes[16] = {0x00}; if (datain[1] == 0xff) { @@ -454,13 +602,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) uint8_t IV[16] = {0x00}; mbedtls_aes_init(&ctx); - cmd[0] = AUTHENTICATE_AES; - cmd[1] = 0x0; + cmd[0] = 0x90; + cmd[1] = AUTHENTICATE_AES; cmd[2] = 0x0; - cmd[3] = 0x1; - cmd[4] = arg2; //keynumber - cmd[5] = 0x0; - len = DesfireAPDU(cmd, 6, resp); + cmd[3] = 0x0; + cmd[4] = 0x1; + cmd[5] = arg2; //keynumber + cmd[6] = 0x0; + len = DesfireAPDU(cmd, 7, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -482,6 +631,14 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_DECRYPT, 16, IV, encRndB, decRndB); rol(decRndB, 16); uint8_t nonce[16] = {0x00}; + uint32_t val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[0]); + val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[4]); + val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[8]); + val = prng_successor(GetTickCount(), 32); + num_to_bytes(val, 4, &nonce[12]); memcpy(both, nonce, 16); memcpy(both + 16, decRndB, 16); uint8_t encBoth[32] = {0x00}; @@ -494,14 +651,15 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, 32, IV, both, encBoth); - cmd[0] = ADDITIONAL_FRAME; - cmd[1] = 0x00; + cmd[0] = 0x90; + cmd[1] = ADDITIONAL_FRAME; cmd[2] = 0x00; - cmd[3] = 0x20; - memcpy(cmd + 4, encBoth, 32); - cmd[36]=0x0; + cmd[3] = 0x00; + cmd[4] = 0x20; + memcpy(cmd + 5, encBoth, 32); + cmd[32 + 5] = 0x0; - len = DesfireAPDU(cmd, 37, resp); // 4 + 32 + 1 == 37 + len = DesfireAPDU(cmd, 5 + 32 + 1, resp); if (!len) { if (DBGLEVEL >= DBG_ERROR) { DbpString("Authentication failed. Card timeout."); @@ -510,7 +668,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) return; } - if ((resp[1+16] == 0x91)&&(resp[1+16+1] == 0x00)) { + if ((resp[1 + 16] == 0x91) && (resp[1 + 16 + 1] == 0x00)) { // Create AES Session key struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; @@ -526,7 +684,7 @@ void MifareDES_Auth1(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } } - OnSuccess(); + //OnSuccess(); reply_mix(CMD_ACK, 1, len, 0, resp, len); } @@ -557,10 +715,10 @@ int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout) { // if we received an I- or R(ACK)-Block with a block number equal to the // current block number, toggle the current block number if (len >= 4 // PCB+CID+CRC = 4 bytes - && ((resp[0] & 0xC0) == 0 // I-Block - || (resp[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 - && (resp[0] & 0x01) == pcb_blocknum) { // equal block numbers - pcb_blocknum ^= 1; //toggle next block + && ((resp[0] & 0xC0) == 0 // I-Block + || (resp[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 + && (resp[0] & 0x01) == pcb_blocknum) { // equal block numbers + pcb_blocknum ^= 1; //toggle next block } memcpy(dataout, resp, len); @@ -570,7 +728,7 @@ int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout) { // CreateAPDU size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout) { - size_t cmdlen = MIN(len + 4, PM3_CMD_DATA_SIZE - 1); + size_t cmdlen = MIN(len + 3, PM3_CMD_DATA_SIZE - 1); uint8_t cmd[cmdlen]; memset(cmd, 0, cmdlen); @@ -578,18 +736,18 @@ size_t CreateAPDU(uint8_t *datain, size_t len, uint8_t *dataout) { cmd[0] = 0x02; // 0x0A = send cid, 0x02 = no cid. cmd[0] |= pcb_blocknum; // OR the block number into the PCB - if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("pcb_blocknum %d == %d ", pcb_blocknum, cmd[0] ); + if (DBGLEVEL >= DBG_EXTENDED) Dbprintf("pcb_blocknum %d == %d ", pcb_blocknum, cmd[0]); - cmd[1] = 0x90; // CID: 0x00 //TODO: allow multiple selected cards + //cmd[1] = 0x90; // CID: 0x00 //TODO: allow multiple selected cards - memcpy(cmd + 2, datain, len); - AddCrc14A(cmd, len + 2); - -/* -hf 14a apdu -sk 90 60 00 00 00 -hf 14a apdu -k 90 AF 00 00 00 -hf 14a apdu 90AF000000 -*/ + memcpy(cmd + 1, datain, len); + AddCrc14A(cmd, len + 1); + + /* + hf 14a apdu -sk 90 60 00 00 00 + hf 14a apdu -k 90 AF 00 00 00 + hf 14a apdu 90AF000000 + */ memcpy(dataout, cmd, cmdlen); return cmdlen; } diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index b0bf532b0..6d269e38e 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -697,7 +697,7 @@ int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData) { int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData) { int len; - uint8_t data[17] = {MFDES_AUTHENTICATION_FRAME}; + uint8_t data[17] = {MFDES_ADDITIONAL_FRAME}; memcpy(data + 1, key, 16); uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00}; diff --git a/client/cmdhflist.c b/client/cmdhflist.c index 871cd68a3..7aeac0bc7 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -675,7 +675,7 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { // it's basically a ISO14443a tag, so try annotation from there if (applyIso14443a(exp, size, cmd, cmdsize) == 0) { - + // S-block 11xxx010 if ((cmd[0] & 0xC0) && (cmdsize == 3)) { switch ((cmd[0] & 0x30)) { @@ -707,9 +707,8 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { if ((cmd[0] & 0x04) == 0x04) // nad byte following pos++; - + for (uint8_t i = 0; i < 2; i++, pos++) { - switch (cmd[pos]) { case MFDES_CREATE_APPLICATION: snprintf(exp, size, "CREATE APPLICATION"); @@ -819,9 +818,12 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t *cmd, uint8_t cmdsize) { case MFDES_GET_KEY_VERSION: snprintf(exp, size, "GET KEY VERSION"); break; - case MFDES_AUTHENTICATION_FRAME: + case MFDES_ADDITIONAL_FRAME: snprintf(exp, size, "AUTH FRAME / NEXT FRAME"); break; + case MFDES_READSIG: + snprintf(exp, size, "READ SIGNATURE"); + break; default: break; } diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 931471961..0afc03cde 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -34,14 +34,17 @@ uint8_t key_ones_data[16] = { 0x01 }; uint8_t key_defa_data[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; uint8_t key_picc_data[16] = { 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f }; +#define status(x) ( ((uint16_t)(0x91<<8)) + x ) + typedef enum { UNKNOWN = 0, - MF3ICD40, - EV1, - EV2, - EV3, - LIGHT, -} desfire_cardtype_t; + DESFIRE_MF3ICD40, + DESFIRE_EV1, + DESFIRE_EV2, + DESFIRE_EV3, + DESFIRE_LIGHT, + PLUS_EV1, +} nxp_cardtype_t; typedef struct { uint8_t aid[3]; @@ -52,14 +55,65 @@ typedef struct { static int CmdHelp(const char *Cmd); /* - uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; - int res = ExchangeRAW14a(cmd, sizeof(cmd), false, false, data, sizeof(data), &datalen, false); - - if (!res && datalen > 1 && data[0] == 0x09) { - SLmode = 0; - } - + The 7 MSBits (= n) code the storage size itself based on 2^n, + the LSBit is set to '0' if the size is exactly 2^n + and set to '1' if the storage size is between 2^n and 2^(n+1). + For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. */ +static char *getCardSizeStr(uint8_t fsize) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + uint16_t usize = 1 << ((fsize >> 1) + 1); + uint16_t lsize = 1 << (fsize >> 1); + + // is LSB set? + if (fsize & 1) + sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); + return buf; +} + +static char *getProtocolStr(uint8_t id, bool hw) { + + static char buf[50] = {0x00}; + char *retStr = buf; + + if (id == 0x04) { + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3 MIFARE, 14443-4") ")", id); + } else if (id == 0x05) { + if (hw) + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-2, 14443-3") ")", id); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); + } else { + sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); + } + return buf; +} + +static char *getVersionStr(uint8_t major, uint8_t minor) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + if (major == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); + else if (major == 0x01 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); + else if (major == 0x12 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); +// else if (major == 0x13 && minor == 0x00) +// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); + else if (major == 0x30 && minor == 0x00) + sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); + else + sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); + return buf; +} + int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { @@ -105,41 +159,196 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t if (sw) *sw = isw; - if (isw != 0x9000 && isw != MFDES_SUCCESS_FRAME_RESP && isw != MFDES_ADDITIONAL_FRAME_RESP) { + if (isw != 0x9000 && isw != status(MFDES_S_OPERATION_OK) && isw != status(MFDES_S_SIGNATURE) && isw != status(MFDES_S_ADDITIONAL_FRAME) && isw != status(MFDES_S_NO_CHANGES)) { if (GetAPDULogging()) { if (isw >> 8 == 0x61) { - PrintAndLogEx(ERR, "APDU chaining len:%02x -->", isw & 0xff); + PrintAndLogEx(ERR, "APDU chaining len: 0x%02x -->", isw & 0xff); } else { - PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); + PrintAndLogEx(ERR, "APDU(%02x%02x) ERROR: [0x%4X] %s", apdu.CLA, apdu.INS, isw, GetAPDUCodeDescription(isw >> 8, isw & 0xff)); return PM3_EAPDU_FAIL; } } + return PM3_EAPDU_FAIL; } - return PM3_SUCCESS; } +static char *getstatus(uint16_t *sw) { + if (sw == NULL) return "--> sw argument error. This should never happen !"; + if (((*sw >> 8) & 0xFF) == 0x91) { + switch (*sw & 0xFF) { + case MFDES_E_OUT_OF_EEPROM: + return "Out of Eeprom, insufficient NV-Memory to complete command"; + case MFDES_E_ILLEGAL_COMMAND_CODE: + return "Command code not supported"; + + case MFDES_E_INTEGRITY_ERROR: + return "CRC or MAC does not match data / Padding bytes invalid"; + + case MFDES_E_NO_SUCH_KEY: + return "Invalid key number specified"; + + case MFDES_E_LENGTH: + return "Length of command string invalid"; + + case MFDES_E_PERMISSION_DENIED: + return "Current configuration/status does not allow the requested command"; + + case MFDES_E_PARAMETER_ERROR: + return "Value of the parameter(s) invalid"; + + case MFDES_E_APPLICATION_NOT_FOUND: + return "Requested AID not present on PICC"; + + case MFDES_E_APPL_INTEGRITY: + return "Application integrity error, application will be disabled"; + + case MFDES_E_AUTHENTIFICATION_ERROR: + return "Current authentication status does not allow the requested command"; + + case MFDES_E_BOUNDARY: + return "Attempted to read/write data from/to beyong the file's/record's limit"; + + case MFDES_E_PICC_INTEGRITY: + return "PICC integrity error, PICC will be disabled"; + + case MFDES_E_COMMAND_ABORTED: + return "Previous command was not fully completed / Not all Frames were requested or provided by the PCD"; + + case MFDES_E_PICC_DISABLED: + return "PICC was disabled by an unrecoverable error"; + + case MFDES_E_COUNT: + return "Application count is limited to 28, not addition CreateApplication possible"; + + case MFDES_E_DUPLICATE: + return "Duplicate entry: File/Application does already exist"; + + case MFDES_E_EEPROM: + return "Eeprom error due to loss of power, internal backup/rollback mechanism activated"; + + case MFDES_E_FILE_NOT_FOUND: + return "Specified file number does not exist"; + + case MFDES_E_FILE_INTEGRITY: + return "File integrity error, file will be disabled"; + + default: + return "Unknown error"; + } + } + return "Unknown error"; +} + +static char *GetErrorString(int res, uint16_t *sw) { + switch (res) { + case PM3_EAPDU_FAIL: + return getstatus(sw); + case PM3_EUNDEF: + return "Undefined error"; + case PM3_EINVARG: + return "Invalid argument(s)"; + case PM3_EDEVNOTSUPP: + return "Operation not supported by device"; + case PM3_ETIMEOUT: + return "Operation timed out"; + case PM3_EOPABORTED: + return "Operation aborted (by user)"; + case PM3_ENOTIMPL: + return "Not (yet) implemented"; + case PM3_ERFTRANS: + return "Error while RF transmission"; + case PM3_EIO: + return "Input / output error"; + case PM3_EOVFLOW: + return "Buffer overflow"; + case PM3_ESOFT: + return "Software error"; + case PM3_EFLASH: + return "Flash error"; + case PM3_EMALLOC: + return "Memory allocation error"; + case PM3_EFILE: + return "File error"; + case PM3_ENOTTY: + return "Generic TTY error"; + case PM3_EINIT: + return "Initialization error"; + case PM3_EWRONGANSVER: + return "Expected a different answer error"; + case PM3_EOUTOFBOUND: + return "Memory out-of-bounds error"; + case PM3_ECARDEXCHANGE: + return "Exchange with card error"; + case PM3_EAPDU_ENCODEFAIL: + return "Failed to create APDU"; + case PM3_ENODATA: + return "No data"; + case PM3_EFATAL: + return "Fatal error"; + default: + break; + } + return ""; +} + +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize, bool readalldata) { + if (apdu == NULL) { + PrintAndLogEx(DEBUG, "APDU=NULL"); + return PM3_EINVARG; + } + if (dest == NULL) { + PrintAndLogEx(DEBUG, "DEST=NULL"); + return PM3_EINVARG; + } + if (sw == NULL) { + PrintAndLogEx(DEBUG, "SW=NULL"); + return PM3_EINVARG; + } + if (recv_len == NULL) { + PrintAndLogEx(DEBUG, "RECV_LEN=NULL"); + return PM3_EINVARG; + } -static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize) { - //SetAPDULogging(true); *sw = 0; uint8_t data[255 * 5] = {0x00}; int resplen = 0; int pos = 0; int i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return res; - if (*sw != MFDES_ADDITIONAL_FRAME_RESP && *sw != MFDES_SUCCESS_FRAME_RESP) return PM3_ESOFT; + if (res != PM3_SUCCESS) { + PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); + return res; + } if (dest != NULL) { memcpy(dest, data, resplen); } pos += resplen; - if (*sw == MFDES_ADDITIONAL_FRAME_RESP) { + if (!readalldata) { + if (*sw == status(MFDES_ADDITIONAL_FRAME)) { + apdu->INS = MFDES_ABORT_TRANSACTION; + apdu->Lc = 0; + apdu->P1 = 0; + apdu->P2 = 0; + res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); + return PM3_SUCCESS; + } + return res; + } + + while (*sw == status(MFDES_ADDITIONAL_FRAME)) { apdu->INS = MFDES_ADDITIONAL_FRAME; //0xAF + apdu->Lc = 0; + apdu->P1 = 0; + apdu->P2 = 0; res = DESFIRESendApdu(false, true, *apdu, data, sizeof(data), &resplen, sw); - if (res != PM3_SUCCESS) return res; + if (res != PM3_SUCCESS) { + PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); + return res; + } + if (dest != NULL) { if (splitbysize) { memcpy(&dest[i * splitbysize], data, resplen); @@ -149,85 +358,97 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l } } pos += resplen; - } - if (splitbysize) *recv_len = i; - else { - *recv_len = pos; - } - //SetAPDULogging(false); - return PM3_SUCCESS; + if (*sw != status(MFDES_ADDITIONAL_FRAME)) break; + } + + *recv_len = (splitbysize) ? i : pos; + return PM3_SUCCESS; } -static desfire_cardtype_t getCardType(uint8_t major, uint8_t minor) { +static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { if (major == 0x00) - return MF3ICD40; - else if (major == 0x01 && minor == 0x00) - return EV1; - else if (major == 0x12 && minor == 0x00) - return EV2; -// else if (major == 0x13 && minor == 0x00) -// return EV3; - else if (major == 0x30 && minor == 0x00) - return LIGHT; - else - return UNKNOWN; + return DESFIRE_MF3ICD40; + if (major == 0x01 && minor == 0x00) + return DESFIRE_EV1; + if (major == 0x12 && minor == 0x00) + return DESFIRE_EV2; +// if (major == 0x13 && minor == 0x00) +// return DESFIRE_EV3; + if (major == 0x30 && minor == 0x00) + return DESFIRE_LIGHT; + if (major == 0x11 && minor == 0x00 ) + return PLUS_EV1; + + return UNKNOWN; } -//none +// -- test if card supports 0x0A static int test_desfire_authenticate() { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } -// none +// -- test if card supports 0x1A static int test_desfire_authenticate_iso() { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } -//none +// -- test if card supports 0xAA static int test_desfire_authenticate_aes() { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 int recv_len = 0; uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0); + return send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, false); } -// --- FREE MEM +// --- GET FREE MEM static int desfire_print_freemem(uint32_t free_mem) { PrintAndLogEx(SUCCESS, " Available free memory on card : " _GREEN_("%d bytes"), free_mem); return PM3_SUCCESS; } -// init / disconnect static int get_desfire_freemem(uint32_t *free_mem) { + if (free_mem == NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E + *free_mem = 0; int recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; - int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0); - if (res == PM3_SUCCESS) { - *free_mem = le24toh(fmem); + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS ) return res; - } - *free_mem = 0; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + + *free_mem = le24toh(fmem); return res; } - // --- GET SIGNATURE -static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, desfire_cardtype_t card_type) { +static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, nxp_cardtype_t card_type) { + if (uid == NULL) { + PrintAndLogEx(DEBUG, "UID=NULL"); + return PM3_EINVARG; + } + if (signature == NULL) { + PrintAndLogEx(DEBUG, "SIGNATURE=NULL"); + return PM3_EINVARG; + } // DESFire Ev3 - wanted // ref: MIFARE Desfire Originality Signature Validation @@ -237,7 +458,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign {"NTAG413DNA, DESFire EV1", "04BB5D514F7050025C7D0F397310360EEC91EAF792E96FC7E0F496CB4E669D414F877B7B27901FE67C2E3B33CD39D1C797715189AC951C2ADD"}, {"DESFire EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3A"}, {"NTAG424DNA, NTAG424DNATT, DESFire Light EV2", "04B304DC4C615F5326FE9383DDEC9AA892DF3A57FA7FFB3276192BC0EAA252ED45A865E3B093A3D0DCE5BE29E92F1392CE7DE321E3E5C52B3B"}, - {"DESFire Light EV1", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, + {"DESFire Light", "040E98E117AAA36457F43173DC920A8757267F44CE4EC5ADD3C54075571AEBBF7B942A9774A1D94AD02572427E5AE0A2DD36591B1FB34FCF3D"}, {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} }; @@ -261,8 +482,8 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign return PM3_ESOFT; } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); +// PrintAndLogEx(NORMAL, ""); +// PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_desfire_public_keys[i].desc); PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_desfire_public_keys[i].value); PrintAndLogEx(INFO, " : %.32s", nxp_desfire_public_keys[i].value + 16); @@ -277,34 +498,38 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign return PM3_SUCCESS; } -// init / disconnect static int get_desfire_signature(uint8_t *signature, size_t *signature_len) { - uint8_t c = 0x00; - sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, 0x01, &c}; // 0x3C + + if (signature == NULL) { + PrintAndLogEx(DEBUG, "SIGNATURE=NULL"); + return PM3_EINVARG; + } + if (signature_len == NULL) { + PrintAndLogEx(DEBUG, "SIGNATURE_LEN=NULL"); + return PM3_EINVARG; + } + + uint8_t c[] = {0x00}; + sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, sizeof(c), c}; // 0x3C int recv_len = 0; uint16_t sw = 0; - int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0); + int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0, true); if (res == PM3_SUCCESS) { if (recv_len != 56) { *signature_len = 0; - DropField(); - return PM3_ESOFT; + res = PM3_ESOFT; } else { *signature_len = recv_len; - } - DropField(); - return PM3_SUCCESS; } DropField(); return res; } - // --- KEY SETTING static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { - PrintAndLogEx(SUCCESS, " AID Key settings : %02x", key_settings); + PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings); PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys); PrintAndLogEx(INFO, "-------------------------------------------------------------"); PrintAndLogEx(SUCCESS, " Changekey Access rights"); @@ -333,24 +558,29 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { return PM3_SUCCESS; } -// none static int get_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { + if (key_settings == NULL) { + PrintAndLogEx(DEBUG, "KEY_SETTINGS=NULL"); + return PM3_EINVARG; + } + if (num_keys == NULL) { + PrintAndLogEx(DEBUG, "NUM_KEYS=NULL"); + return PM3_EINVARG; + } sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 int recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; - if (num_keys == NULL) return PM3_ESOFT; - if (key_settings == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0); - if (sw == MFDES_EAUTH_RESP) { - PrintAndLogEx(WARNING, _RED_("[get_desfire_keysettings] Authentication error")); + int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS ) + return res; + if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; - } - if (res != PM3_SUCCESS) return res; *key_settings = data[0]; *num_keys = data[1]; - return PM3_SUCCESS; + return res; } // --- KEY VERSION @@ -359,272 +589,178 @@ static int desfire_print_keyversion(uint8_t key_idx, uint8_t key_version) { return PM3_SUCCESS; } -// none static int get_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { + if (num_versions == NULL) { + PrintAndLogEx(DEBUG, "NUM_VERSIONS=NULL"); + return PM3_EINVARG; + } sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 int recv_len = 0; uint16_t sw = 0; - if (num_versions == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0); - if (sw == MFDES_ENO_SUCH_KEY_RESP) { - PrintAndLogEx(WARNING, _RED_("[get_desfire_keyversion] Key %d doesn't exist"), curr_key); + int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS ) + return res; + + if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; - } + return res; } - -// init / disconnect +// --- GET APPIDS static int get_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { + if (dest == NULL) { + PrintAndLogEx(DEBUG, "DEST=NULL"); + return PM3_EINVARG; + } + if (app_ids_len == NULL) { + PrintAndLogEx(DEBUG, "APP_IDS_LEN=NULL"); + return PM3_EINVARG; + } + sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a int recv_len = 0; uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (app_ids_len == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0); - if (res != PM3_SUCCESS) return res; + int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS ) + return res; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + *app_ids_len = (uint8_t)recv_len & 0xFF; return res; } +// --- GET DF NAMES static int get_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (dfname_count == NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); + } + if (dest == NULL || dfname_count == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d int recv_len = 0; uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (dfname_count == NULL) return PM3_ESOFT; - int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t)); - if (res != PM3_SUCCESS) return res; + int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t), true); + if (res != PM3_SUCCESS) + return res; + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; *dfname_count = recv_len; return res; } - -// init static int get_desfire_select_application(uint8_t *aid) { + if (g_debugMode > 1) { + if (aid == NULL) PrintAndLogEx(ERR, "AID=NULL"); + } + if (aid == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a int recv_len = 0; uint16_t sw = 0; - if (aid == NULL) return PM3_ESOFT; - return send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t)); + int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t), true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't select AID 0x%X -> %s"), (aid[0] << 16) + (aid[1] << 8) + aid[2], GetErrorString(res, &sw)); + DropField(); + return res; + } + return PM3_SUCCESS; } -// none +// none, verified static int get_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (file_ids_len == NULL) PrintAndLogEx(ERR, "FILE_IDS_LEN=NULL"); + } + if (dest == NULL || file_ids_len == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_IDS, 0x00, 0x00, 0x00, NULL}; //0x6f int recv_len = 0; uint16_t sw = 0; - if (dest == NULL) return PM3_ESOFT; - if (file_ids_len == NULL) return PM3_ESOFT; *file_ids_len = 0; - int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0); - if (res != PM3_SUCCESS) return res; + int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't get file ids -> %s"), GetErrorString(res, &sw)); + DropField(); + return res; + } *file_ids_len = recv_len; return res; } +// none, verified static int get_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { + if (g_debugMode > 1) { + if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); + if (destlen == NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); + } + if (dest == NULL || destlen == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_FILE_SETTINGS, 0x00, 0x00, 0x01, &file_id}; // 0xF5 uint16_t sw = 0; - return send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0); -} - -static int CmdHF14ADesInfo(const char *Cmd) { - (void)Cmd; // Cmd is not used so far - - SendCommandNG(CMD_HF_DESFIRE_INFO, NULL, 0); - PacketResponseNG resp; - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_INFO, &resp, 1500)) { - PrintAndLogEx(WARNING, "Command execute timeout"); + int res = send_desfire_cmd(&apdu, false, dest, destlen, &sw, 0, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't get file settings -> %s"), GetErrorString(res, &sw)); DropField(); - return PM3_ETIMEOUT; + return res; } + return res; +} - struct p { - uint8_t isOK; - uint8_t uid[7]; - uint8_t versionHW[7]; - uint8_t versionSW[7]; - uint8_t details[14]; - } PACKED; +typedef struct { + uint8_t aid[3]; + uint8_t keysetting1; + uint8_t keysetting2; + uint8_t fid[2]; + uint8_t name[16]; +} aidhdr_t; - struct p *package = (struct p *) resp.data.asBytes; - - if (resp.status != PM3_SUCCESS) { - - switch (package->isOK) { - case 1: - PrintAndLogEx(WARNING, "Can't select card"); - break; - case 2: - PrintAndLogEx(WARNING, "Card is most likely not Desfire. Its UID has wrong size"); - break; - case 3: - default: - PrintAndLogEx(WARNING, _RED_("Command unsuccessful")); - break; - } - return PM3_ESOFT; +static int get_desfire_createapp(aidhdr_t *aidhdr) { + if (aidhdr == NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_CREATE_APPLICATION, 0x00, 0x00, sizeof(aidhdr_t), (uint8_t *)aidhdr}; // 0xCA + uint16_t sw = 0; + int recvlen = 0; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't create aid -> %s"), GetErrorString(res, &sw)); + DropField(); + return res; } + return res; +} - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(package->uid, sizeof(package->uid))); - PrintAndLogEx(SUCCESS, " Batch number: " _GREEN_("%s"), sprint_hex(package->details + 7, 5)); - PrintAndLogEx(SUCCESS, " Production date: week " _GREEN_("%02x") "/ " _GREEN_("20%02x"), package->details[12], package->details[13]); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionHW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionHW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionHW[2]); - PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6])); - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionSW[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionSW[2]); - PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6])); - - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Card capabilities")); - uint8_t major = package->versionSW[3]; - uint8_t minor = package->versionSW[4]; - if (major == 0 && minor == 4) - PrintAndLogEx(INFO, "\t0.4 - DESFire MF3ICD40, No support for APDU (only native commands)"); - if (major == 0 && minor == 5) - PrintAndLogEx(INFO, "\t0.5 - DESFire MF3ICD40, Support for wrapping commands inside ISO 7816 style APDUs"); - if (major == 0 && minor == 6) - PrintAndLogEx(INFO, "\t0.6 - DESFire MF3ICD40, Add ISO/IEC 7816 command set compatibility"); - if (major == 1 && minor == 3) - PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1 MF3ICD21/41/81, Support extended APDU commands, EAL4+"); - if (major == 1 && minor == 4) - PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1 MF3ICD21/41/81, EAL4+, N/A (report to iceman!)"); - if (major == 2 && minor == 0) - PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check, EAL5"); -// if (major == 3 && minor == 0) -// PrintAndLogEx(INFO, "\t3.0 - DESFire Ev3, Originality check, proximity check, badass EAL5"); - - if (major == 0 && minor == 2) - PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); - - // Signature originality check - uint8_t signature[56] = {0}; - size_t signature_len = 0; - desfire_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); - - if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) - desfire_print_signature(package->uid, signature, signature_len, cardtype); - - // Master Key settings - uint8_t master_aid[3] = {0x00, 0x00, 0x00}; - getKeySettings(master_aid); - - // Free memory on card - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Free memory")); - uint32_t free_mem = 0; - if (get_desfire_freemem(&free_mem) == PM3_SUCCESS) { - desfire_print_freemem(free_mem); - } else { - PrintAndLogEx(SUCCESS, " Card doesn't support 'free mem' cmd"); +static int get_desfire_deleteapp(uint8_t *aid) { + if (aid == NULL) return PM3_EINVARG; + sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA + uint16_t sw = 0; + int recvlen = 0; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't delete aid -> %s"), GetErrorString(res, &sw)); + DropField(); + return res; } - PrintAndLogEx(INFO, "-------------------------------------------------------------"); - - /* - Card Master key (CMK) 0x00 AID = 00 00 00 (card level) - Application Master Key (AMK) 0x00 AID != 00 00 00 - Application keys (APK) 0x01-0x0D - Application free 0x0E - Application never 0x0F - - ACCESS RIGHTS: - keys 0,1,2,3 C - keys 4,5,6,7 RW - keys 8,9,10,11 W - keys 12,13,14,15 R - - */ - - DropField(); - return PM3_SUCCESS; + return res; } -/* - The 7 MSBits (= n) code the storage size itself based on 2^n, - the LSBit is set to '0' if the size is exactly 2^n - and set to '1' if the storage size is between 2^n and 2^(n+1). - For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. -*/ -char *getCardSizeStr(uint8_t fsize) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - uint16_t usize = 1 << ((fsize >> 1) + 1); - uint16_t lsize = 1 << (fsize >> 1); - - // is LSB set? - if (fsize & 1) - sprintf(retStr, "0x%02X ( " _YELLOW_("%d - %d bytes") ")", fsize, usize, lsize); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("%d bytes") ")", fsize, lsize); - return buf; -} - -char *getProtocolStr(uint8_t id) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (id == 0x05) - sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); - else - sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); - return buf; -} - -char *getVersionStr(uint8_t major, uint8_t minor) { - - static char buf[40] = {0x00}; - char *retStr = buf; - - if (major == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire MF3ICD40") ")", major, minor); - else if (major == 0x01 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV1") ")", major, minor); - else if (major == 0x12 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV2") ")", major, minor); -// else if (major == 0x13 && minor == 0x00) -// sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire EV3") ")", major, minor); - else if (major == 0x30 && minor == 0x00) - sprintf(retStr, "%x.%x ( " _YELLOW_("DESFire Light") ")", major, minor); - else - sprintf(retStr, "%x.%x ( " _YELLOW_("Unknown") ")", major, minor); - return buf; -} - -void getKeySettings(uint8_t *aid) { +int getKeySettings(uint8_t *aid) { + if (aid == NULL) return PM3_EINVARG; + int res = 0; if (memcmp(aid, "\x00\x00\x00", 3) == 0) { // CARD MASTER KEY //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return; - } + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - if (get_desfire_keysettings(&key_setting, &num_keys) == PM3_SUCCESS) { + res = get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { // number of Master keys (0x01) PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); @@ -661,15 +797,15 @@ void getKeySettings(uint8_t *aid) { // Authentication tests int res = test_desfire_authenticate(); - if (res == PM3_ETIMEOUT) return; + if (res == PM3_ETIMEOUT) return res; PrintAndLogEx(SUCCESS, " [0x0A] Authenticate : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); res = test_desfire_authenticate_iso(); - if (res == PM3_ETIMEOUT) return; + if (res == PM3_ETIMEOUT) return res; PrintAndLogEx(SUCCESS, " [0x1A] Authenticate ISO : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); res = test_desfire_authenticate_aes(); - if (res == PM3_ETIMEOUT) return; + if (res == PM3_ETIMEOUT) return res; PrintAndLogEx(SUCCESS, " [0xAA] Authenticate AES : %s", (res == PM3_SUCCESS) ? _YELLOW_("YES") : "NO"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); @@ -678,16 +814,14 @@ void getKeySettings(uint8_t *aid) { // AID - APPLICATION MASTER KEYS //PrintAndLogEx(SUCCESS, "--- " _CYAN_("AMK - Application Master Key settings")); - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return; - } + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - if (get_desfire_keysettings(&key_setting, &num_keys) == PM3_SUCCESS) { + res = get_desfire_keysettings(&key_setting, &num_keys); + if (res == PM3_SUCCESS) { desfire_print_keysetting(key_setting, num_keys); } else { PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); @@ -717,6 +851,471 @@ void getKeySettings(uint8_t *aid) { } DropField(); + return PM3_SUCCESS; +} + + +static int CmdHF14ADesCreateApp(const char *Cmd) { + clearCommandBuffer(); + + CLIParserInit("hf mfdes createaid", + "Create Application ID", + "Usage:\n\t-m Auth type (1=normal, 2=iso, 3=aes)\n\t-t Crypt algo (1=DES, 2=3DES, 3=3K3DES, 4=aes)\n\t-a aid (3 bytes)\n\t-n keyno\n\t-k key (8-24 bytes)\n\n" + "Example:\n\thf mfdes createaid -a 123456 -f 1122 -k 0F -l 2E -n AppName\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to create"), + arg_strx0("fF", "fid", "", "File ID"), + arg_strx0("kK", "keysetting1", "", "Key Setting 1 (Application Master Key Settings)"), + arg_strx0("lL", "keysetting2", "", "Key Setting 2"), + arg_str0("nN", "name", "", "App ISO-4 Name"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + /* KeySetting 1 (AMK Setting): + 0: Allow change master key + 1: Free Directory list access without master key + 0: AMK auth needed for GetFileSettings and GetKeySettings + 1: No AMK auth needed for GetFileIDs, GetISOFileIDs, GetFileSettings, GetKeySettings + 2: Free create/delete without master key + 0: CreateFile/DeleteFile only with AMK auth + 1: CreateFile/DeleteFile always + 3: Configuration changable + 0: Configuration frozen + 1: Configuration changable if authenticated with AMK (default) + 4-7: ChangeKey Access Rights + 0: Application master key needed (default) + 0x1..0xD: Auth with specific key needed to change any key + 0xE: Auth with the key to be changed (same KeyNo) is necessary to change a key + 0xF: All Keys within this application are frozen + + */ + /* KeySetting 2: + 0..3: Number of keys stored within the application (max. 14 keys + 4: RFU + 5: Use of 2 byte ISO FID, 0: No, 1: Yes + 6..7: Crypto Method 00: DES/3DES, 01: 3K3DES, 10: AES + Example: + 2E = FID, DES, 14 keys + 6E = FID, 3K3DES, 14 keys + AE = FID, AES, 14 keys + */ + int aidlength = 3; + int fidlength = 2; + uint8_t aid[3] = {0}; + uint8_t fid[2] = {0}; + uint8_t name[16] = {0}; + uint8_t keysetting1 = 0; + uint8_t keysetting2 = 0; + int keylen1 = 1; + int keylen2 = 1; + int namelen = 16; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIGetHexWithReturn(2, fid, &fidlength); + CLIGetHexWithReturn(3, &keysetting1, &keylen1); + CLIGetHexWithReturn(4, &keysetting2, &keylen2); + CLIGetStrWithReturn(5, name, &namelen); + CLIParserFree(); + + if (aidlength < 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length."); + return PM3_EINVARG; + } + + if (fidlength < 2) { + PrintAndLogEx(ERR, "FID must have 2 bytes length."); + return PM3_EINVARG; + } + + if (keylen1 < 1) { + PrintAndLogEx(ERR, "Keysetting1 must have 1 byte length."); + return PM3_EINVARG; + } + + if (keylen1 < 1) { + PrintAndLogEx(ERR, "Keysetting2 must have 1 byte length."); + return PM3_EINVARG; + } + + if (namelen > 16) { + PrintAndLogEx(ERR, "Name has a max. of 16 bytes length."); + return PM3_EINVARG; + } + + //90 ca 00 00 0e 3cb849 09 22 10e1 d27600 00850101 00 + /*char name[]="Test"; + uint8_t aid[]={0x12,0x34,0x56}; + uint8_t fid[]={0x11,0x22}; + uint8_t keysetting1=0xEE; + uint8_t keysetting2=0xEE;*/ + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + PrintAndLogEx(WARNING, _RED_(" Creating root aid 000000 is forbidden.")); + return PM3_ESOFT; + } + + aidhdr_t aidhdr; + memcpy(aidhdr.aid, aid, sizeof(aid)); + aidhdr.keysetting1 = keysetting1; + aidhdr.keysetting2 = keysetting2; + memcpy(aidhdr.fid, fid, sizeof(fid)); + memcpy(aidhdr.name, name, sizeof(name)); + + uint8_t rootaid[3] = {0x00, 0x00, 0x00}; + int res = get_desfire_select_application(rootaid); + if (res != PM3_SUCCESS) return res; + + return get_desfire_createapp(&aidhdr); +} + +static int CmdHF14ADesDeleteApp(const char *Cmd) { + clearCommandBuffer(); + + CLIParserInit("hf mfdes deleteaid", + "Delete Application ID", + "Usage:\n\t-a aid (3 bytes)\n\n" + "Example:\n\thf mfdes deleteaid -a 123456\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to delete"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(1, aid, &aidlength); + CLIParserFree(); + + if (aidlength < 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length."); + return PM3_EINVARG; + } + + if (memcmp(aid, "\x00\x00\x00", 3) == 0) { + PrintAndLogEx(WARNING, _RED_(" Deleting root aid 000000 is forbidden.")); + return PM3_ESOFT; + } + + uint8_t rootaid[3] = {0x00, 0x00, 0x00}; + int res = get_desfire_select_application(rootaid); + if (res != PM3_SUCCESS) return res; + return get_desfire_deleteapp(aid); +} + + +static int CmdHF14ADesFormatPICC(const char *Cmd) { + (void) Cmd; // Cmd is not used so far + CLIParserInit("hf mfdes formatpicc", + "Formats MIFARE DESFire PICC to factory state", + "Usage:\n\t-k PICC key (8 bytes)\n\n" + "Example:\n\thf mfdes formatpicc -k 0000000000000000\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), + arg_param_end + }; + CLIExecWithReturn(Cmd, argtable, true); + + uint8_t key[8] = {0}; + int keylen = 8; + CLIGetHexWithReturn(1, key, &keylen); + CLIParserFree(); + + if ((keylen < 8) || (keylen > 8)) { + PrintAndLogEx(ERR, "Specified key must have 8 bytes length."); + //SetAPDULogging(false); + return PM3_EINVARG; + } + + clearCommandBuffer(); + DropField(); + uint8_t aid[3] = {0}; + int res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + uint8_t data[25] = {keylen}; // max length: 1 + 24 (3k3DES) + memcpy(data + 1, key, keylen); + SendCommandOLD(CMD_HF_DESFIRE_AUTH1, 2, 1, 0, data, keylen + 1); + PacketResponseNG resp; + + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + + uint8_t isOK = resp.oldarg[0] & 0xff; + if (isOK) { + uint8_t rdata[] = {0xFC}; // 0xFC + SendCommandMIX(CMD_HF_DESFIRE_COMMAND, NONE, sizeof(rdata), 0, rdata, sizeof(rdata)); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { + PrintAndLogEx(WARNING, "Client reset command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + if (resp.oldarg[0] & 0xFF) { + PrintAndLogEx(INFO, "Card successfully reset"); + return PM3_SUCCESS; + } + } else { + PrintAndLogEx(WARNING, _RED_("Auth command failed.")); + } + + return PM3_SUCCESS; +} + + +static int CmdHF14ADesInfo(const char *Cmd) { + (void)Cmd; // Cmd is not used so far + + SendCommandNG(CMD_HF_DESFIRE_INFO, NULL, 0); + PacketResponseNG resp; + + if (!WaitForResponseTimeout(CMD_HF_DESFIRE_INFO, &resp, 1500)) { + PrintAndLogEx(WARNING, "Command execute timeout"); + DropField(); + return PM3_ETIMEOUT; + } + + struct p { + uint8_t isOK; + uint8_t uid[7]; + uint8_t versionHW[7]; + uint8_t versionSW[7]; + uint8_t details[14]; + } PACKED; + + struct p *package = (struct p *) resp.data.asBytes; + + if (resp.status != PM3_SUCCESS) { + switch (package->isOK) { + case 1: + PrintAndLogEx(WARNING, "Can't select card"); + break; + case 2: + PrintAndLogEx(WARNING, "Card is most likely not DESFire. Wrong size UID"); + break; + case 3: + default: + PrintAndLogEx(WARNING, _RED_("Command unsuccessful")); + break; + } + return PM3_ESOFT; + } + + nxp_cardtype_t cardtype = getCardType(package->versionHW[3], package->versionHW[4]); + if (cardtype == PLUS_EV1) { + PrintAndLogEx(INFO, "Card seems to be MIFARE Plus EV1. Try " _YELLOW_("`hf mfp info`")); + return PM3_SUCCESS; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") "---------------------------"); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(package->uid, sizeof(package->uid))); + PrintAndLogEx(SUCCESS, " Batch number: " _GREEN_("%s"), sprint_hex(package->details + 7, 5)); + PrintAndLogEx(SUCCESS, " Production date: week " _GREEN_("%02x") "/ " _GREEN_("20%02x"), package->details[12], package->details[13]); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionHW[0])); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionHW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionHW[2]); + PrintAndLogEx(INFO, " Version: %s", getVersionStr(package->versionHW[3], package->versionHW[4])); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionHW[5])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionHW[6], true)); + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(package->versionSW[0])); + PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), package->versionSW[1]); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), package->versionSW[2]); + PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), package->versionSW[3], package->versionSW[4]); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(package->versionSW[5])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(package->versionSW[6], false)); + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Card capabilities")); + uint8_t major = package->versionSW[3]; + uint8_t minor = package->versionSW[4]; + if (major == 0 && minor == 4) + PrintAndLogEx(INFO, "\t0.4 - DESFire MF3ICD40, No support for APDU (only native commands)"); + if (major == 0 && minor == 5) + PrintAndLogEx(INFO, "\t0.5 - DESFire MF3ICD40, Support for wrapping commands inside ISO 7816 style APDUs"); + if (major == 0 && minor == 6) + PrintAndLogEx(INFO, "\t0.6 - DESFire MF3ICD40, Add ISO/IEC 7816 command set compatibility"); + if (major == 1 && minor == 3) + PrintAndLogEx(INFO, "\t1.3 - DESFire Ev1 MF3ICD21/41/81, Support extended APDU commands, EAL4+"); + if (major == 1 && minor == 4) + PrintAndLogEx(INFO, "\t1.4 - DESFire Ev1 MF3ICD21/41/81, EAL4+, N/A (report to iceman!)"); + if (major == 2 && minor == 0) + PrintAndLogEx(INFO, "\t2.0 - DESFire Ev2, Originality check, proximity check, EAL5"); +// if (major == 3 && minor == 0) +// PrintAndLogEx(INFO, "\t3.0 - DESFire Ev3, Originality check, proximity check, badass EAL5"); + + if (major == 0 && minor == 2) + PrintAndLogEx(INFO, "\t0.2 - DESFire Light, Originality check, "); + + if (cardtype == DESFIRE_EV2 || cardtype == DESFIRE_LIGHT || cardtype == DESFIRE_EV3) { + // Signature originality check + uint8_t signature[56] = {0}; + size_t signature_len = 0; + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + if (get_desfire_signature(signature, &signature_len) == PM3_SUCCESS) { + desfire_print_signature(package->uid, signature, signature_len, cardtype); + } else { + PrintAndLogEx(WARNING, "--- Card doesn't support GetSignature cmd"); + } + } + + // Master Key settings + uint8_t master_aid[3] = {0x00, 0x00, 0x00}; + getKeySettings(master_aid); + + if (cardtype != DESFIRE_LIGHT) { + // Free memory on card + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Free memory")); + uint32_t free_mem = 0; + if (get_desfire_freemem(&free_mem) == PM3_SUCCESS) { + desfire_print_freemem(free_mem); + } else { + PrintAndLogEx(SUCCESS, " Card doesn't support 'free mem' cmd"); + } + PrintAndLogEx(INFO, "-------------------------------------------------------------"); + } + /* + Card Master key (CMK) 0x00 AID = 00 00 00 (card level) + Application Master Key (AMK) 0x00 AID != 00 00 00 + Application keys (APK) 0x01-0x0D + Application free 0x0E + Application never 0x0F + + ACCESS RIGHTS: + keys 0,1,2,3 C + keys 4,5,6,7 RW + keys 8,9,10,11 W + keys 12,13,14,15 R + + */ + + DropField(); + return PM3_SUCCESS; +} + + +static void DecodeFileType(uint8_t filetype) { + switch (filetype) { + case 0x00: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Standard Data File", filetype); + break; + case 0x01: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Backup Data File", filetype); + break; + case 0x02: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Value Files with Backup", filetype); + break; + case 0x03: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Linear Record Files with Backup", filetype); + break; + case 0x04: + PrintAndLogEx(INFO, " File Type: 0x%02X -> Cyclic Record Files with Backup", filetype); + break; + default: + PrintAndLogEx(INFO, " File Type: 0x%02X", filetype); + break; + } +} + +static void DecodeComSet(uint8_t comset) { + switch (comset) { + case 0x00: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain", comset); + break; + case 0x01: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Plain + MAC", comset); + break; + case 0x03: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X -> Enciphered", comset); + break; + default: + PrintAndLogEx(INFO, " Com.Setting: 0x%02X", comset); + break; + } +} + +static char *DecodeAccessValue(uint8_t value) { + char *car = (char *)calloc(255, sizeof(char)); + if (car == NULL) + return NULL; + + switch (value) { + case 0xE: + strcat(car, "(Free Access)"); + break; + case 0xF: + strcat(car, "(Denied Access)"); + break; + default: + sprintf(car, "(Access Key: %d)", value); + break; + } + return car; +} + +static void DecodeAccessRights(uint16_t accrights) { + int change_access_rights = accrights & 0xF; + int read_write_access = (accrights >> 4) & 0xF; + int write_access = (accrights >> 8) & 0xF; + int read_access = (accrights >> 12) & 0xF; + char *car = DecodeAccessValue(change_access_rights); + if (car == NULL) return; + + char *rwa = DecodeAccessValue(read_write_access); + if (rwa == NULL) return; + + char *wa = DecodeAccessValue(write_access); + if (wa == NULL) return; + + char *ra = DecodeAccessValue(read_access); + if (ra == NULL) return; + + PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights, car, rwa, wa, ra); + free(car); + free(rwa); + free(wa); + free(ra); +} + +static int DecodeFileSettings(uint8_t *src, int src_len, int maclen) { + uint8_t filetype = src[0]; + uint8_t comset = src[1]; + + uint16_t accrights = (src[4] << 8) + src[3]; + if (src_len == 1 + 1 + 2 + 3 + maclen) { + int filesize = (src[7] << 16) + (src[6] << 8) + src[5]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Filesize: %d", filesize); + return PM3_SUCCESS; + } else if (src_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) { + int lowerlimit = (src[8] << 24) + (src[7] << 16) + (src[6] << 8) + src[5]; + int upperlimit = (src[12] << 24) + (src[11] << 16) + (src[10] << 8) + src[9]; + int limitcredvalue = (src[16] << 24) + (src[15] << 16) + (src[14] << 8) + src[13]; + uint8_t limited_credit_enabled = src[17]; + DecodeFileType(filetype); + DecodeComSet(comset); + DecodeAccessRights(accrights); + PrintAndLogEx(INFO, " Lower limit: %d - Upper limit: %d - limited credit value: %d - limited credit enabled: %d", lowerlimit, upperlimit, limitcredvalue, limited_credit_enabled); + return PM3_SUCCESS; + } + return PM3_ESOFT; } static int CmdHF14ADesEnumApplications(const char *Cmd) { @@ -733,6 +1332,8 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { dfname_t dfnames[255]; uint8_t dfname_count = 0; + int res = 0; + if (get_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); DropField(); @@ -772,14 +1373,11 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { } } - getKeySettings(aid); + res = getKeySettings(aid); + if (res != PM3_SUCCESS) return res; + res = get_desfire_select_application(aid); - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return PM3_ESOFT; - } // Get File IDs if (get_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { @@ -790,15 +1388,15 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t filesettings[20] = {0}; int fileset_len = 0; int res = get_desfire_filesettings(j, filesettings, &fileset_len); + int maclen = 0; // To be implemented if (res == PM3_SUCCESS) { - PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); + if (DecodeFileSettings(filesettings, fileset_len, maclen) != PM3_SUCCESS) { + PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len)); + } } } } - - - /* // Get ISO File IDs { @@ -831,6 +1429,8 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { // #define BUFSIZE 256 static int CmdHF14ADesAuth(const char *Cmd) { + int res = 0; + DropField(); clearCommandBuffer(); // NR DESC KEYLENGHT // ------------------------ @@ -939,21 +1539,16 @@ static int CmdHF14ADesAuth(const char *Cmd) { return PM3_EINVARG; } - if (get_desfire_select_application(aid) != PM3_SUCCESS) { - PrintAndLogEx(WARNING, _RED_(" Can't select AID")); - DropField(); - return PM3_ESOFT; - } - uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; - int res = get_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) { - PrintAndLogEx(WARNING, "Get file ids error."); - DropField(); - return res; - } + res = get_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + if (memcmp(aid, "\x00\x00\x00", 3) != 0) { + uint8_t file_ids[33] = {0}; + uint8_t file_ids_len = 0; + res = get_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) return res; + } // algo, keylength, uint8_t data[25] = {keylength}; // max length: 1 + 24 (3k3DES) @@ -993,6 +1588,9 @@ static command_t CommandTable[] = { {"list", CmdHF14ADesList, AlwaysAvailable, "List DESFire (ISO 14443A) history"}, {"enum", CmdHF14ADesEnumApplications, IfPm3Iso14443a, "Tries enumerate all applications"}, {"auth", CmdHF14ADesAuth, IfPm3Iso14443a, "Tries a MIFARE DesFire Authentication"}, + {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, + {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, + {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, // {"rdbl", CmdHF14ADesRb, IfPm3Iso14443a, "Read MIFARE DesFire block"}, // {"wrbl", CmdHF14ADesWb, IfPm3Iso14443a, "write MIFARE DesFire block"}, {NULL, NULL, NULL, NULL} diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h index 4f6605cff..eb4dd77e0 100644 --- a/client/cmdhfmfdes.h +++ b/client/cmdhfmfdes.h @@ -14,10 +14,11 @@ int CmdHFMFDes(const char *Cmd); +/* char *getCardSizeStr(uint8_t fsize); -char *getProtocolStr(uint8_t id); char *getVersionStr(uint8_t major, uint8_t minor); -void getKeySettings(uint8_t *aid); +int getKeySettings(uint8_t *aid); +*/ // Ev1 card limits #define MAX_NUM_KEYS 0x0F @@ -26,57 +27,16 @@ void getKeySettings(uint8_t *aid); #define MAX_FRAME_SIZE 60 #define FRAME_PAYLOAD_SIZE (MAX_FRAME_SIZE - 5) +// Ev2 card limits + +// Ev3 card limits + +// Light card limits + +// Light Ev1 card limits + #define NOT_YET_AUTHENTICATED 0xFF -// status- and error codes | -#define OPERATION_OK 0x00 // Successful operation -#define NO_CHANGES 0x0C // No changes done to backup files -// ,CommitTransaction/ -// AbortTransaction not necessary -#define OUT_OF_EEPROM_ERROR 0x0E // Insufficient NV-Memory to -// complete command -#define ILLEGAL_COMMAND_CODE 0x1C // Command code not supported -#define INTEGRITY_ERROR 0x1E // CRC or MAC does not match data -// Padding bytes not valid -#define NO_SUCH_KEY 0x40 // Invalid key number specified -#define LENGTH_ERROR 0x7E // Length of command string invalid -#define PERMISSION_DENIED 0x9D // Current configuration status -// does not allow the requested -// command -#define PARAMETER_ERROR 0x9E // Value of the parameter(s) inval. -#define APPLICATION_NOT_FOUND 0xA0 // Requested AID not present on PIC -#define APPL_INTEGRITY_ERROR 0xA1 // [1] // Unrecoverable error within app- -// lication, app will be disabled -#define AUTHENTICATION_ERROR 0xAE // Current authentication status -// does not allow the requested -// command -#define ADDITIONAL_FRAME 0xAF // Additional data frame is -// expected to be sent -#define BOUNDARY_ERROR 0xBE // Attempt to read/write data from/ -// to beyond the file's/record's -// limits. Attempt to exceed the -// limits of a value file. -#define PICC_INTEGRITY_ERROR 0xC1 // [1] // Unrecoverable error within PICC -// ,PICC will be disabled -#define COMMAND_ABORTED 0xCA // Previous Command was not fully -// completed Not all Frames were -// requested or provided by PCD -#define PICC_DISABLED_ERROR 0xCD // [1] // PICC was disabled by an unrecoverable error -#define COUNT_ERROR 0xCE // Number of Applications limited -// to 28, no additional -// CreateApplication possible -#define DUPLICATE_ERROR 0xDE // Creation of file/application -// failed because file/application -// with same number already exists -#define EEPROM_ERROR 0xEE // [1] // Could not complete NV-write -// operation due to loss of power, -// internal backup/rollback -// mechanism activated -#define FILE_NOT_FOUND_ERROR 0xF0 // Specified file number does not -// exist -#define FILE_INTEGRITY_ERROR 0xF1 // [1] // Unrecoverable error within file, -// file will be disabled -// -// [1] These errors are not expected to appear during normal operation + #endif diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c index 71da93bcc..e85f0861a 100644 --- a/client/cmdhfmfp.c +++ b/client/cmdhfmfp.c @@ -27,11 +27,19 @@ #include "protocols.h" #include "crypto/libpcrypto.h" - static const uint8_t DefaultKey[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; - uint16_t CardAddresses[] = {0x9000, 0x9001, 0x9002, 0x9003, 0x9004, 0xA000, 0xA001, 0xA080, 0xA081, 0xC000, 0xC001}; +typedef enum { + MFP_UNKNOWN = 0, + DESFIRE_MF3ICD40, + DESFIRE_EV1, + DESFIRE_EV2, + DESFIRE_EV3, + DESFIRE_LIGHT, + PLUS_EV1, +} nxp_cardtype_t; + static int CmdHelp(const char *Cmd); /* @@ -56,15 +64,21 @@ static char *getCardSizeStr(uint8_t fsize) { return buf; } -static char *getProtocolStr(uint8_t id) { +static char *getProtocolStr(uint8_t id, bool hw) { - static char buf[40] = {0x00}; + static char buf[50] = {0x00}; char *retStr = buf; - if (id == 0x05) - sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); - else + if (id == 0x04) { + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3 MIFARE, 14443-4") ")", id); + } else if (id == 0x05) { + if (hw) + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-2, 14443-3") ")", id); + else + sprintf(retStr, "0x%02X ( " _YELLOW_("ISO 14443-3, 14443-4") ")", id); + } else { sprintf(retStr, "0x%02X ( " _YELLOW_("Unknown") ")", id); + } return buf; } @@ -91,6 +105,59 @@ static char *getVersionStr(uint8_t major, uint8_t minor) { return buf; } +static char *getTypeStr(uint8_t type) { + + static char buf[40] = {0x00}; + char *retStr = buf; + + switch (type) { + case 1: + sprintf(retStr, "0x%02X ( " _YELLOW_("DESFire") ")", type); + break; + case 2: + sprintf(retStr, "0x%02X ( " _YELLOW_("Plus") ")", type); + break; + case 3: + sprintf(retStr, "0x%02X ( " _YELLOW_("Ultralight") ")", type); + break; + case 4: + sprintf(retStr, "0x%02X ( " _YELLOW_("NTAG") ")", type); + break; + default: + break; + } + return buf; +} + +static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { + + // DESFire MF3ICD40 + if (major == 0x00 && minor == 0x00 ) + return DESFIRE_MF3ICD40; + + // DESFire EV1 + if (major == 0x01 && minor == 0x00 ) + return DESFIRE_EV1; + + // DESFire EV2 + if (major == 0x12 && minor == 0x00 ) + return DESFIRE_EV2; + + // DESFire EV3 +// if (major == 0x13 && minor == 0x00 ) +// return DESFIRE_EV3; + + // DESFire Light + if (major == 0x30 && minor == 0x00 ) + return DESFIRE_LIGHT; + + // Plus EV1 + if (major == 0x11 && minor == 0x00 ) + return PLUS_EV1; + + return MFP_UNKNOWN; +} + // --- GET SIGNATURE static int plus_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature, int signature_len) { @@ -115,13 +182,15 @@ static int plus_print_signature(uint8_t *uid, uint8_t uidlen, uint8_t *signature if (is_valid) break; } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); + if (is_valid == false) { PrintAndLogEx(SUCCESS, "Signature verification " _RED_("failed")); return PM3_ESOFT; } - PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(INFO, "--- " _CYAN_("Tag Signature")); PrintAndLogEx(INFO, " IC signature public key name: " _GREEN_("%s"), nxp_plus_public_keys[i].desc); PrintAndLogEx(INFO, "IC signature public key value: %.32s", nxp_plus_public_keys[i].value); PrintAndLogEx(INFO, " : %.32s", nxp_plus_public_keys[i].value + 16); @@ -162,19 +231,19 @@ static int plus_print_version(uint8_t *version) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Hardware Information")); PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); + PrintAndLogEx(INFO, " Type: %s", getTypeStr(version[1])); PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); PrintAndLogEx(INFO, " Version: %s", getVersionStr(version[3], version[4])); PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6], true)); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Software Information")); - PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[0])); - PrintAndLogEx(INFO, " Type: " _YELLOW_("0x%02X"), version[1]); - PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[2]); - PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), version[3], version[4]); - PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[5])); - PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[6])); + PrintAndLogEx(INFO, " Vendor Id: " _YELLOW_("%s"), getTagInfo(version[7])); + PrintAndLogEx(INFO, " Type: %s", getTypeStr(version[8])); + PrintAndLogEx(INFO, " Subtype: " _YELLOW_("0x%02X"), version[9]); + PrintAndLogEx(INFO, " Version: " _YELLOW_("%d.%d"), version[10], version[11]); + PrintAndLogEx(INFO, " Storage size: %s", getCardSizeStr(version[12])); + PrintAndLogEx(INFO, " Protocol: %s", getProtocolStr(version[13], false)); return PM3_SUCCESS; } static int get_plus_version(uint8_t *version, int *version_len) { @@ -235,17 +304,28 @@ static int CmdHFMFPInfo(const char *Cmd) { if (select_status == 1 || select_status == 2) { PrintAndLogEx(INFO, "--- " _CYAN_("Fingerprint")); - - if (supportVersion && supportSignature) { - PrintAndLogEx(INFO, " Tech: " _GREEN_("MIFARE Plus EV1")); - } else { - PrintAndLogEx(INFO, " Tech: " _YELLOW_("MIFARE Plus SE/X")); + + bool isPlus = false; + + if (supportVersion) { + + int cardtype = getCardType(version[3], version[4]); + + if (cardtype == 6) { + if (supportSignature) { + PrintAndLogEx(INFO, " Tech: " _GREEN_("MIFARE Plus EV1")); + } else { + PrintAndLogEx(INFO, " Tech: " _YELLOW_("MIFARE Plus SE/X")); + } + isPlus = true; + } else { + + } } // MIFARE Type Identification Procedure // https://www.nxp.com/docs/en/application-note/AN10833.pdf uint16_t ATQA = card.atqa[0] + (card.atqa[1] << 8); - bool isPlus = false; if (ATQA & 0x0004) { PrintAndLogEx(INFO, " SIZE: " _GREEN_("2K") "(%s UID)", (ATQA & 0x0040) ? "7" : "4"); @@ -289,6 +369,10 @@ static int CmdHFMFPInfo(const char *Cmd) { uint8_t cmd[3 + 16] = {0xa8, 0x90, 0x90, 0x00}; int res = ExchangeRAW14a(cmd, sizeof(cmd), true, false, data, sizeof(data), &datalen, false); + // DESFire answers 0x1C + // Plus answers 0x0B, 0x09 + PrintAndLogEx(INFO, "ICEE: %s", sprint_hex(data, datalen)); + if (memcmp(data, "\x67\x00", 2) == 0) { PrintAndLogEx(INFO, "\tMost likely a MIFARE DESFire tag"); PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`hf mfdes info`")); @@ -1105,10 +1189,13 @@ static int CmdHFMFPChk(const char *Cmd) { if (keyListLen == 0) { PrintAndLogEx(ERR, "Key list is empty. Nothing to check."); return PM3_EINVARG; + } else { + PrintAndLogEx(INFO, "Loaded " _YELLOW_("%zu") "keys", keyListLen); } if (!verbose) printf("Search keys:"); + while (true) { res = MFPKeyCheck(startSector, endSector, startKeyAB, endKeyAB, keyList, keyListLen, foundKeys, verbose); if (res == PM3_EOPABORTED) diff --git a/client/proxguiqt.cpp b/client/proxguiqt.cpp index dc67953e6..dd5fd3f24 100644 --- a/client/proxguiqt.cpp +++ b/client/proxguiqt.cpp @@ -26,6 +26,7 @@ #include #include "proxgui.h" #include +#include "ui.h" extern "C" { #include "util_darwin.h" @@ -168,7 +169,11 @@ void ProxWidget::vchange_dthr_down(int v) { } ProxWidget::ProxWidget(QWidget *parent, ProxGuiQT *master) : QWidget(parent) { this->master = master; - resize(800, 400); + // Set the initail postion and size from settings + if (session.settings_loaded) + setGeometry (session.window_plot_xpos,session.window_plot_ypos,session.window_plot_wsize,session.window_plot_hsize); + else + resize(800, 400); // Setup the controller widget controlWidget = new QWidget(); diff --git a/client/proxmark3.c b/client/proxmark3.c index 0438f81ad..4d36c490b 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -29,6 +29,10 @@ #include "flash.h" #include "settings.h" +// Used to enable/disable use of settings json file +// #define USE_SETTING_FILE + + static void showBanner(void) { g_printAndLog = PRINTANDLOG_PRINT; @@ -489,12 +493,15 @@ finish2: return ret; } +#ifndef USE_SETTING_FILE + // Check if windows AnsiColor Support is enabled in the registery // [HKEY_CURRENT_USER\Console] // "VirtualTerminalLevel"=dword:00000001 // 2nd Key needs to be enabled... This key takes the console out of legacy mode. // [HKEY_CURRENT_USER\Console] // "ForceV2"=dword:00000001 + static bool DetectWindowsAnsiSupport(void) { bool ret = false; #if defined(_WIN32) @@ -543,6 +550,8 @@ static bool DetectWindowsAnsiSupport(void) { return ret; } +#endif + int main(int argc, char *argv[]) { srand(time(0)); @@ -582,12 +591,17 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); - // Settings Load and Test - // settings_load (); +#ifdef USE_SETTING_FILE + // Load Settings and assign + // This will allow the command line to override the settings.json values + settings_load (); + + // quick patch for debug level + g_debugMode = session.client_debug_level; // settings_save (); - // printf ("Ver : %s\n",mySettings.version); // End Settings - +#endif + for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { @@ -766,8 +780,11 @@ int main(int argc, char *argv[]) { return 1; } +#ifndef USE_SETTING_FILE + // comment next 2 lines to use session values set from settings_load session.supports_colors = DetectWindowsAnsiSupport(); session.emoji_mode = ALTTEXT; +#endif session.stdinOnTTY = isatty(STDIN_FILENO); session.stdoutOnTTY = isatty(STDOUT_FILENO); @@ -837,6 +854,14 @@ int main(int argc, char *argv[]) { if (!script_cmds_file && !script_cmd && session.stdinOnTTY && session.stdoutOnTTY && !flash_mode) showBanner(); +#ifdef USE_SETTING_FILE + // Save settings if not load from settings json file. + // Doing this here will ensure other checks and updates are saved to over rule default + // e.g. Linux color use check + if (!session.settings_loaded) + settings_save (); +#endif + #ifdef HAVE_GUI # ifdef _WIN32 diff --git a/client/settings.c b/client/settings.c index 79fa00fd1..c3cb02ad6 100644 --- a/client/settings.c +++ b/client/settings.c @@ -39,55 +39,55 @@ // Settings Functions //----------------------------------------------------------------------------- +//----------------------------------------------------------------------------- +// Notes +// To add a new setting +// Add the new setting to the session_arg_t; in ui.h +// Add the default value for the setting in the settings_load page below +// Update the settings_load_callback to load your setting into the stucture +// Update the settings_save_callback to enusre your setting gets saved when needed. +// use the setting as needed : session. +// Can use (session.settings_loaded) to check if json settings file was used +//----------------------------------------------------------------------------- + #include "settings.h" #include "comms.h" #include "emv/emvjson.h" +#include // Load all settings into memory (struct) int settings_load (void) { + + // Set all defaults + session.client_debug_level = OFF; + session.window_plot_xpos = 10; + session.window_plot_ypos = 30; + session.window_plot_hsize = 400; + session.window_plot_wsize = 800; + session.emoji_mode = ALIAS; + session.show_hints = false; + session.supports_colors = false; + // loadFileJson wants these, so pass in place holder values, though not used // in settings load; uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - // clear all settings - memset (&mySettings,0x00,sizeof(mySettings)); - if (loadFileJSON(settingsFilename, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) { - printf ("==> Settings Loaded\n"); - mySettings.loaded = true; + session.settings_loaded = true; } - - - // Test results - /* - bool os_windows_usecolor; - bool os_windows_useansicolor; - int window_xpos; - int window_ypos; - int window_hsize; - int window_wsize; - bool use_emojis - bool use_hints - */ - printf (" Settings Version : [%s]\n", mySettings.version); - printf (" os_windows_usecolor (bool) : [%d]\n", mySettings.os_windows_usecolor); - printf (" os_windows_useAnsicolor (bool) : [%d]\n", mySettings.os_windows_useansicolor); - printf (" window_xpos (int) : [%d]\n", mySettings.window_xpos); - printf (" window_ypos (int) : [%d]\n", mySettings.window_ypos); - printf (" window_hsize (int) : [%d]\n", mySettings.window_hsize); - printf (" window_wsize (int) : [%d]\n", mySettings.window_wsize); - printf (" use emoji (bool) : [%d]\n", mySettings.use_emojis); - printf (" use hints (bool) : [%d]\n", mySettings.use_hints); - return PM3_SUCCESS; + // Note, if session.settings_loaded == false then the settings_save + // will be called in main () to save settings as set in defaults and main() checks. + + return PM3_SUCCESS; } // Save all settings from memory (struct) to file -int settings_save(void) { +int settings_save (void) { // Note sure if backup has value ? char backupFilename[500]; - snprintf(backupFilename, sizeof(backupFilename),"%s.bak",settingsFilename); + snprintf (backupFilename,sizeof(backupFilename),"%s.bak",settingsFilename); if (fileExists (backupFilename)) { if (remove (backupFilename) != 0) { @@ -95,7 +95,7 @@ int settings_save(void) { return PM3_ESOFT; } } - + if (fileExists (settingsFilename)) { if (rename (settingsFilename,backupFilename) != 0) { PrintAndLogEx (FAILED, "Error - could not backup settings file \"%s\" to \"%s\"",settingsFilename,backupFilename); @@ -105,90 +105,87 @@ int settings_save(void) { uint8_t dummyData = 0x00; size_t dummyDL = 0x00; - + if (saveFileJSON(settingsFilename, jsfSettings, &dummyData, dummyDL) == PM3_SUCCESS) PrintAndLogEx (NORMAL, "settings have been saved to \"%s\"",settingsFilename); - + return PM3_SUCCESS; } -void settings_save_callback(json_t *root) { - - printf ("==> Save Settings\n"); - //JsonSaveStr(root, "FileType", "settings"); - //JsonSaveStr (root,"Test1.Test2","test settings"); - /* - "version": "1.0 Nov 2019", - "os.windows.usecolor": true, - "os.windows.useAnsiColor": true, - "window.xpos": 10, - "window.ypos": 10, - "window.hsize": 300, - "window.wsize": 600 - */ - JsonSaveStr (root,"FileType","settings"); - JsonSaveStr (root,"version","1.0 Nov 2019");//mySettings.version); - JsonSaveBoolean (root,"os.windows.useColor", mySettings.os_windows_usecolor); - JsonSaveBoolean (root,"os.windows.useAnsiColor", mySettings.os_windows_useansicolor); - JsonSaveInt (root,"window.xpos", mySettings.window_xpos); - JsonSaveInt (root,"window.ypos", mySettings.window_ypos); - JsonSaveInt (root,"window.hsize", mySettings.window_hsize); - JsonSaveInt (root,"window.wsize", mySettings.window_wsize); - JsonSaveBoolean (root,"client.useEmojis", mySettings.use_emojis); - JsonSaveBoolean (root,"client.useHints", mySettings.use_hints); +void settings_save_callback (json_t *root) { + + JsonSaveStr (root,"FileType","settings"); + + // Log level, convert to text + switch (session.client_debug_level) { + case OFF: JsonSaveStr (root,"client.debug.level","off"); break; + case SIMPLE: JsonSaveStr (root,"client.debug.level","simple"); break; + case FULL: JsonSaveStr (root,"client.debug.level","full"); break; + default: + JsonSaveStr (root,"logging.level","NORMAL"); + } + + // Plot window + JsonSaveInt (root,"window.plot.xpos",session.window_plot_xpos); + JsonSaveInt (root,"window.plot.ypos",session.window_plot_ypos); + JsonSaveInt (root,"window.plot.hsize",session.window_plot_hsize); + JsonSaveInt (root,"window.plot.wsize",session.window_plot_wsize); + + // Emoji + switch (session.emoji_mode) { + case ALIAS: JsonSaveStr (root,"show.emoji","alias"); break; + case EMOJI: JsonSaveStr (root,"show.emoji","emoji"); break; + case ALTTEXT: JsonSaveStr (root,"show.emoji","alttext"); break; + case ERASE: JsonSaveStr (root,"show.emoji","erase"); break; + default: + JsonSaveStr (root,"show.emoji","ALIAS"); + } + + JsonSaveBoolean (root,"show.hints",session.show_hints); + + JsonSaveBoolean (root,"os.supports.colors",session.supports_colors); } -void settings_load_callback(json_t *root) { - +void settings_load_callback (json_t *root) { json_error_t up_error = {0}; - int b1; + bool b1; int i1; const char *s1; + char tempStr [500]; // to use str_lower() since json unpack uses const char * - if (json_unpack_ex(root, &up_error , 0, "{s:s}","version", &s1) == 0) - strncpy (mySettings.version,s1,sizeof (mySettings.version) - 1); - else - strncpy (mySettings.version,"unknown",sizeof (mySettings.version) - 1); + // Logging Level + if (json_unpack_ex(root,&up_error, 0, "{s:s}","client.debug.level",&s1) == 0) { + strncpy (tempStr,s1,sizeof(tempStr)-1); + str_lower (tempStr); + if (strncmp (tempStr,"off",3) == 0) session.client_debug_level = OFF; + if (strncmp (tempStr,"simple",6) == 0) session.client_debug_level = SIMPLE; + if (strncmp (tempStr,"full",4) == 0) session.client_debug_level = FULL; + } - // os.windows... - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useColor",&b1) == 0) - mySettings.os_windows_usecolor = b1; - else // default - mySettings.os_windows_useansicolor = false; + // window plot + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.xpos",&i1) == 0) + session.window_plot_xpos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.ypos",&i1) == 0) + session.window_plot_ypos = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.hsize",&i1) == 0) + session.window_plot_hsize = i1; + if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.plot.wsize",&i1) == 0) + session.window_plot_wsize = i1; - if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.windows.useAnsiColor",&b1) == 0) - mySettings.os_windows_useansicolor = b1; - else // default - mySettings.os_windows_useansicolor = false; + // show options + if (json_unpack_ex(root,&up_error, 0, "{s:s}","show.emoji",&s1) == 0) { + strncpy (tempStr,s1,sizeof(tempStr)-1); + str_lower (tempStr); + if (strncmp (tempStr,"alias",5) == 0) session.emoji_mode = ALIAS; + if (strncmp (tempStr,"emoji",5) == 0) session.emoji_mode = EMOJI; + if (strncmp (tempStr,"alttext",7) == 0) session.emoji_mode = ALTTEXT; + if (strncmp (tempStr,"erase",5) == 0) session.emoji_mode = ERASE; + } - // window... - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.xpos",&i1) == 0) - mySettings.window_xpos = i1; - else // default - mySettings.window_xpos = 0; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.ypos",&i1) == 0) - mySettings.window_ypos = i1; - else // default - mySettings.window_ypos = 0; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.hsize",&i1) == 0) - mySettings.window_hsize = i1; - else // default - mySettings.window_hsize = 0; - if (json_unpack_ex(root,&up_error, 0, "{s:i}","window.wsize",&i1) == 0) - mySettings.window_wsize = i1; - else // default - mySettings.window_wsize = 0; - - // Use EMOJIS - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useEmojis",&b1) == 0) - mySettings.use_emojis = b1; - else // default - mySettings.use_emojis = false; - - // Use Hints - if (json_unpack_ex(root,&up_error, 0, "{s:b}","client.useHints",&b1) == 0) - mySettings.use_hints = b1; - else // default - mySettings.use_hints = false; + if (json_unpack_ex(root,&up_error, 0, "{s:b}","show.hints",&b1) == 0) + session.show_hints = b1; + + if (json_unpack_ex(root,&up_error, 0, "{s:b}","os.supports.colors",&b1) == 0) + session.supports_colors = b1; } diff --git a/client/settings.h b/client/settings.h index 4bf8b2a5e..c404a82e2 100644 --- a/client/settings.h +++ b/client/settings.h @@ -8,29 +8,13 @@ //----------------------------------------------------------------------------- // Settings Functions //----------------------------------------------------------------------------- -#ifndef settings_h -#define settings_h +#ifndef SETTINGS_H_ +#define SETTINGS_H_ #include "fileutils.h" #define settingsFilename "settings.json" -typedef struct { - bool loaded; - char version[20]; - bool os_windows_usecolor; - bool os_windows_useansicolor; - int window_xpos; - int window_ypos; - int window_hsize; - int window_wsize; - bool use_emojis; - bool use_hints; -} settings_t; - -// Settings struct so as to be available to other modules by including settings.h -settings_t mySettings; - int settings_load (void); int settings_save (void); diff --git a/client/ui.h b/client/ui.h index 5bb814b81..343b55c1f 100644 --- a/client/ui.h +++ b/client/ui.h @@ -19,8 +19,10 @@ typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t; typedef enum emojiMode {ALIAS, EMOJI, ALTTEXT, ERASE} emojiMode_t; +typedef enum clientdebugLevel {OFF,SIMPLE,FULL} clientdebugLevel_t; typedef struct { + bool settings_loaded; bool stdinOnTTY; bool stdoutOnTTY; bool supports_colors; @@ -28,6 +30,11 @@ typedef struct { bool pm3_present; bool help_dump_mode; bool show_hints; + int window_plot_xpos; + int window_plot_ypos; + int window_plot_hsize; + int window_plot_wsize; + clientdebugLevel_t client_debug_level; } session_arg_t; extern session_arg_t session; diff --git a/client/util.c b/client/util.c index 36362f83b..654a87cc3 100644 --- a/client/util.c +++ b/client/util.c @@ -212,7 +212,6 @@ void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex sprintf(tmp, " "); // remove last space - --tmp; *tmp = '\0'; return; } diff --git a/include/protocols.h b/include/protocols.h index 03953fcc6..b927058b0 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -349,26 +349,20 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // 6x xx = ERROR // MIFARE DESFire command set: - - -#define MFDES_GET_VERSION 0x60 - #define MFDES_AUTHENTICATE 0x0A // AUTHENTICATE_NATIVE #define MFDES_AUTHENTICATE_ISO 0x1A // AUTHENTICATE_STANDARD #define MFDES_AUTHENTICATE_AES 0xAA #define MFDES_CREDIT 0x0C #define MFDES_LIMITED_CREDIT 0x1C -#define MFDES_DEBIT 0xDC - #define MFDES_WRITE_RECORD 0x3B #define MFDES_READSIG 0x3C #define MFDES_WRITE_DATA 0x3D - #define MFDES_GET_KEY_SETTINGS 0x45 #define MFDES_CHANGE_KEY_SETTINGS 0x54 #define MFDES_SELECT_APPLICATION 0x5A #define MFDES_CHANGE_FILE_SETTINGS 0x5F +#define MFDES_GET_VERSION 0x60 #define MFDES_GET_ISOFILE_IDS 0x61 #define MFDES_GET_KEY_VERSION 0x64 #define MFDES_GET_APPLICATION_IDS 0x6A @@ -376,19 +370,10 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_GET_FREE_MEMORY 0x6E #define MFDES_GET_DF_NAMES 0x6D #define MFDES_GET_FILE_IDS 0x6F - - #define MFDES_ABORT_TRANSACTION 0xA7 -#define MFDES_AUTHENTICATION_FRAME 0xAF #define MFDES_ADDITIONAL_FRAME 0xAF -#define MFDES_ADDITIONAL_FRAME_RESP 0x91AF -#define MFDES_SUCCESS_FRAME_RESP 0x9100 -#define MFDES_EAUTH_RESP 0x91AE -#define MFDES_ENO_SUCH_KEY_RESP 0x9140 - #define MFDES_READ_RECORDS 0xBB #define MFDES_READ_DATA 0xBD - #define MFDES_CREATE_CYCLIC_RECORD_FILE 0xC0 #define MFDES_CREATE_LINEAR_RECORD_FILE 0xC1 #define MFDES_CHANGE_KEY 0xC4 @@ -397,15 +382,41 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_CREATE_BACKUP_DATA_FILE 0xCB #define MFDES_CREATE_VALUE_FILE 0xCC #define MFDES_CREATE_STD_DATA_FILE 0xCD - -#define MFDES_CLEAR_RECORD_FILE 0xEB - #define MFDES_DELETE_APPLICATION 0xDA +#define MFDES_DEBIT 0xDC #define MFDES_DELETE_FILE 0xDF - +#define MFDES_CLEAR_RECORD_FILE 0xEB #define MFDES_GET_FILE_SETTINGS 0xF5 #define MFDES_FORMAT_PICC 0xFC + +// MIFARE DESFire status & error codes: +#define MFDES_S_OPERATION_OK 0x00 +#define MFDES_S_NO_CHANGES 0x0C +#define MFDES_S_SIGNATURE 0x90 +#define MFDES_S_ADDITIONAL_FRAME 0xAF + +#define MFDES_E_OUT_OF_EEPROM 0x0E +#define MFDES_E_ILLEGAL_COMMAND_CODE 0x1C +#define MFDES_E_INTEGRITY_ERROR 0x1E +#define MFDES_E_NO_SUCH_KEY 0x40 +#define MFDES_E_LENGTH 0x7E +#define MFDES_E_PERMISSION_DENIED 0x9D +#define MFDES_E_PARAMETER_ERROR 0x9E +#define MFDES_E_APPLICATION_NOT_FOUND 0xA0 +#define MFDES_E_APPL_INTEGRITY 0xA1 +#define MFDES_E_AUTHENTIFICATION_ERROR 0xAE +#define MFDES_E_BOUNDARY 0xBE +#define MFDES_E_PICC_INTEGRITY 0xC1 +#define MFDES_E_COMMAND_ABORTED 0xCA +#define MFDES_E_PICC_DISABLED 0xCD +#define MFDES_E_COUNT 0xCE +#define MFDES_E_DUPLICATE 0xDE +#define MFDES_E_EEPROM 0xEE +#define MFDES_E_FILE_NOT_FOUND 0xF0 +#define MFDES_E_FILE_INTEGRITY 0xF1 + + // LEGIC Commands #define LEGIC_MIM_22 0x0D #define LEGIC_MIM_256 0x1D