diff --git a/CHANGELOG.md b/CHANGELOG.md index 3975e12cb..ce186a2b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ 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] + - Fix `hf mfdes` authentification issues, DES working (@bkerler) + - Add Android cross-compilation to client cmake (@dxl, @doegox) + - Fix `emv scan` - now saves in current folder and uses unique names (@iceman1001) + - Fix pm3.sh - parse COM ports larger than one digit (@doegox) - Fix stack size and automatically use available space for BigBuf. Stack is now 5K (@slurdge) - Added Mifare MAD Card Holder Information decoding (@lukaskuzmiak) - Change Better precision for HF and LF voltage measurements and Add theremin.py script (@rosco) diff --git a/README.md b/README.md index 9d69ba832..1a1a06699 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ |[Notes on external flash](/doc/ext_flash_notes.md)|[Notes on loclass](/doc/loclass_notes.md)|[Notes on Coverity Scan Config & Run](/doc/md/Development/Coverity-Scan-Config-%26-Run.md)| |[Notes on file formats used with Proxmark3](/doc/extensions_notes.md)|[Notes on MFU binary format](/doc/mfu_binary_format_notes.md)|[Notes on FPGA & ARM](/doc/fpga_arm_notes.md)| |[Developing standalone mode](/armsrc/Standalone/readme.md)|[Wiki about standalone mode](https://github.com/RfidResearchGroup/proxmark3/wiki/Standalone-mode)|| - +|[Notes on Color usage](/doc/colors_notes.md)|| ## Build for non-RDV4 Proxmark3 platforms diff --git a/armsrc/i2c.c b/armsrc/i2c.c index 7e7ba4605..82b4fdb10 100644 --- a/armsrc/i2c.c +++ b/armsrc/i2c.c @@ -626,9 +626,8 @@ int I2C_get_version(uint8_t *maj, uint8_t *min) { *maj = resp[0]; *min = resp[1]; return PM3_SUCCESS; - } else { - return PM3_EDEVNOTSUPP; } + return PM3_EDEVNOTSUPP; } // Will read response from smart card module, retries 3 times to get the data. diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 8db8ebf9c..0de34d58f 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -4,6 +4,13 @@ # On Proxspace 3.3 or less, you need to install cmake: # pacman -S mingw-w64-x86_64-cmake # /mingw64/bin/cmake -G"MSYS Makefiles" .. +# +# Android cross-compilation: +# cmake \ +# -DCMAKE_TOOLCHAIN_FILE=/build/cmake/android.toolchain.cmake \ +# -DANDROID_ABI=armeabi-v7a \ +# -DANDROID_NATIVE_API_LEVEL=android-19 \ +# -DSKIPBT=1 -DSKIPPYTHON=1 -DSKIPPTHREAD=1 .. cmake_minimum_required(VERSION 3.10) project(proxmark3) @@ -49,21 +56,75 @@ if (NOT SKIPPYTHON EQUAL 1) pkg_search_module(PYTHON3EMBED QUIET python3-embed) endif (NOT SKIPPYTHON EQUAL 1) +# If build on android cross, we need to init source and build. +if (ANDROID) + set(CFLAGS_EXTERNAL_LIB CFLAGS=--target=${CMAKE_C_COMPILER_TARGET}) + include(ExternalProject) +endif (ANDROID) + if (NOT SKIPREADLINE EQUAL 1) if (APPLE) find_path(READLINE_INCLUDE_DIRS readline/readline.h /usr/local/opt/readline/include /opt/local/include /opt/include /usr/local/include /usr/include NO_DEFAULT_PATH) - endif (APPLE) - find_path(READLINE_INCLUDE_DIRS readline/readline.h) - - if (APPLE) find_library(READLINE_LIBRARIES readline /usr/local/opt/readline/lib /opt/local/lib /opt/lib /usr/local/lib /usr/lib NO_DEFAULT_PATH) endif (APPLE) - find_library(READLINE_LIBRARIES readline) + if (ANDROID) + ExternalProject_Add(ncurses + URL http://ftp.gnu.org/pub/gnu/ncurses/ncurses-6.0.tar.gz + PREFIX deps/ncurses + DOWNLOAD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/ncurses + CONFIGURE_COMMAND ./configure CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} LD=${CMAKE_C_COMPILER} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB} ${CFLAGS_EXTERNAL_LIB} --host=arm + BUILD_IN_SOURCE ON + BUILD_COMMAND make -j2 libs + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + ExternalProject_Add_StepTargets(ncurses configure build install) + + ExternalProject_Add(readline + URL ftp://ftp.gnu.org/gnu/readline/readline-7.0.tar.gz + PREFIX deps/readline + DOWNLOAD_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/readline + CONFIGURE_COMMAND ./configure CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} LD=${CMAKE_C_COMPILER} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB} ${CFLAGS_EXTERNAL_LIB} --host=arm --enable-static + BUILD_IN_SOURCE ON + BUILD_COMMAND make -j2 + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + ExternalProject_Add_StepTargets(readline configure build install) + set(READLINE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/deps/readline/src/) + set(READLINE_LIBRARIES ${CMAKE_CURRENT_BINARY_DIR}/deps/readline/src/readline/libreadline.a ${CMAKE_CURRENT_BINARY_DIR}/deps/ncurses/src/ncurses/lib/libncurses.a) + else (ANDROID) + find_path(READLINE_INCLUDE_DIRS readline/readline.h) + find_library(READLINE_LIBRARIES readline) + endif (ANDROID) if (READLINE_INCLUDE_DIRS AND READLINE_LIBRARIES) set(READLINE_FOUND ON) endif (READLINE_INCLUDE_DIRS AND READLINE_LIBRARIES) endif (NOT SKIPREADLINE EQUAL 1) +if(ANDROID) + set(BZIP2_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/deps/bzip2/src/bzip2) + ExternalProject_Add(bzip2 + GIT_REPOSITORY https://android.googlesource.com/platform/external/bzip2 + GIT_TAG platform-tools-30.0.2 + PREFIX deps/bzip2 + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/deps/bzip2 + CONFIGURE_COMMAND mkdir -p ${BZIP2_BUILD_DIR} && git archive --format tar HEAD | tar -C ${BZIP2_BUILD_DIR} -x + BUILD_IN_SOURCE ON + BUILD_COMMAND make -C ${BZIP2_BUILD_DIR} -j4 CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER} LD=${CMAKE_C_COMPILER} AR=${CMAKE_AR} RANLIB=${CMAKE_RANLIB} ${CFLAGS_EXTERNAL_LIB} libbz2.a + INSTALL_COMMAND "" + LOG_DOWNLOAD ON + ) + ExternalProject_Add_StepTargets(bzip2 configure build install) + set(BZIP2_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR}/deps/bzip2/src/bzip2) + set(BZIP2_LIBRARIES ${CMAKE_CURRENT_BINARY_DIR}/deps/bzip2/src/bzip2/libbz2.a) +else() + set(BZIP2_LIBRARIES bz2) +endif(ANDROID) +if (BZIP2_LIBRARIES) + set(BZIP2_FOUND ON) +endif (BZIP2_LIBRARIES) + add_subdirectory(${PM3_ROOT}/client/deps deps) set (TARGET_SOURCES @@ -268,6 +329,12 @@ if (NOT SKIPREADLINE EQUAL 1) set(ADDITIONAL_LNK ${READLINE_LIBRARIES} ${ADDITIONAL_LNK}) endif (READLINE_FOUND) endif(NOT SKIPREADLINE EQUAL 1) +if (BZIP2_FOUND) + set(ADDITIONAL_DIRS ${BZIP2_INCLUDE_DIRS} ${ADDITIONAL_DIRS}) + set(ADDITIONAL_LNK ${BZIP2_LIBRARIES} ${ADDITIONAL_LNK}) +else (BZIP2_FOUND) + message(FATAL_ERROR "Bzip2 not found") +endif (BZIP2_FOUND) message("===================================================================") if (SKIPQT EQUAL 1) @@ -320,6 +387,12 @@ add_executable(proxmark3 ) target_compile_options(proxmark3 PUBLIC -Wall -Werror -O3) +if (ANDROID) + if (NOT SKIPREADLINE EQUAL 1) + add_dependencies(proxmark3 ncurses readline) + endif (NOT SKIPREADLINE EQUAL 1) + add_dependencies(proxmark3 bzip2) +endif (ANDROID) if (MINGW) # Mingw uses by default Microsoft printf, we want the GNU printf (e.g. for %z) @@ -357,7 +430,6 @@ find_library(pm3rrg_rdv4_hardnested REQUIRED) find_library(pm3rrg_rdv4_whereami REQUIRED) target_link_libraries(proxmark3 PRIVATE - bz2 m pm3rrg_rdv4_mbedtls pm3rrg_rdv4_cliparser diff --git a/client/dictionaries/mfc_default_keys.dic b/client/dictionaries/mfc_default_keys.dic index 26f1f938e..cc68b0d88 100644 --- a/client/dictionaries/mfc_default_keys.dic +++ b/client/dictionaries/mfc_default_keys.dic @@ -605,6 +605,7 @@ d58023ba2bdc # charlie 62ced42a6d87 # charlie 2548a443df28 # charlie 2ed3b15e7c0f # charlie +f66224ee1e89 # charlie # 60012e9ba3fa # diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c index f5ba787ad..a91c1a418 100644 --- a/client/src/cmdhflegic.c +++ b/client/src/cmdhflegic.c @@ -12,7 +12,7 @@ #include // for Mingw readline #include // tolower -#ifndef ANDROID +#ifdef HAVE_READLINE #include #endif diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index d1c38373a..920fcaba8 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -7,6 +7,8 @@ //----------------------------------------------------------------------------- // High frequency MIFARE Desfire commands //----------------------------------------------------------------------------- +// Code heavily modified by B.Kerler :) + #include "cmdhfmfdes.h" #include @@ -32,13 +34,24 @@ #define MAX_KEY_LEN 24 #define MAX_KEYS_LIST_LEN 1024 -static struct desfire_key defaultkey = {0}; -static desfirekey_t sessionkey = &defaultkey; +struct desfire_key default_key = {0}; -//uint8_t key_zero_data[16] = { 0x00 }; -//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 }; +uint8_t desdefaultkeys[3][8] = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, //Official + {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47}, + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07} +}; + +uint8_t aesdefaultkeys[5][16] = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, //Official, TRF7970A + {0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53, 0x79, 0x70, 0x25, 0x53}, // TRF7970A + {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}, // TRF7970A + {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, + {0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f} +}; + +uint8_t k3kdefaultkeys[1][24] = {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; + +struct desfire_tag mf_state = {.session_key = NULL, .authentication_scheme = AS_LEGACY, .authenticated_key_no = NOT_YET_AUTHENTICATED, .crypto_buffer = NULL, .crypto_buffer_size = 0, .selected_application = 0}; +static desfiretag_t tag = &mf_state; typedef struct { uint8_t mode; @@ -48,6 +61,8 @@ typedef struct { uint8_t key[24]; } PACKED mfdes_authinput_t; +static mfdes_authinput_t currentauth[0xF] = {{.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}, {.keyno = -1}}; + typedef struct mfdes_auth_res { uint8_t sessionkeylen; uint8_t sessionkey[24]; @@ -325,8 +340,8 @@ 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); + uint16_t usize = 1 << (((uint16_t)fsize >> 1) + 1); + uint16_t lsize = 1 << ((uint16_t)fsize >> 1); // is LSB set? if (fsize & 1) @@ -375,7 +390,7 @@ static char *getVersionStr(uint8_t major, uint8_t minor) { } -static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) { +static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, uint32_t max_result_len, uint32_t *result_len, uint16_t *sw) { *result_len = 0; if (sw) *sw = 0; @@ -402,7 +417,7 @@ static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, if (GetAPDULogging() || (g_debugMode > 1)) PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, datalen)); - res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, result_len); + res = ExchangeAPDU14a(data, datalen, activate_field, leavefield_on, result, max_result_len, (int *)result_len); if (res) { return res; } @@ -552,15 +567,11 @@ static const char *GetErrorString(int res, uint16_t *sw) { return ""; } -static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_len, uint16_t *sw, int splitbysize, bool readalldata) { +static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, uint32_t *recv_len, uint16_t *sw, uint32_t 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; @@ -572,9 +583,9 @@ static int send_desfire_cmd(sAPDU *apdu, bool select, uint8_t *dest, int *recv_l *sw = 0; uint8_t data[255 * 5] = {0x00}; - int resplen = 0; - int pos = 0; - int i = 1; + uint32_t resplen = 0; + uint32_t pos = 0; + uint32_t i = 1; int res = DESFIRESendApdu(select, true, *apdu, data, sizeof(data), &resplen, sw); if (res != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "%s", GetErrorString(res, sw)); @@ -642,10 +653,12 @@ static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) { return DESFIRE_UNKNOWN; } -static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, bool def_key) { +static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload) { // 3 different way to authenticate AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32) // 4 different crypto arg1 DES, 3DES, 3K3DES, AES // 3 different communication modes, PLAIN,MAC,CRYPTO + tag->authenticated_key_no = NOT_YET_AUTHENTICATED; + tag->session_key = NULL; mbedtls_aes_context ctx; @@ -669,27 +682,8 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp value = prng_successor(ng, 32); num_to_bytes(value, 4, &RndA[12]); - // Default Keys - uint8_t PICC_MASTER_KEY8[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - uint8_t PICC_MASTER_KEY16[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - uint8_t PICC_MASTER_KEY24[24] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - //uint8_t null_key_data16[16] = {0x00}; - //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; - //uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF}; - - // Part 1 - if (def_key) { - if (payload->algo == MFDES_AUTH_DES) { - memcpy(keybytes, PICC_MASTER_KEY8, 8); - } else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES) { - memcpy(keybytes, PICC_MASTER_KEY16, 16); - } else if (payload->algo == MFDES_ALGO_3DES) { - memcpy(keybytes, PICC_MASTER_KEY24, 24); - } - } else { - memcpy(keybytes, payload->key, payload->keylen); - } + memcpy(keybytes, payload->key, payload->keylen); struct desfire_key dkey = {0}; desfirekey_t key = &dkey; @@ -706,13 +700,17 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } uint8_t subcommand = MFDES_AUTHENTICATE; + tag->authentication_scheme = AS_LEGACY; - if (payload->mode == MFDES_AUTH_AES) + if (payload->mode == MFDES_AUTH_AES) { subcommand = MFDES_AUTHENTICATE_AES; - else if (payload->mode == MFDES_AUTH_ISO) + tag->authentication_scheme = AS_NEW; + } else if (payload->mode == MFDES_AUTH_ISO) { subcommand = MFDES_AUTHENTICATE_ISO; + tag->authentication_scheme = AS_NEW; + } - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; uint8_t recv_data[256] = {0}; @@ -739,7 +737,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp return 3; } - int expectedlen = 8; + uint32_t expectedlen = 8; if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) { expectedlen = 16; } @@ -747,7 +745,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp if (recv_len != expectedlen) { return 4; } - int rndlen = recv_len; + uint32_t rndlen = recv_len; // Part 2 if (payload->mode != MFDES_AUTH_PICC) { @@ -756,7 +754,6 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp memcpy(encRndB, recv_data + 2, rndlen); } - // Part 3 if (payload->algo == MFDES_ALGO_AES) { if (mbedtls_aes_setkey_dec(&ctx, key->data, 128) != 0) { @@ -787,7 +784,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp des_decrypt(encRndA, RndA, key->data); memcpy(both, encRndA, rndlen); - for (int x = 0; x < rndlen; x++) { + for (uint32_t x = 0; x < rndlen; x++) { rotRndB[x] = rotRndB[x] ^ encRndA[x]; } @@ -838,7 +835,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } } - int bothlen = 16; + uint32_t bothlen = 16; if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3K3DES) { bothlen = 32; } @@ -875,7 +872,8 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } // Part 4 - Desfire_session_key_new(RndA, RndB, key, sessionkey); + tag->session_key = &default_key; + Desfire_session_key_new(RndA, RndB, key, tag->session_key); if (payload->mode != MFDES_AUTH_PICC) { memcpy(encRndA, recv_data, rndlen); @@ -898,7 +896,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } rol(RndA, rndlen); - for (int x = 0; x < rndlen; x++) { + for (uint32_t x = 0; x < rndlen; x++) { if (RndA[x] != encRndA[x]) { if (g_debugMode > 1) { PrintAndLogEx(INFO, "Expected_RndA : %s", sprint_hex(RndA, rndlen)); @@ -909,7 +907,12 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp } rpayload->sessionkeylen = payload->keylen; - memcpy(rpayload->sessionkey, sessionkey->data, rpayload->sessionkeylen); + memcpy(rpayload->sessionkey, tag->session_key->data, rpayload->sessionkeylen); + memset(tag->ivect, 0, MAX_CRYPTO_BLOCK_SIZE); + tag->authenticated_key_no = payload->keyno; + if (tag->authentication_scheme == AS_NEW) { + cmac_generate_subkeys(tag->session_key); + } return PM3_SUCCESS; } @@ -952,11 +955,13 @@ static void AuthToError(int error) { break; } } + + // -- test if card supports 0x0A static int test_desfire_authenticate(void) { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false); if (res == PM3_SUCCESS) @@ -971,7 +976,7 @@ static int test_desfire_authenticate(void) { static int test_desfire_authenticate_iso(void) { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false); if (res == PM3_SUCCESS) @@ -986,7 +991,7 @@ static int test_desfire_authenticate_iso(void) { static int test_desfire_authenticate_aes(void) { uint8_t data[] = {0x00}; sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, false); if (res == PM3_SUCCESS) @@ -1008,15 +1013,23 @@ static int handler_desfire_freemem(uint32_t *free_mem) { sAPDU apdu = {0x90, MFDES_GET_FREE_MEMORY, 0x00, 0x00, 0x00, NULL}; // 0x6E *free_mem = 0; - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; uint8_t fmem[4] = {0}; + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; + int res = send_desfire_cmd(&apdu, true, fmem, &recv_len, &sw, 0, true); if (res != PM3_SUCCESS) return res; + size_t dlen = recv_len; + p = mifare_cryto_postprocess_data(tag, apdu.data, &dlen, MDCM_PLAIN | CMAC_COMMAND | CMAC_VERIFY); + if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; @@ -1024,6 +1037,119 @@ static int handler_desfire_freemem(uint32_t *free_mem) { return res; } +static int mifare_desfire_change_key(uint8_t key_no, uint8_t *new_key, uint8_t new_algo, uint8_t *old_key, uint8_t old_algo, uint8_t aes_version) { + key_no &= 0x0F; + + /* + * Because new crypto methods can be setup only at application creation, + * changing the card master key to one of them require a key_no tweak. + */ + if (0x000000 == tag->selected_application) { + switch (new_algo) { + case MFDES_ALGO_DES: + break; + case MFDES_ALGO_3K3DES: + key_no |= 0x40; + break; + case MFDES_ALGO_AES: + key_no |= 0x80; + break; + } + } + + uint8_t data[24 * 4] = {key_no}; + sAPDU apdu = {0x90, MFDES_CHANGE_KEY, 0x00, 0x00, 0x01, data}; // 0xC4 + + uint8_t new_key_length = 16; + switch (new_algo) { + case MFDES_ALGO_DES: + case MFDES_ALGO_AES: + new_key_length = 16; + break; + case MFDES_ALGO_3K3DES: + new_key_length = 24; + break; + } + + uint32_t cmdcnt = 0; + memcpy(data + cmdcnt + 1, new_key, new_key_length); + + if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { + if (old_key) { + for (uint32_t n = 0; n < new_key_length; n++) { + data[cmdcnt + 1 + n] ^= old_key[n]; + } + } + } + + cmdcnt += new_key_length; + + if (new_algo == MFDES_ALGO_AES) { + data[cmdcnt + 1] = aes_version; + cmdcnt += 1; + } + + if ((tag->authenticated_key_no & 0x0f) != (key_no & 0x0f)) { + switch (tag->authentication_scheme) { + case AS_LEGACY: + iso14443a_crc_append(data + 1, cmdcnt); + cmdcnt += 2; + iso14443a_crc(new_key, new_key_length, data + cmdcnt); + cmdcnt += 2; + break; + case AS_NEW: + desfire_crc32_append(data + 1, cmdcnt); + cmdcnt += 4; + + desfire_crc32(new_key, new_key_length, data + cmdcnt); + cmdcnt += 4; + break; + } + } else { + switch (tag->authentication_scheme) { + case AS_LEGACY: + iso14443a_crc_append(data + 1, cmdcnt); + cmdcnt += 2; + break; + case AS_NEW: + desfire_crc32_append(data, cmdcnt); + cmdcnt += 4; + break; + } + } + + uint8_t *p = mifare_cryto_preprocess_data(tag, data + 1, (size_t *)&cmdcnt, 0, MDCM_ENCIPHERED | ENC_COMMAND | NO_CRC); + apdu.Lc = (uint8_t)cmdcnt + 1; + apdu.data = p; + + uint32_t recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't change key -> %s"), GetErrorString(res, &sw)); + DropField(); + return res; + } + + size_t sn = recv_len; + p = mifare_cryto_postprocess_data(tag, data, &sn, MDCM_PLAIN | CMAC_COMMAND | CMAC_VERIFY); + + if (!p) + return PM3_ESOFT; + + /* + * If we changed the current authenticated key, we are not authenticated + * anymore. + */ + if (key_no == tag->authenticated_key_no) { + free(tag->session_key); + tag->session_key = NULL; + } + + return 0; +} + // --- GET SIGNATURE static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t signature_len, nxp_cardtype_t card_type) { (void)card_type; @@ -1049,7 +1175,7 @@ static int desfire_print_signature(uint8_t *uid, uint8_t *signature, size_t sign {"Mifare Plus EV1", "044409ADC42F91A8394066BA83D872FB1D16803734E911170412DDF8BAD1A4DADFD0416291AFE1C748253925DA39A5F39A1C557FFACD34C62E"} }; - uint8_t i; + uint32_t i; bool is_valid = false; for (i = 0; i < ARRAYLEN(nxp_desfire_public_keys); i++) { @@ -1097,7 +1223,8 @@ static int handler_desfire_signature(uint8_t *signature, size_t *signature_len) uint8_t c[] = {0x00}; sAPDU apdu = {0x90, MFDES_READSIG, 0x00, 0x00, sizeof(c), c}; // 0x3C - int recv_len = 0; + + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, signature, &recv_len, &sw, 0, true); if (res == PM3_SUCCESS) { @@ -1113,24 +1240,16 @@ static int handler_desfire_signature(uint8_t *signature, size_t *signature_len) } // --- KEY SETTING -static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { +static int desfire_print_keysetting(uint8_t key_settings, mifare_des_authalgo_t algo) { PrintAndLogEx(SUCCESS, " AID Key settings : 0x%02x", key_settings); // 2 MSB denotes const char *str = " Max key number and type : %d, " _YELLOW_("%s"); - switch (num_keys >> 6) { - case 0: - PrintAndLogEx(SUCCESS, str, num_keys & 0x3F, "(3)DES"); - break; - case 1: - PrintAndLogEx(SUCCESS, str, num_keys & 0x3F, "3K3DES"); - break; - case 2: - PrintAndLogEx(SUCCESS, str, num_keys & 0x3F, "AES"); - break; - default: - break; - } + + if (algo == MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); + else if (algo == MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); + else if (algo == MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); + //PrintAndLogEx(SUCCESS, " Max number of keys in AID : %d", num_keys & 0x3F); PrintAndLogEx(INFO, "-------------------------------------------------------------"); PrintAndLogEx(SUCCESS, " Changekey Access rights"); @@ -1159,7 +1278,7 @@ static int desfire_print_keysetting(uint8_t key_settings, uint8_t num_keys) { return PM3_SUCCESS; } -static int handler_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) { +static int handler_desfire_getkeysettings(uint8_t *key_settings, uint8_t *num_keys) { if (key_settings == NULL) { PrintAndLogEx(DEBUG, "KEY_SETTINGS=NULL"); return PM3_EINVARG; @@ -1169,7 +1288,8 @@ static int handler_desfire_keysettings(uint8_t *key_settings, uint8_t *num_keys) return PM3_EINVARG; } sAPDU apdu = {0x90, MFDES_GET_KEY_SETTINGS, 0x00, 0x00, 0x00, NULL}; //0x45 - int recv_len = 0; + + uint32_t recv_len = 0; uint16_t sw = 0; uint8_t data[2] = {0}; int res = send_desfire_cmd(&apdu, false, data, &recv_len, &sw, 0, true); @@ -1196,7 +1316,7 @@ static int handler_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { return PM3_EINVARG; } sAPDU apdu = {0x90, MFDES_GET_KEY_VERSION, 0x00, 0x00, 0x01, &curr_key}; //0x64 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, num_versions, &recv_len, &sw, 0, true); @@ -1209,9 +1329,28 @@ static int handler_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) { return res; } +static int handler_desfire_getuid(uint8_t *uid) { + if (uid == NULL) { + PrintAndLogEx(DEBUG, "UID=NULL"); + return PM3_EINVARG; + } + sAPDU apdu = {0x90, MFDES_GET_UID, 0x00, 0x00, 0x00, NULL}; //0x51 + uint32_t recv_len = 0; + uint16_t sw = 0; + int res = send_desfire_cmd(&apdu, false, uid, &recv_len, &sw, 0, true); + + if (res != PM3_SUCCESS) + return res; + + if (sw != status(MFDES_S_OPERATION_OK)) + return PM3_ESOFT; + + return res; +} + static int handler_desfire_commit_transaction(void) { sAPDU apdu = {0x90, MFDES_COMMIT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xC7 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, true); @@ -1226,7 +1365,7 @@ static int handler_desfire_commit_transaction(void) { /*static int handler_desfire_abort_transaction(void) { sAPDU apdu = {0x90, MFDES_ABORT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xA7 - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recv_len, &sw, 0, true); @@ -1240,7 +1379,7 @@ static int handler_desfire_commit_transaction(void) { }*/ // --- GET APPIDS -static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { +static int handler_desfire_appids(uint8_t *dest, uint32_t *app_ids_len) { if (dest == NULL) { PrintAndLogEx(DEBUG, "DEST=NULL"); return PM3_EINVARG; @@ -1251,7 +1390,7 @@ static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { } sAPDU apdu = {0x90, MFDES_GET_APPLICATION_IDS, 0x00, 0x00, 0x00, NULL}; //0x6a - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, dest, &recv_len, &sw, 0, true); @@ -1261,12 +1400,13 @@ static int handler_desfire_appids(uint8_t *dest, uint8_t *app_ids_len) { if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; - *app_ids_len = (uint8_t)recv_len & 0xFF; + *app_ids_len = (uint8_t)(recv_len & 0xFF); return res; } // --- GET DF NAMES static int handler_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { + *dfname_count = 0; if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (dfname_count == NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL"); @@ -1277,11 +1417,12 @@ static int handler_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) { *dfname_count = 0; sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t), true); - if (res != PM3_SUCCESS) + if (res != PM3_SUCCESS) { return res; + } if (sw != status(MFDES_S_OPERATION_OK)) return PM3_ESOFT; @@ -1296,7 +1437,7 @@ static int handler_desfire_select_application(uint8_t *aid) { } if (aid == NULL) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_SELECT_APPLICATION, 0x00, 0x00, 0x03, aid}; //0x5a - int recv_len = 0; + uint32_t recv_len = 0; uint16_t sw = 0; int res = send_desfire_cmd(&apdu, true, NULL, &recv_len, &sw, sizeof(dfname_t), true); if (res != PM3_SUCCESS) { @@ -1304,18 +1445,40 @@ static int handler_desfire_select_application(uint8_t *aid) { DropField(); return res; } + memcpy(&tag->selected_application, aid, 3); return PM3_SUCCESS; } -// none, verified -static int handler_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { +static int key_setting_to_algo(uint8_t aid[3], uint8_t *key_setting, mifare_des_authalgo_t *algo) { + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + + uint8_t num_keys = 0; + res = handler_desfire_getkeysettings(key_setting, &num_keys); + if (res == PM3_SUCCESS) { + switch (num_keys >> 6) { + case 0: + *algo = MFDES_ALGO_DES; + break; + case 1: + *algo = MFDES_ALGO_3K3DES; + break; + case 2: + *algo = MFDES_ALGO_AES; + break; + } + } + return res; +} + +static int handler_desfire_fileids(uint8_t *dest, uint32_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; + uint32_t recv_len = 0; uint16_t sw = 0; *file_ids_len = 0; int res = send_desfire_cmd(&apdu, false, dest, &recv_len, &sw, 0, true); @@ -1329,7 +1492,7 @@ static int handler_desfire_fileids(uint8_t *dest, uint8_t *file_ids_len) { } // none, verified -static int handler_desfire_filesettings(uint8_t file_id, uint8_t *dest, int *destlen) { +static int handler_desfire_filesettings(uint8_t file_id, uint8_t *dest, uint32_t *destlen) { if (g_debugMode > 1) { if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL"); if (destlen == NULL) PrintAndLogEx(ERR, "DESTLEN=NULL"); @@ -1374,7 +1537,7 @@ static int handler_desfire_createapp(aidhdr_t *aidhdr, bool usename, bool usefid } uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (data != NULL) free(data); if (res != PM3_SUCCESS) { @@ -1386,11 +1549,11 @@ static int handler_desfire_createapp(aidhdr_t *aidhdr, bool usename, bool usefid return res; } -static int handler_desfire_deleteapp(uint8_t *aid) { +static int handler_desfire_deleteapp(const uint8_t *aid) { if (aid == NULL) return PM3_EINVARG; - sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, aid}; // 0xDA + sAPDU apdu = {0x90, MFDES_DELETE_APPLICATION, 0x00, 0x00, 3, (uint8_t *)aid}; // 0xDA uint16_t sw = 0; - int recvlen = 0; + uint32_t 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)); @@ -1400,10 +1563,16 @@ static int handler_desfire_deleteapp(uint8_t *aid) { return res; } -static int handler_desfire_credit(mfdes_value_t *value) { +static int handler_desfire_credit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_CREDIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0x0C uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; + + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't credit value -> %s"), GetErrorString(res, &sw)); @@ -1413,10 +1582,16 @@ static int handler_desfire_credit(mfdes_value_t *value) { return res; } -static int handler_desfire_limitedcredit(mfdes_value_t *value) { +static int handler_desfire_limitedcredit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_LIMITED_CREDIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0x1C uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; + + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't credit limited value -> %s"), GetErrorString(res, &sw)); @@ -1426,10 +1601,16 @@ static int handler_desfire_limitedcredit(mfdes_value_t *value) { return res; } -static int handler_desfire_debit(mfdes_value_t *value) { +static int handler_desfire_debit(mfdes_value_t *value, uint8_t cs) { sAPDU apdu = {0x90, MFDES_DEBIT, 0x00, 0x00, 1 + 4, (uint8_t *)value}; // 0xDC uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; + + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't debit value -> %s"), GetErrorString(res, &sw)); @@ -1439,42 +1620,59 @@ static int handler_desfire_debit(mfdes_value_t *value) { return res; } -static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) { +static int handler_desfire_readdata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, uint8_t cs) { if (data->fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_READ_DATA, 0x00, 0x00, 1 + 3 + 3, (uint8_t *)data}; // 0xBD if (type == MFDES_RECORD_FILE) apdu.INS = MFDES_READ_RECORDS; //0xBB uint16_t sw = 0; - int resplen = 0; + uint32_t resplen = 0; + + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; + int res = send_desfire_cmd(&apdu, false, data->data, &resplen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't read data -> %s"), GetErrorString(res, &sw)); DropField(); return res; } - data->length[2] = (uint8_t)(resplen & 0xFF); - data->length[1] = (uint8_t)((resplen >> 8) & 0xFF); - data->length[0] = (uint8_t)((resplen >> 16) & 0xFF); + + size_t dlen = resplen; + p = mifare_cryto_postprocess_data(tag, data->data, &dlen, cs | CMAC_COMMAND | CMAC_VERIFY | MAC_VERIFY); + if (dlen != -1) resplen = dlen; memcpy(data->length, &resplen, 3); + + return res; } -static int handler_desfire_getvalue(mfdes_value_t *value, int *resplen) { +static int handler_desfire_getvalue(mfdes_value_t *value, uint32_t *resplen, uint8_t cs) { if (value->fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_GET_VALUE, 0x00, 0x00, 0x01, &value->fileno}; // 0xBD uint16_t sw = 0; *resplen = 0; + + size_t plen = apdu.Lc; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)apdu.data, &plen, 0, MDCM_PLAIN | CMAC_COMMAND); + apdu.Lc = (uint8_t)plen; + apdu.data = p; + int res = send_desfire_cmd(&apdu, false, value->value, resplen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't read data -> %s"), GetErrorString(res, &sw)); DropField(); return res; } + size_t dlen = (size_t)resplen; + p = mifare_cryto_postprocess_data(tag, value->value, &dlen, cs | CMAC_COMMAND | CMAC_VERIFY | MAC_VERIFY); return res; } -static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) { +static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type, uint8_t cs) { /* LC FN OF OF OF LN LN LN DD DD DD 90 3d 00 00 16 01 00 00 00 0f 00 00 00 0f 20 00 3b 00 34 04 06 e1 04 0f fe 00 00 00 90 3d 00 00 09 02 00 00 00 02 00 00 00 00 00 @@ -1483,9 +1681,9 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) if (data->fileno > 0x1F) return PM3_EINVARG; uint32_t datatowrite = le24toh(data->length); uint32_t offset = le24toh(data->offset); - int datasize; - int pos = 0; - int recvlen = 0; + uint32_t datasize; + uint32_t pos = 0; + uint32_t recvlen = 0; int res = PM3_SUCCESS; uint16_t sw = 0; uint8_t tmp[59] = {0}; @@ -1509,9 +1707,15 @@ static int handler_desfire_writedata(mfdes_data_t *data, MFDES_FILE_TYPE_T type) tmp[5] = (datasize >> 8) & 0xFF; tmp[6] = (datasize >> 16) & 0xFF; - memcpy(&tmp[7], &data->data[pos], datasize); + + size_t plen = datasize; + uint8_t *p = mifare_cryto_preprocess_data(tag, (uint8_t *)&data->data[pos], &plen, 0, cs | MAC_COMMAND | CMAC_COMMAND | ENC_COMMAND); + if (plen != -1) datasize = (uint8_t)plen; + memcpy(&tmp[7], p, datasize); + apdu.Lc = datasize + 1 + 3 + 3; + res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't write data -> %s"), GetErrorString(res, &sw)); @@ -1537,7 +1741,7 @@ static int handler_desfire_deletefile(uint8_t fileno) { if (fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_DELETE_FILE, 0x00, 0x00, 1, &fileno}; // 0xDF uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't delete file -> %s"), GetErrorString(res, &sw)); @@ -1551,7 +1755,7 @@ static int handler_desfire_clearrecordfile(uint8_t fileno) { if (fileno > 0x1F) return PM3_EINVARG; sAPDU apdu = {0x90, MFDES_CLEAR_RECORD_FILE, 0x00, 0x00, 1, &fileno}; // 0xEB uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't clear record file -> %s"), GetErrorString(res, &sw)); @@ -1574,7 +1778,7 @@ static int handler_desfire_create_value_file(mfdes_value_file_t *value) { sAPDU apdu = {0x90, MFDES_CREATE_VALUE_FILE, 0x00, 0x00, sizeof(mfdes_value_file_t), (uint8_t *)value}; // 0xCc uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create value -> %s"), GetErrorString(res, &sw)); @@ -1589,7 +1793,7 @@ static int handler_desfire_create_std_file(mfdes_file_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_STD_DATA_FILE, 0x00, 0x00, sizeof(mfdes_file_t), (uint8_t *)file}; // 0xCD uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create file -> %s"), GetErrorString(res, &sw)); @@ -1605,7 +1809,7 @@ static int handler_desfire_create_linearrecordfile(mfdes_linear_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_LINEAR_RECORD_FILE, 0x00, 0x00, sizeof(mfdes_linear_t), (uint8_t *)file}; // 0xC1 uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create linear record file -> %s"), GetErrorString(res, &sw)); @@ -1621,7 +1825,7 @@ static int handler_desfire_create_cyclicrecordfile(mfdes_linear_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_CYCLIC_RECORD_FILE, 0x00, 0x00, sizeof(mfdes_linear_t), (uint8_t *)file}; // 0xC0 uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create cyclic record file -> %s"), GetErrorString(res, &sw)); @@ -1637,7 +1841,7 @@ static int handler_desfire_create_backup_file(mfdes_file_t *file) { sAPDU apdu = {0x90, MFDES_CREATE_BACKUP_DATA_FILE, 0x00, 0x00, sizeof(mfdes_file_t), (uint8_t *)file}; // 0xCB uint16_t sw = 0; - int recvlen = 0; + uint32_t recvlen = 0; int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); if (res != PM3_SUCCESS) { PrintAndLogEx(WARNING, _RED_(" Can't create backup file -> %s"), GetErrorString(res, &sw)); @@ -1655,13 +1859,13 @@ static int getKeySettings(uint8_t *aid) { // CARD MASTER KEY //PrintAndLogEx(INFO, "--- " _CYAN_("CMK - PICC, Card Master Key settings")); - res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) return res; // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - res = handler_desfire_keysettings(&key_setting, &num_keys); + mifare_des_authalgo_t algo; + res = key_setting_to_algo(aid, &key_setting, &algo); + if (res == PM3_SUCCESS) { // number of Master keys (0x01) PrintAndLogEx(SUCCESS, " Number of Masterkeys : " _YELLOW_("%u"), (num_keys & 0x3F)); @@ -1676,20 +1880,9 @@ static int getKeySettings(uint8_t *aid) { const char *str = " Operation of PICC master key : " _YELLOW_("%s"); - // 2 MSB denotes - switch (num_keys >> 6) { - case 0: - PrintAndLogEx(SUCCESS, str, "(3)DES"); - break; - case 1: - PrintAndLogEx(SUCCESS, str, "3K3DES"); - break; - case 2: - PrintAndLogEx(SUCCESS, str, "AES"); - break; - default: - break; - } + if (algo == MFDES_ALGO_DES) PrintAndLogEx(SUCCESS, str, "(3)DES"); + else if (algo == MFDES_ALGO_AES) PrintAndLogEx(SUCCESS, str, "AES"); + else if (algo == MFDES_ALGO_3K3DES) PrintAndLogEx(SUCCESS, str, "3K3DES"); uint8_t cmk_num_versions = 0; if (handler_desfire_keyversion(0, &cmk_num_versions) == PM3_SUCCESS) { @@ -1722,9 +1915,10 @@ static int getKeySettings(uint8_t *aid) { // KEY Settings - AMK uint8_t num_keys = 0; uint8_t key_setting = 0; - res = handler_desfire_keysettings(&key_setting, &num_keys); + mifare_des_authalgo_t algo; + res = key_setting_to_algo(aid, &key_setting, &algo); if (res == PM3_SUCCESS) { - desfire_print_keysetting(key_setting, num_keys); + desfire_print_keysetting(key_setting, algo); } else { PrintAndLogEx(WARNING, _RED_(" Can't read Application Master key settings")); } @@ -1780,6 +1974,129 @@ static void swap16(uint8_t *data) { data[1] = tmp; }; +static int desfire_authenticate(int cmdAuthMode, int cmdAuthAlgo, uint8_t *aid, uint8_t *key, int cmdKeyNo, mfdes_auth_res_t *rpayload) { + switch (cmdAuthMode) { + case MFDES_AUTH_DES: + if (cmdAuthAlgo != MFDES_ALGO_DES && cmdAuthAlgo != MFDES_ALGO_3DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth des mode"); + return PM3_EINVARG; + } + break; + case MFDES_AUTH_ISO: + if (cmdAuthAlgo != MFDES_ALGO_3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode"); + return PM3_EINVARG; + } + break; + case MFDES_AUTH_AES: + if (cmdAuthAlgo != MFDES_ALGO_AES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth aes mode"); + return PM3_EINVARG; + } + break; + case MFDES_AUTH_PICC: + if (cmdAuthAlgo != MFDES_AUTH_DES) { + PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth picc mode"); + return PM3_EINVARG; + } + break; + default: + PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); + return PM3_EINVARG; + } + + int keylength = 16; + + switch (cmdAuthAlgo) { + case MFDES_ALGO_3DES: + keylength = 16; + break; + case MFDES_ALGO_3K3DES: + keylength = 24; + break; + case MFDES_ALGO_AES: + keylength = 16; + break; + default: + cmdAuthAlgo = MFDES_ALGO_DES; + keylength = 8; + break; + } + + // KEY + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) return res; + + if (memcmp(aid, "\x00\x00\x00", 3) != 0) { + uint8_t file_ids[33] = {0}; + uint32_t file_ids_len = 0; + res = handler_desfire_fileids(file_ids, &file_ids_len); + if (res != PM3_SUCCESS) return res; + } + + mfdes_authinput_t payload; + payload.keylen = keylength; + memcpy(payload.key, key, keylength); + payload.mode = cmdAuthMode; + payload.algo = cmdAuthAlgo; + payload.keyno = cmdKeyNo; + + int error = handler_desfire_auth(&payload, rpayload); + if (error == PM3_SUCCESS) { + memcpy(¤tauth[payload.keyno], &payload, sizeof(mfdes_authinput_t)); + } + return error; +} + +static int CmdHF14ADesGetUID(const char *Cmd) { + (void)Cmd; + + uint8_t uid[16] = {0}; + int res = handler_desfire_getuid(uid); + if (res != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(ERR, "Error on getting uid."); + return res; + } + PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(uid, sizeof(uid))); + return res; +} + +static int CmdHF14ADesSelectApp(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes selectaid", + "Select Application ID", + "Usage:\n\thf mfdes selectaid -a 123456\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 1, aid, &aidlength); + CLIParserFree(ctx); + + swap24(aid); + + if (aidlength != 3) { + PrintAndLogEx(ERR, "AID must have 3 bytes length"); + return PM3_EINVARG; + } + + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(ERR, "Error on selecting aid."); + return res; + } + PrintAndLogEx(SUCCESS, "Successfully selected aid."); + return res; +} + static int CmdHF14ADesCreateApp(const char *Cmd) { CLIParserContext *ctx; @@ -1851,7 +2168,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { return PM3_EINVARG; } - if (fidlength != 2) { + if (fidlength != 2 && fidlength != 0) { PrintAndLogEx(ERR, "FID must have 2 bytes length"); return PM3_EINVARG; } @@ -1905,6 +2222,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { res = handler_desfire_createapp(&aidhdr, usename, usefid); DropField(); + PrintAndLogEx(SUCCESS, "Successfully created aid."); return res; } @@ -1942,6 +2260,34 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { if (res != PM3_SUCCESS) { DropField(); return res;} res = handler_desfire_deleteapp(aid); DropField(); + PrintAndLogEx(SUCCESS, "Successfully deleted aid."); + return res; +} + +static int selectfile(uint8_t *aid, uint32_t fileno, uint8_t *cs) { + if (handler_desfire_select_application(aid) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Couldn't select aid.")); + return PM3_ESOFT; + } + + uint8_t filesettings[20] = {0}; + uint32_t fileset_len = 0; + int res = handler_desfire_filesettings(fileno, filesettings, &fileset_len); + + if (tag->session_key != NULL) { + mfdes_auth_res_t rpayload; + uint8_t keyno = (uint8_t)((filesettings[0] >> 4) & 0xF); + if (keyno != 0xE && currentauth[keyno].keyno == keyno) { + if (handler_desfire_auth(¤tauth[keyno], &rpayload) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Couldn't authenticate key.")); + return PM3_ESOFT; + } + } else if (keyno != 0xE) { + PrintAndLogEx(ERR, _RED_(" Please authenticate first.")); + return PM3_ESOFT; + } + } + *cs = filesettings[1]; return res; } @@ -1951,27 +2297,25 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes clearrecord", "Clear record file", "Usage:\n\t" - "hf mfdes clearrecord -a 123456 -n 01\n" + "hf mfdes clearrecord -n 01\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); - - int fidlength = 0; - uint8_t fid[2] = {0}; - CLIGetHexWithReturn(ctx, 3, fid, &fidlength); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 2, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); if (filenolen != 1) { @@ -1984,20 +2328,23 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - swap24(aid); - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; + uint8_t cs = 0; + if (selectfile(aid, _fileno[0], &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; } - res = handler_desfire_clearrecordfile(_fileno[0]); + int res = handler_desfire_clearrecordfile(_fileno[0]); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully cleared record file."); } else { @@ -2012,27 +2359,25 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes deletefile", "Delete File", "Usage:\n\t" - "hf mfdes deletefile -a 123456 -n 01\n" + "hf mfdes deletefile -n 01\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); - - int fidlength = 0; - uint8_t fid[2] = {0}; - CLIGetHexWithReturn(ctx, 3, fid, &fidlength); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 2, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); if (filenolen != 1) { @@ -2045,20 +2390,23 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); } - swap24(aid); - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; + uint8_t cs = 0; + if (selectfile(aid, _fileno[0], &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; } - res = handler_desfire_deletefile(_fileno[0]); + int res = handler_desfire_deletefile(_fileno[0]); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully deleted file.."); } else { @@ -2073,46 +2421,46 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes createfile", "Create Standard/Backup File", "Usage:" - "\n\thf mfdes createfile -a 123456 -f 1111 -n 01 -c 0 -r EEEE -s 000100\n" + "\n\thf mfdes createfile -f 0001 -n 01 -c 0 -r EEEE -s 000100 -a 123456\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("fF", "fileid", "", "ISO FID (2 hex bytes, big endian)"), arg_int0("cC", "com.set", "", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"), - arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"), + arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> RW/Chg/R/W, 0-D Key, E Free, F Denied)"), arg_strx0("sS", "filesize", "", "File size (3 hex bytes, big endian)"), arg_lit0("bB", "backup", "Create backupfile instead of standard file"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int fidlength = 0; uint8_t fid[2] = {0}; - CLIGetHexWithReturn(ctx, 3, fid, &fidlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), fid, 2, &fidlength); - uint8_t comset = arg_get_int(ctx, 4); + uint8_t comset = arg_get_int(ctx, 3); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(ctx, 5, ar, &arlength); + CLIGetHexWithReturn(ctx, 4, ar, &arlength); int fsizelen = 0; uint8_t filesize[3] = {0}; - CLIGetHexWithReturn(ctx, 6, filesize, &fsizelen); + CLIGetHexWithReturn(ctx, 5, filesize, &fsizelen); - bool isbackup = arg_get_lit(ctx, 7); + bool isbackup = arg_get_lit(ctx, 6); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 7, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); - swap24(aid); swap16(fid); swap24(filesize); @@ -2145,19 +2493,6 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } - mfdes_file_t ft; memcpy(ft.fid, fid, 2); memcpy(ft.filesize, filesize, 3); @@ -2165,6 +2500,26 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { ft.comset = comset; memcpy(ft.access_rights, ar, 2); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + DropField(); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + DropField(); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + + int res = handler_desfire_select_application(aid); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Couldn't select aid. Error %d", res); + DropField(); + return res; + } + if (isbackup) res = handler_desfire_create_backup_file(&ft); else @@ -2184,24 +2539,26 @@ static int CmdHF14ADesGetValueData(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes getvalue", "Get value from value file", "Usage:" - "\n\thf mfdes getvalue -a 123456 -n 03\n" + "\n\thf mfdes getvalue -n 03\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); - int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 2, aid, &aidlength); + swap24(aid); + CLIParserFree(ctx); if (filenolen != 1) { @@ -2214,30 +2571,32 @@ static int CmdHF14ADesGetValueData(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - swap24(aid); - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } mfdes_value_t value; value.fileno = _fileno[0]; - int len = 0; - res = handler_desfire_getvalue(&value, &len); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + uint8_t cs = 0; + if (selectfile(aid, value.fileno, &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; + } + + uint32_t len = 0; + int res = handler_desfire_getvalue(&value, &len, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully read value from File %u:", _fileno[0]); PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); - for (int i = 0; i < len; i += 16) { + for (uint32_t i = 0; i < len; i += 16) { PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&value.value[i], len > 16 ? 16 : len), sprint_ascii(&value.value[i], len > 16 ? 16 : len)); } } else { @@ -2252,36 +2611,41 @@ static int CmdHF14ADesReadData(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes readdata", "Read data from File", "Usage:" - "\n\thf mfdes readdata -a 123456 -n 01 -t 0 -o 000000 -l 000000\n" + "\n\thf mfdes readdata -n 01 -t 0 -o 000000 -l 000000 -a 123456\n" + "\thf mfdes readdata -n 01 -t 0 (Read all data from standard file, fileno 01)\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), - arg_strx0("lL", "length", "", "Length to read (3 hex bytes, big endian -> 000000 = Read all data),optional"), - arg_int0("type", "type", "", "File Type (0=Standard/Backup, 1=Record)"), + arg_strx0("lL", "length", "", + "Length to read (3 hex bytes, big endian -> 000000 = Read all data),optional"), + arg_int0("tT", "type", "", "File Type (0=Standard/Backup, 1=Record)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int offsetlength = 0; uint8_t offset[3] = {0}; - CLIGetHexWithReturn(ctx, 3, offset, &offsetlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); int flength = 0; uint8_t filesize[3] = {0}; - CLIGetHexWithReturn(ctx, 4, filesize, &flength); + CLIParamHexToBuf(arg_get_str(ctx, 3), filesize, 3, &flength); - int type = arg_get_int(ctx, 5); + int type = arg_get_int(ctx, 4); + + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 5, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); if (type > 1) { @@ -2304,48 +2668,55 @@ static int CmdHF14ADesReadData(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - swap24(aid); swap24(filesize); swap24(offset); - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } - mfdes_data_t ft; memcpy(ft.offset, offset, 3); memcpy(ft.length, filesize, 3); ft.fileno = _fileno[0]; - uint32_t bytestoread = le24toh(filesize); + uint32_t bytestoread = (uint32_t)le24toh(filesize); bytestoread &= 0xFFFFFF; if (bytestoread == 0) bytestoread = 0xFFFFFF; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + uint8_t cs = 0; + if (selectfile(aid, ft.fileno, &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; + } + uint8_t *data = (uint8_t *)calloc(bytestoread, sizeof(uint8_t)); + int res = PM3_ESOFT; if (data != NULL) { ft.data = data; - res = handler_desfire_readdata(&ft, type); + res = handler_desfire_readdata(&ft, type, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully read data from file %d:", ft.fileno); PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); + uint32_t len = le24toh(ft.length); for (uint32_t i = 0; i < len; i += 16) { - PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&ft.data[i], len > 16 ? 16 : len), sprint_ascii(&ft.data[i], len > 16 ? 16 : len)); + uint32_t l = len - i; + PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", i, i, sprint_hex(&ft.data[i], l > 16 ? 16 : l), sprint_ascii(&ft.data[i], l > 16 ? 16 : l)); } } else { PrintAndLogEx(ERR, "Couldn't read data. Error %d", res); + DropField(); + return res; } free(data); } @@ -2358,37 +2729,38 @@ static int CmdHF14ADesChangeValue(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes changevalue", "Change value (credit/limitedcredit/debit)", "Usage:" - "\n\thf mfdes changevalue -a 123456 -n 03 -m 0 -d 00000001\n" + "\n\thf mfdes changevalue -n 03 -m 0 -d 00000001\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("dD", "value", "", "Value to increase (4 hex bytes, big endian)"), arg_int0("mM", "mode", "", "Mode (0=Credit, 1=LimitedCredit, 2=Debit)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian)"), arg_param_end }; mfdes_value_t value; CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); - int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); value.fileno = _fileno[0]; int vlength = 0x0; - CLIGetHexWithReturn(ctx, 3, value.value, &vlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), value.value, 4, &vlength); - int mode = arg_get_int(ctx, 4); - CLIParserFree(ctx); + int mode = arg_get_int(ctx, 3); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 4, aid, &aidlength); swap24(aid); + CLIParserFree(ctx); + if (mode > 2) { PrintAndLogEx(ERR, "Invalid mode (0=Credit, 1=LimitedCredit, 2=Debit)."); return PM3_EINVARG; @@ -2410,25 +2782,30 @@ static int CmdHF14ADesChangeValue(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + uint8_t cs = 0; + if (selectfile(aid, _fileno[0], &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; } - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } + int res = PM3_ESOFT; if (mode == 0) { - res = handler_desfire_credit(&value); + res = handler_desfire_credit(&value, cs); } else if (mode == 1) { - res = handler_desfire_limitedcredit(&value); + res = handler_desfire_limitedcredit(&value, cs); } else if (mode == 2) { - res = handler_desfire_debit(&value); + res = handler_desfire_debit(&value, cs); } if (res == PM3_SUCCESS) { @@ -2451,32 +2828,29 @@ static int CmdHF14ADesWriteData(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes writedata", "Write data to File", "Usage:" - "\n\thf mfdes writedata -a 123456 -n 01 -t 0 -o 000000 -d 3132333435363738\n" + "\n\thf mfdes writedata -n 01 -t 0 -o 000000 -d 3132333435363738\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("oO", "offset", "", "File Offset (3 hex bytes, big endian), optional"), arg_strx0("dD", "data", "", "Data to write (hex bytes, 0xFFFF bytes max.)"), arg_int0("type", "type", "", "File Type (0=Standard/Backup, 1=Record)"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian, optional)"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); - int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int offsetlength = 0; uint8_t offset[3] = {0}; - CLIGetHexWithReturn(ctx, 3, offset, &offsetlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), offset, 3, &offsetlength); int dlength = 0xFFFF; uint8_t *data = (uint8_t *)calloc(dlength, sizeof(uint8_t)); @@ -2485,17 +2859,16 @@ static int CmdHF14ADesWriteData(const char *Cmd) { CLIParserFree(ctx); return PM3_EMALLOC; } - if (CLIParamHexToBuf(arg_get_str(ctx, 4), data, dlength, &dlength)) { - free(data); - CLIParserFree(ctx); - return PM3_ESOFT; - } + CLIParamHexToBuf(arg_get_str(ctx, 3), data, 0xFFFF, &dlength); - int type = arg_get_int(ctx, 5); + int type = arg_get_int(ctx, 4); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 5, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); - swap24(aid); swap24(offset); if (type < 0 || type > 1) { @@ -2528,30 +2901,32 @@ static int CmdHF14ADesWriteData(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - if (data) free(data); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid"); - DropField(); - if (data) free(data); - return res; - } - mfdes_data_t ft; memcpy(ft.offset, offset, 3); htole24(dlength, ft.length); ft.fileno = _fileno[0]; + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + uint8_t cs = 0; + if (selectfile(aid, _fileno[0], &cs) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting file.")); + return PM3_ESOFT; + } + + int res = PM3_ESOFT; if (data != NULL) { ft.data = data; - res = handler_desfire_writedata(&ft, type); + res = handler_desfire_writedata(&ft, type, cs); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully wrote data"); } else { @@ -2569,51 +2944,52 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes createrecordfile", "Create Linear/Cyclic Record File", "Usage:" - "\n\thf mfdes createrecordfile -a 123456 -f 1122 -n 02 -c 0 -r EEEE -s 000010 -m 000005\n" + "\n\thf mfdes createrecordfile -f 1122 -n 02 -c 0 -r EEEE -s 000010 -m 000005 -a 123456\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_strx0("fF", "fileid", "", "ISO FID (2 hex bytes, big endian)"), arg_int0("cC", "com.set", "", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"), - arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"), + arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> RW/Chg/R/W, 0-D Key, E Free, F Denied)"), arg_strx0("sS", "recordsize", "", "Record size (3 hex bytes, big endian, 000001 to FFFFFF)"), arg_strx0("mM", "maxnumrecord", "", "Max. Number of Records (3 hex bytes, big endian)"), arg_lit0("bB", "cyclic", "Create cyclic record file instead of linear record file"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); int fidlength = 0; uint8_t fid[2] = {0}; - CLIGetHexWithReturn(ctx, 3, fid, &fidlength); + CLIParamHexToBuf(arg_get_str(ctx, 2), fid, 2, &fidlength); - uint8_t comset = arg_get_int(ctx, 4); + uint8_t comset = arg_get_int(ctx, 3); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(ctx, 5, ar, &arlength); + CLIGetHexWithReturn(ctx, 4, ar, &arlength); int rsizelen = 0; uint8_t recordsize[3] = {0}; - CLIGetHexWithReturn(ctx, 6, recordsize, &rsizelen); + CLIGetHexWithReturn(ctx, 5, recordsize, &rsizelen); int msizelen = 0; uint8_t maxnumrecords[3] = {0}; - CLIGetHexWithReturn(ctx, 7, maxnumrecords, &msizelen); + CLIGetHexWithReturn(ctx, 6, maxnumrecords, &msizelen); - bool cyclic = arg_get_lit(ctx, 8); + bool cyclic = arg_get_lit(ctx, 7); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 8, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); - swap24(aid); swap16(fid); swap24(recordsize); swap24(maxnumrecords); @@ -2658,19 +3034,6 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } - mfdes_linear_t ft; ft.fileno = _fileno[0]; @@ -2680,6 +3043,22 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { memcpy(ft.recordsize, recordsize, 3); memcpy(ft.maxnumrecords, maxnumrecords, 3); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + if (handler_desfire_select_application(aid) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting aid.")); + return PM3_ESOFT; + } + + int res = PM3_SUCCESS; if (cyclic) { res = handler_desfire_create_cyclicrecordfile(&ft); } else { @@ -2700,54 +3079,54 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { CLIParserInit(&ctx, "hf mfdes createvaluefile", "Create Value File", "Usage:" - "\n\thf mfdes createvaluefile -a 123456 -n 03 -c 0 -r EEEE -l 00000000 -u 00002000 -v 00000001 -m 02\n" + "\n\thf mfdes createvaluefile -n 03 -c 0 -r EEEE -l 00000000 -u 00002000 -v 00000001 -m 02 -a 123456\n" + "Make sure to select aid or authenticate aid before running this command.\n" ); void *argtable[] = { arg_param_begin, - arg_strx0("aA", "aid", "", "AID for file (3 hex bytes, big endian)"), arg_strx0("nN", "fileno", "", "File Number (1 hex byte, 0x00 - 0x1F)"), arg_int0("cC", "com.set", "", "Communication setting (0=Plain,1=Plain+MAC,3=Enciphered)"), - arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> R/W/RW/Chg, 0-D Key, E Free, F Denied)"), + arg_strx0("rR", "accessrights", "", "Access rights (2 hex bytes -> RW/Chg/R/W, 0-D Key, E Free, F Denied)"), arg_strx0("lL", "lowerlimit", "", "Lower limit (4 hex bytes, big endian)"), arg_strx0("uU", "upperlimit", "", "Upper limit (4 hex bytes, big endian)"), arg_strx0("vV", "value", "", "Value (4 hex bytes, big endian)"), arg_strx0("mM", "limitcredit", "", "Limited Credit enabled (1 hex byte [Bit 0=LimitedCredit, 1=FreeValue])"), + arg_strx0("aA", "aid", "", "App ID to select as hex bytes (3 bytes,big endian,optional)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - int aidlength = 0; - uint8_t aid[3] = {0}; - CLIGetHexWithReturn(ctx, 1, aid, &aidlength); + CLIExecWithReturn(ctx, Cmd, argtable, false); int filenolen = 0; uint8_t _fileno[1] = {0}; - CLIGetHexWithReturn(ctx, 2, _fileno, &filenolen); + CLIGetHexWithReturn(ctx, 1, _fileno, &filenolen); - uint8_t comset = arg_get_int(ctx, 3); + uint8_t comset = arg_get_int(ctx, 2); int arlength = 0; uint8_t ar[2] = {0}; - CLIGetHexWithReturn(ctx, 4, ar, &arlength); + CLIGetHexWithReturn(ctx, 3, ar, &arlength); int lllen = 0; uint8_t lowerlimit[4] = {0}; - CLIGetHexWithReturn(ctx, 5, lowerlimit, &lllen); + CLIGetHexWithReturn(ctx, 4, lowerlimit, &lllen); int ullen = 0; uint8_t upperlimit[4] = {0}; - CLIGetHexWithReturn(ctx, 6, upperlimit, &ullen); + CLIGetHexWithReturn(ctx, 5, upperlimit, &ullen); int vllen = 0; uint8_t value[4] = {0}; - CLIGetHexWithReturn(ctx, 7, value, &vllen); + CLIGetHexWithReturn(ctx, 6, value, &vllen); int limitedlen = 0; uint8_t limited[1] = {0}; - CLIGetHexWithReturn(ctx, 8, limited, &limitedlen); - + CLIGetHexWithReturn(ctx, 7, limited, &limitedlen); + int aidlength = 3; + uint8_t aid[3] = {0}; + CLIGetHexWithReturn(ctx, 8, aid, &aidlength); + swap24(aid); CLIParserFree(ctx); - swap24(aid); swap32(lowerlimit); swap32(upperlimit); swap32(value); @@ -2791,18 +3170,6 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { PrintAndLogEx(WARNING, "Limited Credit Enabled must have 1 hex byte"); return PM3_EINVARG; } - // AID - if (aidlength != 3) { - PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); - return PM3_EINVARG; - } - - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "Couldn't select aid."); - DropField(); - return res; - } mfdes_value_file_t ft; @@ -2814,7 +3181,23 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { memcpy(ft.value, value, 4); ft.limitedcreditenabled = limited[0]; - res = handler_desfire_create_value_file(&ft); + if (aidlength != 3 && aidlength != 0) { + PrintAndLogEx(ERR, _RED_(" The given aid must have 3 bytes (big endian).")); + return PM3_ESOFT; + } else if (aidlength == 0) { + if (memcmp(&tag->selected_application, aid, 3) == 0) { + PrintAndLogEx(ERR, _RED_(" You need to select an aid first.")); + return PM3_ESOFT; + } + memcpy(aid, (uint8_t *)&tag->selected_application, 3); + } + + if (handler_desfire_select_application(aid) != PM3_SUCCESS) { + PrintAndLogEx(ERR, _RED_(" Error on selecting aid.")); + return PM3_ESOFT; + } + + int res = handler_desfire_create_value_file(&ft); if (res == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "Successfully created value file."); } else { @@ -2828,78 +3211,22 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "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" + "Usage:" + "\n\thf mfdes formatpicc\n" + "Make sure to authenticate picc before running this command.\n" ); - void *argtable[] = { - arg_param_begin, - arg_str0("kK", "key", "", "Key for checking (HEX 16 bytes)"), - arg_param_end - }; - CLIExecWithReturn(ctx, Cmd, argtable, false); - - uint8_t key[8] = {0}; - int keylen = 8; - CLIGetHexWithReturn(ctx, 1, key, &keylen); - CLIParserFree(ctx); - - if ((keylen < 8) || (keylen > 8)) { - PrintAndLogEx(ERR, "Specified key must have 8 bytes length"); - return PM3_EINVARG; - } - - DropField(); - uint8_t aid[3] = {0}; - int res = handler_desfire_select_application(aid); - if (res != PM3_SUCCESS) return res; - - mfdes_authinput_t payload; - payload.keylen = keylen; - memcpy(payload.key, key, keylen); - payload.mode = MFDES_AUTH_PICC; - payload.algo = MFDES_ALGO_DES; - payload.keyno = 0; - - SendCommandNG(CMD_HF_DESFIRE_AUTH1, (uint8_t *)&payload, sizeof(payload)); - PacketResponseNG resp; - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client command execute timeout"); + sAPDU apdu = {0x90, MFDES_FORMAT_PICC, 0x00, 0x00, 0, NULL}; // 0xDF + uint16_t sw = 0; + uint32_t recvlen = 0; + int res = send_desfire_cmd(&apdu, false, NULL, &recvlen, &sw, 0, true); + if (res != PM3_SUCCESS) { + PrintAndLogEx(WARNING, _RED_(" Can't format picc -> %s"), GetErrorString(res, &sw)); DropField(); - return PM3_ETIMEOUT; - } - - uint8_t isOK = (resp.status == PM3_SUCCESS); - if (isOK) { - struct { - uint8_t flags; - uint8_t datalen; - uint8_t datain[FRAME_PAYLOAD_SIZE]; - } PACKED payload_raw; - - payload_raw.datain[0] = 0xFC; - payload_raw.flags = NONE; - payload_raw.datalen = 1; - - SendCommandNG(CMD_HF_DESFIRE_COMMAND, (uint8_t *)&payload_raw, sizeof(payload_raw)); - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_COMMAND, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client reset command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - if (resp.status == PM3_SUCCESS) { - /*struct r { - uint8_t len; - uint8_t data[RECEIVE_SIZE]; - } PACKED; - struct r *rpayload = (struct r *)&resp.data.asBytes;*/ - PrintAndLogEx(INFO, "Card successfully reset"); - return PM3_SUCCESS; - } + return res; } else { - PrintAndLogEx(WARNING, _RED_("Auth command failed")); + PrintAndLogEx(INFO, "Card successfully reset"); + return PM3_SUCCESS; } DropField(); return PM3_SUCCESS; @@ -3163,9 +3490,9 @@ static int DecodeFileSettings(uint8_t *src, int src_len, int maclen) { PrintAndLogEx(INFO, " Lower limit: %d (0x%X) - Upper limit: %d (0x%X) - limited credit value: %d (0x%X) - limited credit enabled: %d", lowerlimit, lowerlimit, upperlimit, upperlimit, limitcredvalue, limitcredvalue, limited_credit_enabled); return PM3_SUCCESS; } else if (src_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) { - int recordsize = (src[6] << 16) + (src[5] << 8) + src[4]; - int maxrecords = (src[9] << 16) + (src[8] << 8) + src[7]; - int currentrecord = (src[12] << 16) + (src[11] << 8) + src[10]; + uint32_t recordsize = (src[6] << 16) + (src[5] << 8) + src[4]; + uint32_t maxrecords = (src[9] << 16) + (src[8] << 8) + src[7]; + uint32_t currentrecord = (src[12] << 16) + (src[11] << 8) + src[10]; DecodeFileType(filetype); DecodeComSet(comset); DecodeAccessRights(accrights); @@ -3181,10 +3508,10 @@ static int CmdHF14ADesDump(const char *Cmd) { uint8_t aid[3] = {0}; uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; + uint32_t app_ids_len = 0; uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; dfname_t dfnames[255]; uint8_t dfname_count = 0; @@ -3205,7 +3532,7 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(INFO, "-- Mifare DESFire Dump ----------------------"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); - for (int i = 0; i < app_ids_len; i += 3) { + for (uint32_t i = 0; i < app_ids_len; i += 3) { aid[0] = app_ids[i]; aid[1] = app_ids[i + 1]; @@ -3214,7 +3541,7 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X%02X%02X"), aid[2], aid[1], aid[0]); PrintAndLogEx(SUCCESS, " AID Function Cluster 0x%02X: " _YELLOW_("%s"), aid[2], cluster_to_text(aid[2])); - for (int m = 0; m < dfname_count; m++) { + for (uint8_t m = 0; m < dfname_count; m++) { if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X%02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[1], dfnames[m].fid[0], dfnames[m].name); } @@ -3222,7 +3549,7 @@ static int CmdHF14ADesDump(const char *Cmd) { uint8_t num_keys = 0; uint8_t key_setting = 0; - res = handler_desfire_keysettings(&key_setting, &num_keys); + res = handler_desfire_getkeysettings(&key_setting, &num_keys); if (res != PM3_SUCCESS) continue; res = handler_desfire_select_application(aid); @@ -3231,11 +3558,11 @@ static int CmdHF14ADesDump(const char *Cmd) { res = handler_desfire_fileids(file_ids, &file_ids_len); if (res != PM3_SUCCESS) continue; - for (int j = file_ids_len - 1; j >= 0; j--) { + for (int j = (int)file_ids_len - 1; j >= 0; j--) { PrintAndLogEx(SUCCESS, "\n\n Fileid %d (0x%02x)", file_ids[j], file_ids[j]); uint8_t filesettings[20] = {0}; - int fileset_len = 0; + uint32_t fileset_len = 0; res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len); if (res != PM3_SUCCESS) continue; @@ -3256,7 +3583,7 @@ static int CmdHF14ADesDump(const char *Cmd) { } fdata.data = data; - res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE); + res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3276,12 +3603,12 @@ static int CmdHF14ADesDump(const char *Cmd) { PrintAndLogEx(NORMAL, "\n\nValue file: 0x%0x", file_ids[j]); mfdes_value_t value; value.fileno = file_ids[j]; - int len = 0; - res = handler_desfire_getvalue(&value, &len); + uint32_t len = 0; + res = handler_desfire_getvalue(&value, &len, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); - for (int n = 0; n < len; n += 16) { + for (uint32_t n = 0; n < len; n += 16) { PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&value.value[n], len > 16 ? 16 : len), sprint_ascii(&value.value[n], len > 16 ? 16 : len)); } } else { @@ -3291,8 +3618,8 @@ static int CmdHF14ADesDump(const char *Cmd) { } } else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) { - int maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7]; - int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4]; + uint32_t maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7]; + uint32_t filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4]; mfdes_data_t fdata; fdata.fileno = file_ids[j]; memset(fdata.length, 0, 3); @@ -3303,13 +3630,13 @@ static int CmdHF14ADesDump(const char *Cmd) { } fdata.data = data; - for (int offset = 0; offset < maxrecords; offset++) { + for (uint32_t offset = 0; offset < maxrecords; offset++) { PrintAndLogEx(NORMAL, "\n\nRecord offset: %024x", offset); memset(data, 0, filesize); fdata.offset[0] = offset & 0xFF; fdata.offset[1] = (offset >> 8) & 0xFF; fdata.offset[2] = (offset >> 16) & 0xFF; - res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE); + res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE, filesettings[1]); if (res == PM3_SUCCESS) { PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii"); PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------"); @@ -3339,10 +3666,10 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { uint8_t aid[3] = {0}; uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; + uint32_t app_ids_len = 0; uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; dfname_t dfnames[255]; uint8_t dfname_count = 0; @@ -3362,7 +3689,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { PrintAndLogEx(INFO, "-------------------------------------------------------------"); PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") " application%c", app_ids_len / 3, (app_ids_len == 3) ? ' ' : 's'); - for (int i = 0; i < app_ids_len; i += 3) { + for (uint32_t i = 0; i < app_ids_len; i += 3) { aid[0] = app_ids[i]; aid[1] = app_ids[i + 1]; @@ -3380,7 +3707,7 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { PrintAndLogEx(SUCCESS, " AID : " _GREEN_("%02X%02X%02X"), aid[2], aid[1], aid[0]); PrintAndLogEx(SUCCESS, " AID Function Cluster 0x%02X: " _YELLOW_("%s"), aid[2], cluster_to_text(aid[2])); - for (int m = 0; m < dfname_count; m++) { + for (uint8_t m = 0; m < dfname_count; m++) { if (dfnames[m].aid[0] == aid[0] && dfnames[m].aid[1] == aid[1] && dfnames[m].aid[2] == aid[2]) { PrintAndLogEx(SUCCESS, " - DF " _YELLOW_("%02X%02X") " Name : " _YELLOW_("%s"), dfnames[m].fid[1], dfnames[m].fid[0], dfnames[m].name); } @@ -3396,12 +3723,12 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { if (res != PM3_SUCCESS) continue; PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") " file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's'); - for (int j = file_ids_len - 1; j >= 0; j--) { + for (int j = (int)file_ids_len - 1; j >= 0; j--) { PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]); uint8_t filesettings[20] = {0}; - int fileset_len = 0; - int maclen = 0; // To be implemented + uint32_t fileset_len = 0; + uint32_t maclen = 0; // To be implemented res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len); if (res != PM3_SUCCESS) continue; @@ -3417,12 +3744,104 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) { return PM3_SUCCESS; } -// MIAFRE DESFire Authentication -// -#define BUFSIZE 256 -static int CmdHF14ADesAuth(const char *Cmd) { - int res = 0; - DropField(); +static int CmdHF14ADesChangeKey(const char *Cmd) { + //DropField(); + // NR DESC KEYLENGHT + // ------------------------ + // 1 = DES 8 + // 2 = 3DES 16 + // 3 = 3K 3DES 24 + // 4 = AES 16 + uint8_t keylength = 8; + uint8_t newkeylength = 8; + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfdes changekey", + "Changes Mifare DESFire Key", + "Usage:" + "\n\thf mfdes changekey -n 0 -t 1 -k 0000000000000000 -u 1 -j 0102030405060708 (DES,keynumber 0)\n" + "Make sure to select aid or authenticate aid before running this command.\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("nN", "keyno", "", "Key number used for authentification"), + arg_int0("tT", "algo", "", "Current key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), + arg_str0("kK", "key", "", "Current Key (HEX 8-24 bytes)"), + arg_int0("uU", "newalgo", "", "New key algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), + arg_str0("jJ", "newkey", "", "New Key (HEX 8-24 bytes)"), + arg_int0("vV", "aesversion", "", "Aes version (if aes is used)"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + uint8_t cmdKeyNo = arg_get_int_def(ctx, 1, 0); + uint8_t cmdAuthAlgo = arg_get_int_def(ctx, 2, 0); + uint8_t key[24] = {0}; + int keylen = 0; + CLIParamHexToBuf(arg_get_str(ctx, 3), key, 24, &keylen); + uint8_t newcmdAuthAlgo = arg_get_int_def(ctx, 4, 0); + uint8_t newkey[24] = {0}; + int newkeylen = 0; + CLIParamHexToBuf(arg_get_str(ctx, 5), newkey, 24, &newkeylen); + uint8_t aesversion = arg_get_int_def(ctx, 6, 0); + CLIParserFree(ctx); + + if (cmdAuthAlgo == MFDES_ALGO_AES) { + keylength = 16; + } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { + keylength = 16; + } else if (cmdAuthAlgo == MFDES_ALGO_DES) { + keylength = 8; + } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + keylength = 24; + } + + if (newcmdAuthAlgo == MFDES_ALGO_AES) { + newkeylength = 16; + } else if (newcmdAuthAlgo == MFDES_ALGO_3DES) { + newkeylength = 16; + } else if (newcmdAuthAlgo == MFDES_ALGO_DES) { + newkeylength = 8; + } else if (newcmdAuthAlgo == MFDES_ALGO_3K3DES) { + newkeylength = 24; + } + + if ((keylen < 8) || (keylen > 24)) { + PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); + return PM3_EINVARG; + } + + if ((newkeylen < 8) || (newkeylen > 24)) { + PrintAndLogEx(ERR, "Specified key must have %d bytes length.", newkeylen); + return PM3_EINVARG; + } + + if (keylen != keylength) { + PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + + if (newkeylen != newkeylength) { + PrintAndLogEx(WARNING, "New key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + + int error = mifare_desfire_change_key(cmdKeyNo, newkey, newcmdAuthAlgo, key, cmdAuthAlgo, aesversion); + if (error == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, " Successfully changed key."); + } else { + PrintAndLogEx(SUCCESS, " Error on changing key."); + return PM3_ESOFT; + } + return PM3_SUCCESS; +} + + +// MIAFRE DESFire Authentication +// +#define BUFSIZE 256 +static int CmdHF14ADesAuth(const char *Cmd) { + //DropField(); // NR DESC KEYLENGHT // ------------------------ // 1 = DES 8 @@ -3430,21 +3849,24 @@ static int CmdHF14ADesAuth(const char *Cmd) { // 3 = 3K 3DES 24 // 4 = AES 16 uint8_t keylength = 8; - bool usedefaultkey = false; CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes auth", "Authenticates Mifare DESFire using Key", "Usage:" - "\n\thf mfdes auth -m 3 -t 4 -a 808301 -n 0 -k 00000000000000000000000000000000 (AES)" - "\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 0 -k 00000000000000000000000000000000 (3DES)" - "\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 0 -k 0000000000000000 (DES)" + "\n\thf mfdes auth -m 3 -t 4 -a 808301 -n 0 -k 00000000000000000000000000000000 (AES,keynumber 0, aid 0x803201)" + "\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 1 -k 00000000000000000000000000000000 (3DES,keynumber 1, aid 0x000000)" + "\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 2 -k 0000000000000000 (DES,keynumber 2, aid 0x000000)" + "\n\thf mfdes auth -m 1 -t 1 -a 000000 -n 0 (DES, defaultkey, aid 0x000000)" + "\n\thf mfdes auth -m 2 -t 2 -a 000000 -n 0 (3DES, defaultkey, aid 0x000000)" + "\n\thf mfdes auth -m 3 -t 4 -a 000000 -n 0 (3K3DES, defaultkey, aid 0x000000)" + "\n\thf mfdes auth -m 3 -t 4 -a 000000 -n 0 (AES, defaultkey, aid 0x000000)" ); void *argtable[] = { arg_param_begin, - arg_int0("mM", "type", "", "Auth type (1=normal, 2=iso, 3=aes, 4=picc)"), - arg_int0("tT", "algo", "", "Crypt algo (1=DES, 2=3DES(2K2DES), 4=3K3DES, 5=AES)"), + arg_int0("mM", "type", "", "Auth type (1=normal, 2=iso, 3=aes)"), + arg_int0("tT", "algo", "", "Crypt algo (1=DES, 2=3DES(2K2DES), 3=3K3DES, 4=AES)"), arg_strx0("aA", "aid", "", "AID used for authentification (HEX 3 bytes)"), arg_int0("nN", "keyno", "", "Key number used for authentification"), arg_str0("kK", "key", "", "Key for checking (HEX 8-24 bytes)"), @@ -3466,104 +3888,50 @@ static int CmdHF14ADesAuth(const char *Cmd) { CLIGetHexWithReturn(ctx, 5, key, &keylen); CLIParserFree(ctx); - if (keylen == 0) { - usedefaultkey = true; - } else if ((keylen < 8) || (keylen > 24)) { + if (cmdAuthAlgo == MFDES_ALGO_AES) { + if (keylen == 0) { + keylen = 16; + memcpy(key, aesdefaultkeys[0], keylen); + } + keylength = 16; + } else if (cmdAuthAlgo == MFDES_ALGO_3DES) { + if (keylen == 0) { + keylen = 16; + memcpy(key, aesdefaultkeys[0], keylen); + } + keylength = 16; + } else if (cmdAuthAlgo == MFDES_ALGO_DES) { + if (keylen == 0) { + keylen = 8; + memcpy(key, desdefaultkeys[0], keylen); + } + keylength = 8; + } else if (cmdAuthAlgo == MFDES_ALGO_3K3DES) { + if (keylen == 0) { + keylen = 24; + memcpy(key, k3kdefaultkeys[0], keylen); + } + keylength = 24; + } + + if ((keylen < 8) || (keylen > 24)) { PrintAndLogEx(ERR, "Specified key must have %d bytes length.", keylen); return PM3_EINVARG; } + if (keylen != keylength) { + PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); + return PM3_EINVARG; + } + // AID if (aidlength != 3) { PrintAndLogEx(WARNING, "aid must include %d HEX symbols", 3); return PM3_EINVARG; } - switch (cmdAuthMode) { - case MFDES_AUTH_DES: - if (cmdAuthAlgo != MFDES_ALGO_DES && cmdAuthAlgo != MFDES_ALGO_3DES) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth des mode"); - return PM3_EINVARG; - } - break; - case MFDES_AUTH_ISO: - if (cmdAuthAlgo != MFDES_ALGO_3DES && cmdAuthAlgo != MFDES_ALGO_3K3DES) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth iso mode"); - return PM3_EINVARG; - } - break; - case MFDES_AUTH_AES: - if (cmdAuthAlgo != MFDES_ALGO_AES) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth aes mode"); - return PM3_EINVARG; - } - break; - case MFDES_AUTH_PICC: - if (cmdAuthAlgo != MFDES_AUTH_DES) { - PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth picc mode"); - return PM3_EINVARG; - } - break; - default: - PrintAndLogEx(WARNING, "Wrong Auth mode (%d) -> (1=normal, 2=iso, 3=aes)", cmdAuthMode); - return PM3_EINVARG; - } - - switch (cmdAuthAlgo) { - case MFDES_ALGO_3DES: - keylength = 16; - PrintAndLogEx(NORMAL, "2 key 3DES selected"); - break; - case MFDES_ALGO_3K3DES: - keylength = 24; - PrintAndLogEx(NORMAL, "3 key 3DES selected"); - break; - case MFDES_ALGO_AES: - keylength = 16; - PrintAndLogEx(NORMAL, "AES selected"); - break; - default: - cmdAuthAlgo = MFDES_ALGO_DES; - keylength = 8; - PrintAndLogEx(NORMAL, "DES selected"); - break; - } - - // KEY - if (keylen != keylength) { - PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); - return PM3_EINVARG; - } - - - res = handler_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 = handler_desfire_fileids(file_ids, &file_ids_len); - if (res != PM3_SUCCESS) return res; - } - - mfdes_authinput_t payload; - payload.keylen = keylength; - memcpy(payload.key, key, keylength); - payload.mode = cmdAuthMode; - payload.algo = cmdAuthAlgo; - payload.keyno = cmdKeyNo; - /*SendCommandNG(CMD_HF_DESFIRE_AUTH1, (uint8_t *)&payload, sizeof(payload)); - - PacketResponseNG resp; - - if (!WaitForResponseTimeout(CMD_HF_DESFIRE_AUTH1, &resp, 3000)) { - PrintAndLogEx(WARNING, "Client command execute timeout"); - DropField(); - return PM3_ETIMEOUT; - } - */ mfdes_auth_res_t rpayload; - int error = handler_desfire_auth(&payload, &rpayload, usedefaultkey); + int error = desfire_authenticate(cmdAuthMode, cmdAuthAlgo, aid, key, cmdKeyNo, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, " Key : " _GREEN_("%s"), sprint_hex(key, keylength)); PrintAndLogEx(SUCCESS, " SESSION : " _GREEN_("%s"), sprint_hex(rpayload.sessionkey, keylength)); @@ -3639,23 +4007,23 @@ static int AuthCheckDesfire(uint8_t *aid, if (memcmp(aid, "\x00\x00\x00", 3) != 0) { uint8_t file_ids[33] = {0}; - uint8_t file_ids_len = 0; + uint32_t file_ids_len = 0; // Get File IDs if (handler_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) { - for (int j = file_ids_len - 1; j >= 0; j--) { + for (int j = (int)file_ids_len - 1; j >= 0; j--) { uint8_t filesettings[20] = {0}; - int fileset_len = 0; + uint32_t fileset_len = 0; res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len); if (res == PM3_SUCCESS) { uint16_t accrights = (filesettings[3] << 8) + filesettings[2]; - 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; + uint8_t change_access_rights = accrights & 0xF; + uint8_t read_write_access = (accrights >> 4) & 0xF; + uint8_t write_access = (accrights >> 8) & 0xF; + uint8_t read_access = (accrights >> 12) & 0xF; if (change_access_rights == 0xE) change_access_rights = 0x0; if (read_write_access == 0xE) read_write_access = 0x0; @@ -3687,7 +4055,7 @@ static int AuthCheckDesfire(uint8_t *aid, } if (file_ids_len == 0) { - for (int z = 0; z < 0xE; z++) { + for (uint8_t z = 0; z < 0xE; z++) { usedkeys[z] = 1; des = true; tdes = true; @@ -3703,24 +4071,14 @@ static int AuthCheckDesfire(uint8_t *aid, int error = PM3_SUCCESS; bool badlen = false; - mfdes_authinput_t payload; - mfdes_auth_res_t payload_res; - if (des) { for (uint8_t keyno = 0; keyno < 0xE; keyno++) { if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < deskeyListLen; curkey++) { - - payload.keylen = 8; - memcpy(payload.key, deskeyList[curkey], 8); - payload.mode = MFDES_AUTH_DES; - payload.algo = MFDES_ALGO_DES; - payload.keyno = keyno; - - error = handler_desfire_auth(&payload, &payload_res, false); + mfdes_auth_res_t rpayload; + error = desfire_authenticate(MFDES_AUTH_DES, MFDES_ALGO_DES, aid, deskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8)); foundKeys[0][keyno][0] = 0x01; @@ -3750,16 +4108,9 @@ static int AuthCheckDesfire(uint8_t *aid, for (uint8_t keyno = 0; keyno < 0xE; keyno++) { if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - - payload.keylen = 16; - memcpy(payload.key, aeskeyList[curkey], 16); - payload.mode = MFDES_AUTH_DES; - payload.algo = MFDES_ALGO_3DES; - payload.keyno = keyno; - - error = handler_desfire_auth(&payload, &payload_res, false); + mfdes_auth_res_t rpayload; + error = desfire_authenticate(MFDES_AUTH_DES, MFDES_ALGO_3DES, aid, aeskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3DES Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16)); foundKeys[1][keyno][0] = 0x01; @@ -3789,16 +4140,9 @@ static int AuthCheckDesfire(uint8_t *aid, for (uint8_t keyno = 0; keyno < 0xE; keyno++) { if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - - payload.keylen = 16; - memcpy(payload.key, aeskeyList[curkey], 16); - payload.mode = MFDES_AUTH_AES; - payload.algo = MFDES_ALGO_AES; - payload.keyno = keyno; - - error = handler_desfire_auth(&payload, &payload_res, false); + mfdes_auth_res_t rpayload; + error = desfire_authenticate(MFDES_AUTH_AES, MFDES_ALGO_AES, aid, aeskeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16)); foundKeys[2][keyno][0] = 0x01; @@ -3828,15 +4172,9 @@ static int AuthCheckDesfire(uint8_t *aid, for (uint8_t keyno = 0; keyno < 0xE; keyno++) { if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < k3kkeyListLen; curkey++) { - payload.keylen = 24; - memcpy(payload.key, k3kkeyList[curkey], 24); - payload.mode = MFDES_AUTH_ISO; - payload.algo = MFDES_ALGO_3K3DES; - payload.keyno = keyno; - - error = handler_desfire_auth(&payload, &payload_res, false); + mfdes_auth_res_t rpayload; + error = desfire_authenticate(MFDES_AUTH_ISO, MFDES_ALGO_3K3DES, aid, k3kkeyList[curkey], keyno, &rpayload); if (error == PM3_SUCCESS) { PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3K3 Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(k3kkeyList[curkey], 24)); foundKeys[3][keyno][0] = 0x01; @@ -3977,11 +4315,11 @@ static int CmdHF14aDesChk(const char *Cmd) { // 1-byte pattern search mode if (pattern1b) { - for (int i = 0; i < 0x100; i++) + for (uint32_t i = 0; i < 0x100; i++) memset(aeskeyList[i], i, 16); - for (int i = 0; i < 0x100; i++) + for (uint32_t i = 0; i < 0x100; i++) memset(deskeyList[i], i, 8); - for (int i = 0; i < 0x100; i++) + for (uint32_t i = 0; i < 0x100; i++) memset(k3kkeyList[i], i, 24); aeskeyListLen = 0x100; deskeyListLen = 0x100; @@ -4040,7 +4378,7 @@ static int CmdHF14aDesChk(const char *Cmd) { bool result = false; uint8_t app_ids[78] = {0}; - uint8_t app_ids_len = 0; + uint32_t app_ids_len = 0; if (handler_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); @@ -4053,7 +4391,7 @@ static int CmdHF14aDesChk(const char *Cmd) { app_ids_len = 1; } - for (int x = 0; x < app_ids_len / 3; x++) { + for (uint32_t x = 0; x < app_ids_len / 3; x++) { uint32_t curaid = (app_ids[x * 3] & 0xFF) + ((app_ids[(x * 3) + 1] & 0xFF) << 8) + ((app_ids[(x * 3) + 2] & 0xFF) << 16); PrintAndLogEx(ERR, "Checking aid 0x%06X...", curaid); res = AuthCheckDesfire(&app_ids[x * 3], deskeyList, deskeyListLen, aeskeyList, aeskeyListLen, k3kkeyList, k3kkeyListLen, foundKeys, &result); @@ -4164,6 +4502,8 @@ 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"}, + {"getuid", CmdHF14ADesGetUID, IfPm3Iso14443a, "Get random uid"}, + {"selectaid", CmdHF14ADesSelectApp, IfPm3Iso14443a, "Select Application ID"}, {"createaid", CmdHF14ADesCreateApp, IfPm3Iso14443a, "Create Application ID"}, {"deleteaid", CmdHF14ADesDeleteApp, IfPm3Iso14443a, "Delete Application ID"}, {"createfile", CmdHF14ADesCreateFile, IfPm3Iso14443a, "Create Standard/Backup File"}, @@ -4175,31 +4515,10 @@ static command_t CommandTable[] = { {"writedata", CmdHF14ADesWriteData, IfPm3Iso14443a, "Write data to standard/backup/record file"}, {"getvalue", CmdHF14ADesGetValueData, IfPm3Iso14443a, "Get value of file"}, {"changevalue", CmdHF14ADesChangeValue, IfPm3Iso14443a, "Write value of a value file (credit/debit/clear)"}, + {"changekey", CmdHF14ADesChangeKey, IfPm3Iso14443a, "Change Key"}, {"formatpicc", CmdHF14ADesFormatPICC, IfPm3Iso14443a, "Format PICC"}, {"dump", CmdHF14ADesDump, IfPm3Iso14443a, "Dump all files"}, {"chk", CmdHF14aDesChk, IfPm3Iso14443a, "Check keys"}, - /* - ToDo: - - Native Cmds - ChangeKeySettings - ChangeKey - SetConfiguration - GetISOFileIDs - GetCardUID - ChangeFileSettings - Handling CMAC/Encryption after authorization - - ISO/IEC 7816 Cmds - 'A4' Select - 'B0' Read Binary - 'D6' Update Binary - 'B2' Read Records - 'E2' Append Records - '84' Get Challenge - '88' Internal Authenticate - '82' External Authenticate - */ {NULL, NULL, NULL, NULL} }; @@ -4213,3 +4532,26 @@ int CmdHFMFDes(const char *Cmd) { clearCommandBuffer(); return CmdsParse(CommandTable, Cmd); } + +/* + ToDo: + + Native Cmds + ----------- + ChangeKeySettings 0x5F + SetConfiguration + GetISOFileIDs + GetCardUID + ChangeFileSettings + + ISO/IEC 7816 Cmds + ----------------- + 'A4' Select + 'B0' Read Binary + 'D6' Update Binary + 'B2' Read Records + 'E2' Append Records + '84' Get Challenge + '88' Internal Authenticate + '82' External Authenticate +*/ diff --git a/client/src/cmdmain.c b/client/src/cmdmain.c index 1e9c8d257..2664ed3a1 100644 --- a/client/src/cmdmain.c +++ b/client/src/cmdmain.c @@ -258,7 +258,7 @@ static command_t CommandTable[] = { {"lf", CmdLF, AlwaysAvailable, "{ Low frequency commands... }"}, {"mem", CmdFlashMem, IfPm3Flash, "{ Flash Memory manipulation... }"}, {"reveng", CmdRev, AlwaysAvailable, "{ CRC calculations from RevEng software }"}, - {"sc", CmdSmartcard, IfPm3Smartcard, "{ Smart card ISO-7816 commands... }"}, + {"sc", CmdSmartcard, AlwaysAvailable, "{ Smart card ISO-7816 commands... }"}, {"script", CmdScript, AlwaysAvailable, "{ Scripting commands }"}, {"trace", CmdTrace, AlwaysAvailable, "{ Trace manipulation... }"}, {"usart", CmdUsart, IfPm3FpcUsartFromUsb, "{ USART commands... }"}, diff --git a/client/src/cmdscript.c b/client/src/cmdscript.c index 24fd5ec37..4fb87cc27 100644 --- a/client/src/cmdscript.c +++ b/client/src/cmdscript.c @@ -19,7 +19,6 @@ #include #endif - #include "cmdparser.h" // command_t #include "scripting.h" #include "comms.h" @@ -33,6 +32,68 @@ #include "ui.h" #include "fileutils.h" +#ifdef HAVE_PYTHON +// Partly ripped from PyRun_SimpleFileExFlags +// but does not terminate client on sys.exit +// and print exit code only if != 0 +static int Pm3PyRun_SimpleFileNoExit(FILE *fp, const char *filename) +{ + PyObject *m, *d, *v; + int set_file_name = 0, ret = -1; + m = PyImport_AddModule("__main__"); + if (m == NULL) + return -1; + Py_INCREF(m); + d = PyModule_GetDict(m); + if (PyDict_GetItemString(d, "__file__") == NULL) { + PyObject *f; + f = PyUnicode_DecodeFSDefault(filename); + if (f == NULL) + goto done; + if (PyDict_SetItemString(d, "__file__", f) < 0) { + Py_DECREF(f); + goto done; + } + if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) { + Py_DECREF(f); + goto done; + } + set_file_name = 1; + Py_DECREF(f); + } + v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, 1, NULL); + if (v == NULL) { + Py_CLEAR(m); + if (PyErr_ExceptionMatches(PyExc_SystemExit)) { + // PyErr_Print() exists if SystemExit so we've to handle it ourselves + PyObject *ty = 0, *er = 0, *tr = 0; + PyErr_Fetch(&ty, &er, &tr); + long err = PyLong_AsLong(er); + if (err) { + PrintAndLogEx(WARNING, "\nScript terminated by " _YELLOW_("SystemExit %li"), err); + } else { + ret = 0; + } + Py_DECREF(ty); + Py_DECREF(er); + Py_DECREF(er); + PyErr_Clear(); + goto done; + } else { + PyErr_Print(); + } + goto done; + } + Py_DECREF(v); + ret = 0; + done: + if (set_file_name && PyDict_DelItemString(d, "__file__")) + PyErr_Clear(); + Py_XDECREF(m); + return ret; +} +#endif // HAVE_PYTHON + typedef enum { PM3_UNSPECIFIED, PM3_LUA, @@ -319,13 +380,17 @@ static int CmdScriptRun(const char *Cmd) { free(script_path); return PM3_ESOFT; } - - PyRun_SimpleFileExFlags(f, preferredName, 1, NULL); + int ret = Pm3PyRun_SimpleFileNoExit(f, preferredName); Py_Finalize(); PyMem_RawFree(program); free(script_path); - PrintAndLogEx(SUCCESS, "\nfinished " _YELLOW_("%s"), preferredName); - return PM3_SUCCESS; + if (ret) { + PrintAndLogEx(WARNING, "\nfinished " _YELLOW_("%s") " with exception", preferredName); + return PM3_ESOFT; + } else { + PrintAndLogEx(SUCCESS, "\nfinished " _YELLOW_("%s"), preferredName); + return PM3_SUCCESS; + } } #endif diff --git a/client/src/emv/cmdemv.c b/client/src/emv/cmdemv.c index 65c9cafb2..2f754ffc4 100644 --- a/client/src/emv/cmdemv.c +++ b/client/src/emv/cmdemv.c @@ -26,6 +26,7 @@ #include "dol.h" #include "ui.h" #include "emv_tags.h" +#include "fileutils.h" static int CmdHelp(const char *Cmd); @@ -1383,8 +1384,6 @@ static int CmdEMVScan(const char *Cmd) { size_t ODAI_listlen = 0; uint16_t sw = 0; int res; - json_t *root; - json_error_t error; CLIParserContext *ctx; CLIParserInit(&ctx, "emv scan", @@ -1426,15 +1425,19 @@ static int CmdEMVScan(const char *Cmd) { bool GenACGPO = arg_get_lit(ctx, 9); bool MergeJSON = arg_get_lit(ctx, 10); + EMVCommandChannel channel = ECC_CONTACTLESS; if (arg_get_lit(ctx, 11)) channel = ECC_CONTACT; + PrintChannel(channel); + uint8_t psenum = (channel == ECC_CONTACT) ? 1 : 2; - uint8_t relfname[250] = {0}; - char *crelfname = (char *)relfname; - int relfnamelen = 0; - CLIGetStrWithReturn(ctx, 12, relfname, &relfnamelen); + + uint8_t filename[FILE_PATH_SIZE] = {0}; + int filenamelen = 0; + CLIGetStrWithReturn(ctx, 12, filename, &filenamelen); + CLIParserFree(ctx); if (!IfPm3Smartcard()) { @@ -1446,16 +1449,13 @@ static int CmdEMVScan(const char *Cmd) { SetAPDULogging(showAPDU); + json_t *root; + json_error_t error; + // current path + file name - if (!strstr(crelfname, ".json")) - strcat(crelfname, ".json"); - - char fname[strlen(get_my_executable_directory()) + strlen(crelfname) + 1]; - strcpy(fname, get_my_executable_directory()); - strcat(fname, crelfname); - if (MergeJSON) { - root = json_load_file(fname, 0, &error); + + root = json_load_file( (char*)filename, 0, &error); if (!root) { PrintAndLogEx(ERR, "Json error on line %d: %s", error.line, error.text); return PM3_EFILE; @@ -1589,6 +1589,7 @@ static int CmdEMVScan(const char *Cmd) { JsonSaveTLVTree(root, root, "$.Application.FCITemplate", fci); else JsonSaveTLVTreeElm(root, "$.Application.FCITemplate", fci, true, true, false); + tlvdb_free(fci); // create transaction parameters @@ -1746,12 +1747,24 @@ static int CmdEMVScan(const char *Cmd) { DropFieldEx(channel); - res = json_dump_file(root, fname, JSON_INDENT(2)); + + if (MergeJSON == false) { + // create unique new name + char *fname = newfilenamemcopy((char*)filename, ".json"); + if (fname == NULL) { + return PM3_EMALLOC; + } + strcpy((char*)filename, fname); + free(fname); + } + + res = json_dump_file(root, (char*)filename, JSON_INDENT(2)); if (res) { - PrintAndLogEx(ERR, "Can't save the file: %s", fname); + PrintAndLogEx(ERR, "Can't save the file: %s", filename); return PM3_EFILE; } - PrintAndLogEx(SUCCESS, "File " _YELLOW_("`%s`") " saved.", fname); + + PrintAndLogEx(SUCCESS, "File " _YELLOW_("`%s`") " saved.", filename); // free json object json_decref(root); diff --git a/client/src/emv/emv_pk.c b/client/src/emv/emv_pk.c index 3331e50a5..ee354e24d 100644 --- a/client/src/emv/emv_pk.c +++ b/client/src/emv/emv_pk.c @@ -32,8 +32,7 @@ #include "fileutils.h" #include "pm3_cmd.h" -#define BCD(c) (((c) >= '0' && (c) <= '9') ? ((c) - '0') : \ - -1) +#define BCD(c) (((c) >= '0' && (c) <= '9') ? ((c) - '0') : -1) #define HEX(c) (((c) >= '0' && (c) <= '9') ? ((c) - '0') : \ ((c) >= 'A' && (c) <= 'F') ? ((c) - 'A' + 10) : \ @@ -93,7 +92,6 @@ static ssize_t emv_pk_read_ymv(char *buf, size_t buflen, unsigned *ymv) { if (buf == NULL) return 0; - int i; unsigned char temp[3]; char *p = buf; @@ -102,7 +100,7 @@ static ssize_t emv_pk_read_ymv(char *buf, size_t buflen, unsigned *ymv) { while ((*p == ' ') && (p < (buf + buflen - 1))) p++; - for (i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) { int c1, c2; c1 = BCD(*p); if (c1 == -1) @@ -164,7 +162,6 @@ static ssize_t emv_pk_read_string(char *buf, size_t buflen, char *str, size_t si return (p - buf); } - struct emv_pk *emv_pk_parse_pk(char *buf, size_t buflen) { struct emv_pk *r = calloc(1, sizeof(*r)); ssize_t l; @@ -264,22 +261,22 @@ static size_t emv_pk_write_str(char *out, size_t outlen, const char *str) { } char *emv_pk_dump_pk(const struct emv_pk *pk) { + size_t outpos = 0; size_t outsize = 1024; /* should be enough */ char *out = malloc(outsize); /* should be enough */ - size_t outpos = 0; - size_t rc; - if (!out) return NULL; - rc = emv_pk_write_bin(out + outpos, outsize - outpos, pk->rid, 5); + size_t rc = emv_pk_write_bin(out + outpos, outsize - outpos, pk->rid, 5); if (rc == 0) goto err; + outpos += rc; rc = emv_pk_write_bin(out + outpos, outsize - outpos, &pk->index, 1); if (rc == 0) goto err; + outpos += rc; if (outpos + 7 > outsize) @@ -504,21 +501,23 @@ struct emv_pk *emv_pk_get_ca_pk(const unsigned char *rid, unsigned char idx) { if (!pk) return NULL; - printf("Verifying CA PK for %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx %zu bits...", + bool isok = emv_pk_verify(pk); + + PrintAndLogEx(INFO, "Verifying CA PK for %02hhx:%02hhx:%02hhx:%02hhx:%02hhx IDX %02hhx %zu bits. ( %s )", pk->rid[0], pk->rid[1], pk->rid[2], pk->rid[3], pk->rid[4], pk->index, - pk->mlen * 8); + pk->mlen * 8, + (isok) ? _GREEN_("ok") : _RED_("failed") + ); - if (emv_pk_verify(pk)) { - printf("OK\n"); + if (isok) { return pk; - } + } - printf("Failed!\n"); emv_pk_free(pk); return NULL; } diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 8528fa770..3e2f252cb 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -228,17 +228,20 @@ static char *filenamemcopy(const char *preferredName, const char *suffix) { char *newfilenamemcopy(const char *preferredName, const char *suffix) { if (preferredName == NULL) return NULL; if (suffix == NULL) return NULL; - uint16_t preferredNameLen = strlen(preferredName); + + uint16_t p_namelen = strlen(preferredName); if (str_endswith(preferredName, suffix)) - preferredNameLen -= strlen(suffix); - char *fileName = (char *) calloc(preferredNameLen + strlen(suffix) + 1 + 10, sizeof(uint8_t)); // 10: room for filenum to ensure new filename + p_namelen -= strlen(suffix); + + char *fileName = (char *) calloc(p_namelen + strlen(suffix) + 1 + 10, sizeof(uint8_t)); // 10: room for filenum to ensure new filename if (fileName == NULL) { return NULL; } + int num = 1; - sprintf(fileName, "%.*s%s", preferredNameLen, preferredName, suffix); + sprintf(fileName, "%.*s%s", p_namelen, preferredName, suffix); while (fileExists(fileName)) { - sprintf(fileName, "%.*s-%d%s", preferredNameLen, preferredName, num, suffix); + sprintf(fileName, "%.*s-%d%s", p_namelen, preferredName, num, suffix); num++; } return fileName; @@ -475,7 +478,7 @@ int saveFileJSONex(const char *preferredName, JSONFileType ftype, uint8_t *data, } break; } - case jsfMfPlusKeys: + case jsfMfPlusKeys: { JsonSaveStr(root, "FileType", "mfp"); JsonSaveBufAsHexCompact(root, "$.Card.UID", &data[0], 7); JsonSaveBufAsHexCompact(root, "$.Card.SAK", &data[10], 1); @@ -503,7 +506,8 @@ int saveFileJSONex(const char *preferredName, JSONFileType ftype, uint8_t *data, } } break; - case jsfMfDesfireKeys: + } + case jsfMfDesfireKeys: { JsonSaveStr(root, "FileType", "mfdes"); JsonSaveBufAsHexCompact(root, "$.Card.UID", &data[0], 7); JsonSaveBufAsHexCompact(root, "$.Card.SAK", &data[10], 1); @@ -541,9 +545,11 @@ int saveFileJSONex(const char *preferredName, JSONFileType ftype, uint8_t *data, } } break; - case jsfCustom: + } + case jsfCustom: { (*callback)(root); break; + } default: break; } diff --git a/client/src/mifare/desfire_crypto.c b/client/src/mifare/desfire_crypto.c index 8dba06ca1..0ec6bd70d 100644 --- a/client/src/mifare/desfire_crypto.c +++ b/client/src/mifare/desfire_crypto.c @@ -28,6 +28,7 @@ #include "desfire_crypto.h" #include #include +#include #include "commonutil.h" #include "aes.h" #include "des.h" @@ -406,6 +407,8 @@ void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, /* pass through */ case MDCM_MACED: + communication_settings |= NO_CRC; + switch (DESFIRE(tag)->authentication_scheme) { case AS_LEGACY: if (!(communication_settings & MAC_COMMAND)) @@ -508,6 +511,9 @@ void *mifare_cryto_preprocess_data(desfiretag_t tag, void *data, size_t *nbytes, void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes, int communication_settings) { void *res = data; void *edata = NULL; + tag->crypto_buffer_size = *nbytes * 2; + tag->crypto_buffer = (uint8_t *)malloc(tag->crypto_buffer_size); + uint8_t first_cmac_byte = 0x00; desfirekey_t key = DESFIRE(tag)->session_key; @@ -527,6 +533,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes /* pass through */ case MDCM_MACED: + communication_settings |= NO_CRC; switch (DESFIRE(tag)->authentication_scheme) { case AS_LEGACY: if (communication_settings & MAC_VERIFY) { @@ -540,18 +547,22 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes break; } - size_t edl = enciphered_data_length(tag, *nbytes - 1, communication_settings); + size_t edl = enciphered_data_length(tag, *nbytes, communication_settings); edata = malloc(edl); - memcpy(edata, data, *nbytes - 1); - memset((uint8_t *)edata + *nbytes - 1, 0, edl - *nbytes + 1); + memcpy(edata, data, *nbytes); + memset((uint8_t *)edata + *nbytes, 0, edl - *nbytes); mifare_cypher_blocks_chained(tag, NULL, NULL, edata, edl, MCD_SEND, MCO_ENCYPHER); - if (0 != memcmp((uint8_t *)data + *nbytes - 1, (uint8_t *)edata + edl - 8, 4)) { + if (0 != memcmp((uint8_t *)data + *nbytes, (uint8_t *)edata + edl - 8, 4)) { +#ifdef WITH_DEBUG + PrintAndLogEx(NORMAL, "Expected MAC %s", sprint_hex(data + *nbytes, key_macing_length(key))); + PrintAndLogEx(NORMAL, "Actual MAC %s", sprint_hex(edata + edl - 8, key_macing_length(key))); +#endif #ifdef WITH_DEBUG Dbprintf("MACing not verified"); - hexdump((uint8_t *)data + *nbytes - 1, key_macing_length(key), "Expect ", 0); + hexdump((uint8_t *)data + *nbytes, key_macing_length(key), "Expect ", 0); hexdump((uint8_t *)edata + edl - 8, key_macing_length(key), "Actual ", 0); #endif DESFIRE(tag)->last_pcd_error = CRYPTO_ERROR; @@ -644,17 +655,19 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes case AS_NEW: /* Move status between payload and CRC */ res = DESFIRE(tag)->crypto_buffer; - memcpy(res, data, *nbytes); + if (res != NULL) { + memcpy(res, data, *nbytes); - crc_pos = (*nbytes) - 16 - 3; - if (crc_pos < 0) { - /* Single block */ - crc_pos = 0; + crc_pos = (*nbytes) - 16 - 3; + if (crc_pos < 0) { + /* Single block */ + crc_pos = 0; + } + memcpy((uint8_t *) res + crc_pos + 1, (uint8_t *) res + crc_pos, *nbytes - crc_pos); + ((uint8_t *) res)[crc_pos] = 0x00; + crc_pos++; + *nbytes += 1; } - memcpy((uint8_t *)res + crc_pos + 1, (uint8_t *)res + crc_pos, *nbytes - crc_pos); - ((uint8_t *)res)[crc_pos] = 0x00; - crc_pos++; - *nbytes += 1; break; } @@ -725,6 +738,9 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes break; } + free(tag->crypto_buffer); + tag->crypto_buffer_size = 0; + tag->crypto_buffer = NULL; return res; } @@ -864,3 +880,19 @@ void mifare_cypher_blocks_chained(desfiretag_t tag, desfirekey_t key, uint8_t *i offset += block_size; } } + +void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc) { + crc32_ex(data,len,crc); +} + +void desfire_crc32_append(uint8_t *data, const size_t len) { + crc32_ex(data, len, data + len); +} + +void iso14443a_crc_append(uint8_t *data, size_t len) { + return compute_crc(CRC_14443_A, data, len, data + len, data + len + 1); +} + +void iso14443a_crc(uint8_t *data, size_t len, uint8_t *pbtCrc) { + return compute_crc(CRC_14443_A, data, len, pbtCrc, pbtCrc + 1); +} diff --git a/client/src/mifare/desfire_crypto.h b/client/src/mifare/desfire_crypto.h index 1dc5316ae..fb36ea991 100644 --- a/client/src/mifare/desfire_crypto.h +++ b/client/src/mifare/desfire_crypto.h @@ -129,4 +129,8 @@ size_t enciphered_data_length(const desfiretag_t tag, const size_t nbytes, int c void cmac_generate_subkeys(desfirekey_t key); void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac); +void desfire_crc32(const uint8_t *data, const size_t len, uint8_t *crc); +void desfire_crc32_append(uint8_t *data, const size_t len); +void iso14443a_crc_append(uint8_t *data, size_t len); +void iso14443a_crc(uint8_t *data, size_t len, uint8_t *pbtCrc); #endif diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 8e15cb509..393495152 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -865,7 +865,7 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_ int mfCWipe(uint8_t *uid, uint8_t *atqa, uint8_t *sak) { uint8_t block0[16] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xBE, 0xAF}; - uint8_t blockD[16] = {0x00}; + //uint8_t blockD[16] = {0x00}; uint8_t blockK[16] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x08, 0x77, 0x8F, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; uint8_t params = MAGIC_SINGLE; @@ -891,8 +891,8 @@ int mfCWipe(uint8_t *uid, uint8_t *atqa, uint8_t *sak) { } else { if (mfIsSectorTrailer(blockNo)) res = mfCSetBlock(blockNo, blockK, NULL, params); - else - res = mfCSetBlock(blockNo, blockD, NULL, params); +// else +// res = mfCSetBlock(blockNo, blockD, NULL, params); } if (res == PM3_SUCCESS) diff --git a/client/src/preferences.c b/client/src/preferences.c index 4313c9456..8ddd0f150 100644 --- a/client/src/preferences.c +++ b/client/src/preferences.c @@ -52,9 +52,7 @@ int preferences_load(void) { session.overlay.y = 60 + session.plot.y + session.plot.h; session.overlay.h = 200; session.overlay.w = session.plot.w; - session.emoji_mode = ALIAS; session.show_hints = false; - session.supports_colors = false; // setDefaultPath (spDefault, ""); // setDefaultPath (spDump, ""); diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c index eea1718c3..e13c79591 100644 --- a/client/src/proxmark3.c +++ b/client/src/proxmark3.c @@ -32,9 +32,6 @@ #include "flash.h" #include "preferences.h" -// Used to enable/disable use of preferences json file -#define USE_PREFERENCE_FILE - #define BANNERMSG1 " :snowflake: iceman@icesql.net" #define BANNERMSG2 " https://github.com/rfidresearchgroup/proxmark3/" #define BANNERMSG3 " bleeding edge :coffee:" @@ -632,8 +629,6 @@ finish2: return ret; } -#ifndef USE_PREFERENCE_FILE - // Check if windows AnsiColor Support is enabled in the registery // [HKEY_CURRENT_USER\Console] // "VirtualTerminalLevel"=dword:00000001 @@ -641,9 +636,9 @@ finish2: // [HKEY_CURRENT_USER\Console] // "ForceV2"=dword:00000001 +#if defined(_WIN32) static bool DetectWindowsAnsiSupport(void) { bool ret = false; -#if defined(_WIN32) HKEY hKey = NULL; bool virtualTerminalLevelSet = false; bool forceV2Set = false; @@ -685,10 +680,8 @@ static bool DetectWindowsAnsiSupport(void) { } // If both VirtualTerminalLevel and ForceV2 is set, AnsiColor should work ret = virtualTerminalLevelSet && forceV2Set; -#endif return ret; } - #endif int main(int argc, char *argv[]) { @@ -733,6 +726,28 @@ int main(int argc, char *argv[]) { set_my_executable_path(); set_my_user_directory(); + // color management: + // 1. default = no color + // 2. enable colors if OS seems to support colors and if stdin/stdout aren't redirected + // 3. load prefs if available, overwrite colors choice if needed + // 4. disable colors anyway if stdin/stdout are redirected + // + // For info, grep --color=auto is doing sth like this, plus test getenv("TERM") != "dumb": + // struct stat tmp_stat; + // if ((fstat (STDOUT_FILENO, &tmp_stat) == 0) && (S_ISCHR (tmp_stat.st_mode)) && isatty(STDIN_FILENO)) + session.stdinOnTTY = isatty(STDIN_FILENO); + session.stdoutOnTTY = isatty(STDOUT_FILENO); + session.supports_colors = false; + session.emoji_mode = ALTTEXT; + if (session.stdinOnTTY && session.stdoutOnTTY) { +#if defined(__linux__) || defined(__APPLE__) + session.supports_colors = true; + session.emoji_mode = EMOJI; +#elif defined(_WIN32) + session.supports_colors = DetectWindowsAnsiSupport(); + session.emoji_mode = ALTTEXT; +#endif + } for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { @@ -912,7 +927,6 @@ int main(int argc, char *argv[]) { return 1; } -#ifdef USE_PREFERENCE_FILE // Load Settings and assign // This will allow the command line to override the settings.json values preferences_load(); @@ -921,44 +935,13 @@ int main(int argc, char *argv[]) { g_debugMode = session.client_debug_level; // settings_save (); // End Settings -#endif -#ifndef USE_PREFERENCE_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); -#if defined(__linux__) || defined(__APPLE__) - // it's okay to use color if: - // * Linux or OSX - // * Not redirected to a file but printed to term - // For info, grep --color=auto is doing sth like this, plus test getenv("TERM") != "dumb": - // struct stat tmp_stat; - // if ((fstat (STDOUT_FILENO, &tmp_stat) == 0) && (S_ISCHR (tmp_stat.st_mode)) && isatty(STDIN_FILENO)) -#ifdef USE_PREFERENCE_FILE - if (!session.preferences_loaded) { - if (session.stdinOnTTY && session.stdoutOnTTY) { - session.supports_colors = true; - session.emoji_mode = EMOJI; - } - } else { - // even if prefs, we disable colors if stdin or stdout is not a TTY - if ((! session.stdinOnTTY) || (! session.stdoutOnTTY)) { - session.supports_colors = false; - session.emoji_mode = ALTTEXT; - } + // even if prefs, we disable colors if stdin or stdout is not a TTY + if ((! session.stdinOnTTY) || (! session.stdoutOnTTY)) { + session.supports_colors = false; + session.emoji_mode = ALTTEXT; } -#else - if (session.stdinOnTTY && session.stdoutOnTTY) { - session.supports_colors = true; - session.emoji_mode = EMOJI; - } -#endif -#endif // Let's take a baudrate ok for real UART, USB-CDC & BT don't use that info anyway if (speed == 0) speed = USART_BAUD_RATE; @@ -1013,7 +996,6 @@ int main(int argc, char *argv[]) { if (!script_cmds_file && !script_cmd && session.stdinOnTTY && session.stdoutOnTTY && !flash_mode) showBanner(); -#ifdef USE_PREFERENCE_FILE // Save settings if not loaded 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 @@ -1034,7 +1016,6 @@ int main(int argc, char *argv[]) { PrintAndLogEx(WARNING,"Proxmark3 not ready to set debug level"); } */ -#endif #ifdef HAVE_GUI @@ -1061,9 +1042,7 @@ int main(int argc, char *argv[]) { CloseProxmark(); } -#ifdef USE_PREFERENCE_FILE if (session.window_changed) // Plot/Overlay moved or resized preferences_save(); -#endif exit(EXIT_SUCCESS); } diff --git a/client/src/ui.c b/client/src/ui.c index 68f0eab24..04e002950 100644 --- a/client/src/ui.c +++ b/client/src/ui.c @@ -44,6 +44,7 @@ session_arg_t session; double CursorScaleFactor = 1; int PlotGridX = 0, PlotGridY = 0, PlotGridXdefault = 64, PlotGridYdefault = 64; uint32_t CursorCPos = 0, CursorDPos = 0; +double GraphPixelsPerPoint = 1.f; // How many visual pixels are between each sample point (x axis) static bool flushAfterWrite = 0; int GridOffset = 0; bool GridLocked = false; @@ -201,34 +202,34 @@ void PrintAndLogEx(logLevel_t level, const char *fmt, ...) { switch (level) { case ERR: if (session.emoji_mode == EMOJI) - strncpy(prefix, _RED_("[!!]") " :rotating_light: ", sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("!!") "] :rotating_light: ", sizeof(prefix) - 1); else - strncpy(prefix, _RED_("[!!] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("!!") "] ", sizeof(prefix) - 1); stream = stderr; break; case FAILED: if (session.emoji_mode == EMOJI) - strncpy(prefix, _RED_("[-]") " :no_entry: ", sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("-") "] :no_entry: ", sizeof(prefix) - 1); else - strncpy(prefix, _RED_("[-] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _RED_("-") "] ", sizeof(prefix) - 1); break; case DEBUG: - strncpy(prefix, _BLUE_("[#] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _BLUE_("#") "] ", sizeof(prefix) - 1); break; case HINT: - strncpy(prefix, _YELLOW_("[?] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _YELLOW_("?") "] ", sizeof(prefix) - 1); break; case SUCCESS: - strncpy(prefix, _GREEN_("[+] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _GREEN_("+") "] ", sizeof(prefix) - 1); break; case WARNING: if (session.emoji_mode == EMOJI) - strncpy(prefix, _CYAN_("[!]") " :warning: ", sizeof(prefix) - 1); + strncpy(prefix, "[" _CYAN_("!") "] :warning: ", sizeof(prefix) - 1); else - strncpy(prefix, _CYAN_("[!] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _CYAN_("!") "] ", sizeof(prefix) - 1); break; case INFO: - strncpy(prefix, _YELLOW_("[=] "), sizeof(prefix) - 1); + strncpy(prefix, "[" _YELLOW_("=") "] ", sizeof(prefix) - 1); break; case INPLACE: if (session.emoji_mode == EMOJI) { @@ -325,9 +326,9 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) { } else { if (session.supports_colors) { - printf(_YELLOW_("[=]") " Session log " _YELLOW_("%s") "\n", my_logfile_path); + printf("["_YELLOW_("=")"] Session log " _YELLOW_("%s") "\n", my_logfile_path); } else { - printf(_YELLOW_("[=]") " Session log %s\n", my_logfile_path); + printf("[=] Session log %s\n", my_logfile_path); } } diff --git a/doc/colors_notes.md b/doc/colors_notes.md new file mode 100644 index 000000000..7756addd9 --- /dev/null +++ b/doc/colors_notes.md @@ -0,0 +1,50 @@ + +# Notes on Color usage. + +## Table of Contents + * [style/color](#style_color) + * [Proxspace](#proxspace) + * [](#) + +The client should autodetect color support when starting. + +You can also use the command `pref show` to see and set your personal setting. + +Why use colors in the Proxmark client? When evertyhing is white it is hard to extract the important information fast. You also need new-lines for extra space to be easier to read. +We have gradually been introducing this color scheme into the client since we got decent color support on all systems: OSX, Linux, WSL, Proxspace. + + +## style/color +^[Top](#top) +The following definition has be crystalized out from these experiments. Its not set in stone yet so take this document as a guideline for how to create unified system scheme. + +### Definition +^[Top](#top) +- blue - system related headers, banner +- white - normal +- cyan - headers +- red - warning, error, catastrophic failures +- yellow - informative (to make things stick out from white blob) +- green - successful, (to make things stick out from white blob) +- magenta - device side messages + + +### Styled header +^[Top](#top) +``` + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------"); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); +``` +For more examples, see also all **-h** helptext now in the LUA scripts. +For the command help texts using _YELLOW_ for the example makes it very easy to see what is the command vs the description. + +### non styled header +^[Top](#top) +Most commands doesn't use a header yet. We added it to make it standout (ie: yellow, green) of the informative tidbits in the output of a command. + + +## Proxspace +^[Top](#top) +Proxspace has support for colors. + diff --git a/include/protocols.h b/include/protocols.h index b927058b0..682f57eff 100644 --- a/include/protocols.h +++ b/include/protocols.h @@ -359,6 +359,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define MFDES_READSIG 0x3C #define MFDES_WRITE_DATA 0x3D #define MFDES_GET_KEY_SETTINGS 0x45 +#define MFDES_GET_UID 0x51 #define MFDES_CHANGE_KEY_SETTINGS 0x54 #define MFDES_SELECT_APPLICATION 0x5A #define MFDES_CHANGE_FILE_SETTINGS 0x5F