diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dee60f20..6a063367e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ 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] +- Added `nfc encode` and `hf mfu ndefwrite` - build NDEF URI/Text/AAR records and write them to Ultralight tags (@0x6r1an0y) +- Fixed `hf emrtd info` - the picture viewer now scales images to the window instead of pinning them at native size (@iceman1001) +- Added `hf emrtd` - PACE-CAM (Chip Authentication Mapping) session support. The anti-clone proof itself is not yet verified (@iceman1001) +- Added `hf emrtd test` - offline regression tests for the PACE / secure messaging primitives (@iceman1001) +- Added `hf emrtd info/dump --can/--pace/--bac` - PACE-ECDH-GM support with MRZ or CAN passwords, AES-CMAC-128/192/256 and 3DES-CBC-CBC secure messaging (@iceman1001) - Changed `hf emrtd info` - now shows EF_DG2 portraits for JPREG2000 via new dependecy lib (@iceman1001) - Changed `hf emrtd info`- now shows portrait, signature and other biometrics at the same time (@iceman1001) - Fixed `pm3_grabbed_output_get` - heap overflow (@jonyen) @@ -16,6 +21,8 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Fixed `hw version` / `hw status` (PM5) - now showing correct information for fpga images (@nemanjan00) - Fixed `hw status` [Model] section reporting "PM3 GENERIC" firmware on Proxmark5 (PM5/AT32); it now reports `PM5` (@nemanjan00) - Added `hw version` / `hw status` - now reports Proxmark5 (PM5/AT32) correct MCU (AT32F437) (@nemanjan00) +- Added CMake support for armsrc and bootrom (@xianglin1998) +- Added HAL support for ARM firmware (@xianglin1998) - Fixed `hf mf dump` - preserving readable sector trailer Key B data (@oSPANNERo) - Changed `magic_cards_notes.md` - documented the USCUID-UL helper scripts (`hf_mfu_uscuid` / `hf_mf_uscuid_prog`) (@c-barron) - Fixed `hf_mf_uscuid_prog.lua` - corrected the script name shown in its usage text (@c-barron) diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index 477c43414..038cb3a4d 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -1007,10 +1007,8 @@ void hitag_sniff(void) { // Set up eavesdropping mode, frequency divisor which will drive the FPGA // and analog mux selection. FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); // 125Khz + FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125); // 125Khz SetAdcMuxFor(ADC_MUXSEL_LOPKD); - RELAY_OFF(); - } @@ -1167,19 +1165,15 @@ void SniffHitag2(bool ledcontrol) { } */ + // Dont use the FPGA modulation output, we only want to capture the tag/reader comms + gpio_fpga_mod_only_setup(); + Gpio_SSC_DOUT_Low(); + // Set up eavesdropping mode, frequency divisor which will drive the FPGA // and analog mux selection. - FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); // 125Khz + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT); + FpgaSendCommand(FPGA_CMD_SET_DIVISOR, LF_DIVISOR_125); // 125Khz SetAdcMuxFor(ADC_MUXSEL_LOPKD); - RELAY_OFF(); - - // Configure output pin that is connected to the FPGA (for modulating) -// AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; -// AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; - - // Disable modulation, we are going to eavesdrop, not modulate ;) -// Gpio_SSC_DOUT_Low(); // Configure the input capture (TC1) via the HAL: it enables the TC1 clock, routes // SSC_FRAME to the timer input, resets on each falling edge and captures RB @@ -1198,6 +1192,10 @@ void SniffHitag2(bool ledcontrol) { auth_table = (uint8_t *)BigBuf_calloc(AUTH_TABLE_LENGTH); + // Only for debug, if we want to see the edge timing of the captured frames + uint8_t edges[100]; + uint8_t e_count = 0; + while (BUTTON_PRESS() == false) { WDT_HIT(); @@ -1219,6 +1217,7 @@ void SniffHitag2(bool ledcontrol) { if (ledcontrol) LED_C_OFF(); reader_frame = true; rxlen = 0; + memset(rx, 0x00, sizeof(rx)); } } @@ -1226,6 +1225,10 @@ void SniffHitag2(bool ledcontrol) { if (lo_edge == LO_EDGE_FALLING) { int rb = GetLoEdgeCaptureFalling() / HITAG_T0; + if (e_count < sizeof(edges)) { + edges[e_count++] = rb; // Store the edge timing for debug purposes + } + if (reader_frame) { if (ledcontrol) LED_B_ON(); @@ -1233,7 +1236,9 @@ void SniffHitag2(bool ledcontrol) { if (rb >= HITAG_T_STOP) { // Capture the T0 periods that have passed since last communication or field drop (reset) response = (rb - HITAG_T_LOW); - if (rxlen != 0) { Dbprintf("rb - HITAG_T_LOW... %i", response); } + if (rxlen != 0) { + DBG Dbprintf("rb - HITAG_T_LOW... %i", response); + } } else if (rb >= HITAG_T_1_MIN) { // '1' bit @@ -1294,6 +1299,15 @@ void SniffHitag2(bool ledcontrol) { frame_count++; LogTraceBits(rx, rxlen, response, 0, reader_frame); + // Print only from tag response(No auth cmd from reader) + DBG { + if (rxlen >= 8) { + for (size_t i = 0; i < e_count; i++) { + Dbprintf("edges[%zu] = %u", i, edges[i]); + } + } + } + // Check if we recognize a valid authentication attempt if (rxlen == 64) { // Store the authentication attempt @@ -1313,28 +1327,21 @@ void SniffHitag2(bool ledcontrol) { lastbit = 1; bSkip = true; tag_sof = 4; - - if (ledcontrol) { - LED_B_OFF(); - LED_C_OFF(); - } - + e_count = 0; } - // Reset the frame length + // Reset the frame length and clear the buffer so that '0' bits written + // by the next frame don't inherit stale '1' bits from this one. rxlen = 0; - - // Reset the capture counter to restart the while-loop that receives frames. - ResetLoEdgeCapture(); + memset(rx, 0x00, sizeof(rx)); } if (ledcontrol) LEDsoff(); - StopLoEdgeCapture(); - DBG Dbprintf("frames.......... %d", frame_count); Dbprintf("Auth attempts... %d", (auth_table_len / 8)); + StopLoEdgeCapture(); switch_off(); BigBuf_free(); } diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 585edfd8a..75d0058db 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -358,6 +358,8 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/cipurse/cipursecrypto.c ${PM3_ROOT}/client/src/cipurse/cipursecore.c ${PM3_ROOT}/client/src/cipurse/cipursetest.c + ${PM3_ROOT}/client/src/emrtd/emrtd_pace.c + ${PM3_ROOT}/client/src/emrtd/emrtd_pacetest.c ${PM3_ROOT}/client/src/loclass/cipher.c ${PM3_ROOT}/client/src/loclass/cipher_bs.c ${PM3_ROOT}/client/src/loclass/cipher_bs_avx2.c diff --git a/client/Makefile b/client/Makefile index 31b3d5b4c..00e23363f 100644 --- a/client/Makefile +++ b/client/Makefile @@ -860,6 +860,8 @@ SRCS = mifare/aiddesfire.c \ cipurse/cipursecore.c \ cipurse/cipursecrypto.c \ cipurse/cipursetest.c \ + emrtd/emrtd_pace.c \ + emrtd/emrtd_pacetest.c \ fileutils.c \ flash.c \ frame_progress.c \ @@ -959,6 +961,8 @@ ifeq ($(QT_FOUND),1) CXXSRCS = proxgui.cpp proxguiqt.cpp proxguiqt.moc.cpp # Qt has no JPEG2000 image handler, so we decode EF_DG2 & friends ourselves SRCS += imgjp2.c + # openjpeg.a is a static lib, avoid __declspec(dllimport) on its Windows API decls + PM3CFLAGS += -DOPJ_STATIC STATICLIBS += $(OPENJPEGLIB) LDLIBS += $(OPENJPEGLIBLD) else diff --git a/client/deps/openjpeg.cmake b/client/deps/openjpeg.cmake index 403f6c32f..e1b5f489e 100644 --- a/client/deps/openjpeg.cmake +++ b/client/deps/openjpeg.cmake @@ -28,6 +28,8 @@ add_library(pm3rrg_rdv4_openjpeg STATIC target_include_directories(pm3rrg_rdv4_openjpeg INTERFACE openjpeg) target_include_directories(pm3rrg_rdv4_openjpeg PRIVATE openjpeg) +# openjpeg.a is a static lib, avoid __declspec(dllimport) on its Windows API decls +target_compile_definitions(pm3rrg_rdv4_openjpeg PUBLIC OPJ_STATIC) # Third party code, don't hold it to our warning settings target_compile_options(pm3rrg_rdv4_openjpeg PRIVATE -w -O3) set_property(TARGET pm3rrg_rdv4_openjpeg PROPERTY POSITION_INDEPENDENT_CODE ON) diff --git a/client/deps/openjpeg/Makefile b/client/deps/openjpeg/Makefile index 8fd3ed6b1..dbc696bbe 100644 --- a/client/deps/openjpeg/Makefile +++ b/client/deps/openjpeg/Makefile @@ -2,7 +2,8 @@ MYSRCPATHS = MYINCLUDES = # Third party code, don't fail the build on upstream's warnings MYCFLAGS = -w -O3 -MYDEFS = +# Avoid __declspec(dllimport/dllexport) on Windows, we always link this in statically +MYDEFS = -DOPJ_STATIC MYSRCS = \ bio.c \ cio.c \ diff --git a/client/deps/openjpeg/j2k.c b/client/deps/openjpeg/j2k.c index a2014c89b..29ce1c735 100644 --- a/client/deps/openjpeg/j2k.c +++ b/client/deps/openjpeg/j2k.c @@ -8129,14 +8129,15 @@ OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k, /* initialize the multiple tiles */ /* ---------------------------- */ - cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t)); + const size_t num_tiles = (size_t)cp->tw * (size_t)cp->th; + cp->tcps = (opj_tcp_t*) opj_calloc(num_tiles, sizeof(opj_tcp_t)); if (!cp->tcps) { opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to allocate tile coding parameters\n"); return OPJ_FALSE; } - for (tileno = 0; tileno < cp->tw * cp->th; tileno++) { + for (tileno = 0; tileno < num_tiles; tileno++) { opj_tcp_t *tcp = &cp->tcps[tileno]; const OPJ_BOOL fixed_distoratio = cp->m_specific_param.m_enc.m_quality_layer_alloc_strategy == diff --git a/client/deps/openjpeg/openjpeg.a b/client/deps/openjpeg/openjpeg.a deleted file mode 100644 index a30067f91..000000000 Binary files a/client/deps/openjpeg/openjpeg.a and /dev/null differ diff --git a/client/experimental_lib/CMakeLists.txt b/client/experimental_lib/CMakeLists.txt index f6e8e89b8..f20b74400 100644 --- a/client/experimental_lib/CMakeLists.txt +++ b/client/experimental_lib/CMakeLists.txt @@ -251,6 +251,8 @@ set (TARGET_SOURCES ${PM3_ROOT}/client/src/crypto/duoxcrypto.c ${PM3_ROOT}/client/src/crypto/libpcrypto.c ${PM3_ROOT}/client/src/crypto/originality.c + ${PM3_ROOT}/client/src/emrtd/emrtd_pace.c + ${PM3_ROOT}/client/src/emrtd/emrtd_pacetest.c ${PM3_ROOT}/client/src/emv/test/cda_test.c ${PM3_ROOT}/client/src/emv/test/crypto_test.c ${PM3_ROOT}/client/src/emv/test/cryptotest.c diff --git a/client/src/cmdhfemrtd.c b/client/src/cmdhfemrtd.c index d097569c1..727ea58ab 100644 --- a/client/src/cmdhfemrtd.c +++ b/client/src/cmdhfemrtd.c @@ -28,6 +28,8 @@ #include "iso7816/apduinfo.h" // GetAPDUCodeDescription #include "iso7816/iso7816core.h" // Iso7816ExchangeEx etc #include "crypto/libpcrypto.h" // Hash calculation (sha1, sha256, sha512), des_encrypt/des_decrypt +#include "emrtd/emrtd_pace.h" // PACE primitives and secure messaging session +#include "emrtd/emrtd_pacetest.h" // emrtd_test #include "des.h" // mbedtls_des_key_set_parity #include "crapto1/crapto1.h" // prng_successor #include "commonutil.h" // num_to_bytes @@ -181,46 +183,6 @@ static emrtd_hashalg_t hashalg_table[] = { {NULL, NULL, 0, 0, {0}} }; -static emrtd_pacealg_t pacealg_table[] = { -// name keygen descriptor - {"DH, Generic Mapping, 3DES-CBC-CBC", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x01}}, - {"DH, Generic Mapping, AES-CMAC-128", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x02}}, - {"DH, Generic Mapping, AES-CMAC-192", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x03}}, - {"DH, Generic Mapping, AES-CMAC-256", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x04}}, - {"ECDH, Generic Mapping, 3DES-CBC-CBC", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x01}}, - {"ECDH, Generic Mapping, AES-CMAC-128", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x02}}, - {"ECDH, Generic Mapping, AES-CMAC-192", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x03}}, - {"ECDH, Generic Mapping, AES-CMAC-256", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x04}}, - {"DH, Integrated Mapping, 3DES-CBC-CBC", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x01}}, - {"DH, Integrated Mapping, AES-CMAC-128", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x02}}, - {"DH, Integrated Mapping, AES-CMAC-192", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x03}}, - {"DH, Integrated Mapping, AES-CMAC-256", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x04}}, - {"ECDH, Integrated Mapping, 3DES-CBC-CBC", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x01}}, - {"ECDH, Integrated Mapping, AES-CMAC-128", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x02}}, - {"ECDH, Integrated Mapping, AES-CMAC-192", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x03}}, - {"ECDH, Integrated Mapping, AES-CMAC-256", NULL, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x04}}, - {NULL, NULL, {0}} -}; - -static emrtd_pacesdp_t pacesdp_table[] = { -// id name size - {0, "1024-bit MODP Group with 160-bit Prime Order Subgroup", 1024}, - {1, "2048-bit MODP Group with 224-bit Prime Order Subgroup", 2048}, - {2, "2048-bit MODP Group with 256-bit Prime Order Subgroup", 2048}, - {8, "NIST P-192 (secp192r1)", 192}, - {10, "NIST P-224 (secp224r1)", 224}, - {12, "NIST P-256 (secp256r1)", 256}, - {15, "NIST P-384 (secp384r1)", 384}, - {18, "NIST P-521 (secp521r1)", 521}, - {9, "BrainpoolP192r1", 192}, - {11, "BrainpoolP224r1", 224}, - {13, "BrainpoolP256r1", 256}, - {14, "BrainpoolP320r1", 320}, - {16, "BrainpoolP384r1", 384}, - {17, "BrainpoolP521r1", 521}, - {32, NULL, 0} -}; - static emrtd_dg_t *emrtd_tag_to_dg(uint8_t tag) { for (int dgi = 0; dg_table[dgi].filename != NULL; dgi++) { if (dg_table[dgi].tag == tag) { @@ -261,26 +223,6 @@ static int emrtd_exchange_commands_noout(sAPDU_t apdu, bool activate_field, bool return emrtd_exchange_commands(apdu, false, 0, response, 0, &resplen, activate_field, keep_field_on); } -static char emrtd_calculate_check_digit(char *data) { - const int mrz_weight[] = {7, 3, 1}; - int value, cd = 0; - - for (int i = 0; i < strlen(data); i++) { - char d = data[i]; - if ('A' <= d && d <= 'Z') { - value = d - 55; - } else if ('a' <= d && d <= 'z') { - value = d - 87; - } else if (d == '<') { - value = 0; - } else { // Numbers - value = d - 48; - } - cd += value * mrz_weight[i % 3]; - } - return cd % 10; -} - static int emrtd_get_asn1_data_length(uint8_t *datain, int datainlen, int offset) { PrintAndLogEx(DEBUG, "asn1 datalength, datain: %s", sprint_hex_inrow(datain, datainlen)); int lenfield = (int) * (datain + offset); @@ -327,86 +269,6 @@ static int emrtd_get_asn1_field_length(uint8_t *datain, int datainlen, int offse return 0; } -static void des3_encrypt_cbc(uint8_t *iv, uint8_t *key, uint8_t *input, int inputlen, uint8_t *output) { - mbedtls_des3_context ctx; - mbedtls_des3_set2key_enc(&ctx, key); - - mbedtls_des3_crypt_cbc(&ctx // des3_context - , MBEDTLS_DES_ENCRYPT // int mode - , inputlen // length - , iv // iv[8] - , input // input - , output // output - ); - mbedtls_des3_free(&ctx); -} - -static void des3_decrypt_cbc(uint8_t *iv, uint8_t *key, uint8_t *input, int inputlen, uint8_t *output) { - mbedtls_des3_context ctx; - mbedtls_des3_set2key_dec(&ctx, key); - - mbedtls_des3_crypt_cbc(&ctx // des3_context - , MBEDTLS_DES_DECRYPT // int mode - , inputlen // length - , iv // iv[8] - , input // input - , output // output - ); - mbedtls_des3_free(&ctx); -} - -static int pad_block(uint8_t *input, int inputlen, uint8_t *output) { - const uint8_t padding[8] = {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - - memcpy(output, input, inputlen); - - int to_pad = (8 - (inputlen % 8)); - - for (int i = 0; i < to_pad; i++) { - output[inputlen + i] = padding[i]; - } - - return inputlen + to_pad; -} - -static void retail_mac(uint8_t *key, uint8_t *input, int inputlen, uint8_t *output) { - // This code assumes blocklength (n) = 8, and input len of up to 240 or so chars - // This code takes inspirations from https://github.com/devinvenable/iso9797algorithm3 - uint8_t k0[8]; - uint8_t k1[8]; - uint8_t intermediate[8] = {0x00}; - uint8_t intermediate_des[256]; - uint8_t block[8]; - uint8_t message[256]; - - // Populate keys - memcpy(k0, key, 8); - memcpy(k1, key + 8, 8); - - // Prepare message - int blocksize = pad_block(input, inputlen, message); - - // Do chaining and encryption - for (int i = 0; i < (blocksize / 8); i++) { - memcpy(block, message + (i * 8), 8); - - // XOR - for (int x = 0; x < 8; x++) { - intermediate[x] = intermediate[x] ^ block[x]; - } - - des_encrypt(intermediate_des, intermediate, k0); - memcpy(intermediate, intermediate_des, 8); - } - - - des_decrypt(intermediate_des, intermediate, k1); - memcpy(intermediate, intermediate_des, 8); - - des_encrypt(intermediate_des, intermediate, k0); - memcpy(output, intermediate_des, 8); -} - static void emrtd_deskey(uint8_t *seed, const uint8_t *type, int length, uint8_t *dataout) { PrintAndLogEx(DEBUG, "seed.............. %s", sprint_hex_inrow(seed, 16)); @@ -457,193 +319,205 @@ static int _emrtd_read_binary(int offset, int bytes_to_read, uint8_t *dataout, s return emrtd_exchange_commands((sAPDU_t) {0, ISO7816_READ_BINARY, offset >> 8, offset & 0xFF, 0, NULL}, true, bytes_to_read, dataout, maxdataoutlen, dataoutlen, false, true); } -static void emrtd_bump_ssc(uint8_t *ssc) { - PrintAndLogEx(DEBUG, "ssc-b: %s", sprint_hex_inrow(ssc, 8)); - for (int i = 7; i > 0; i--) { - if ((*(ssc + i)) == 0xFF) { - // Set anything already FF to 0, we'll do + 1 on num to left anyways - (*(ssc + i)) = 0; - } else { - (*(ssc + i)) += 1; - PrintAndLogEx(DEBUG, "ssc-a: %s", sprint_hex_inrow(ssc, 8)); - return; +// Walks the secure messaging response DOs. Returns the offset of DO'8E' and, +// when present, the offset and length of the encrypted data object DO'87'. +static bool emrtd_sm_split_rapdu(const uint8_t *rapdu, size_t rapdulen, size_t *off8e, + const uint8_t **do87, size_t *do87len) { + const uint8_t *cur = rapdu; + const uint8_t *end = rapdu + rapdulen; + uint32_t tag = 0; + const uint8_t *val = NULL; + size_t vlen = 0; + + *do87 = NULL; + *do87len = 0; + + while (cur < end) { + const uint8_t *tlvstart = cur; + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + PrintAndLogEx(DEBUG, "SM: malformed response DO at offset %zu", (size_t)(tlvstart - rapdu)); + return false; + } + + if (tag == 0x8E) { + if (vlen != 8) { + PrintAndLogEx(DEBUG, "SM: DO'8E' has unexpected length %zu", vlen); + return false; + } + *off8e = (size_t)(tlvstart - rapdu); + return true; + } + + if (tag == 0x87) { + *do87 = val; + *do87len = vlen; } } + + PrintAndLogEx(DEBUG, "SM: response has no DO'8E'"); + return false; } -static bool emrtd_check_cc(uint8_t *ssc, uint8_t *key, uint8_t *rapdu, int rapdulength) { +// ICAO 9303-11 9.8.6: MAC over SSC || every response DO that precedes DO'8E' +static bool emrtd_check_cc(emrtd_session_t *ssn, uint8_t *rapdu, size_t rapdulength) { // https://elixi.re/i/clarkson.png - uint8_t k[500] = { 0x00 }; - uint8_t cc[500] = { 0x00 }; + uint8_t k[EMRTD_SM_MAX_BLOCK_LEN + 512] = { 0x00 }; + uint8_t cc[8] = { 0x00 }; + size_t off8e = 0; + const uint8_t *do87 = NULL; + size_t do87len = 0; - emrtd_bump_ssc(ssc); + emrtd_sm_bump_ssc(ssn); - memcpy(k, ssc, 8); - int length = 0; - int length2 = 0; - - if (*(rapdu) == 0x87) { - length += 2 + (*(rapdu + 1)); - memcpy(k + 8, rapdu, length); - PrintAndLogEx(DEBUG, "len1: %i", length); - } - - if ((*(rapdu + length)) == 0x99) { - length2 += 2 + (*(rapdu + (length + 1))); - memcpy(k + length + 8, rapdu + length, length2); - PrintAndLogEx(DEBUG, "len2: %i", length2); - } - - int klength = length + length2 + 8; - - retail_mac(key, k, klength, cc); - PrintAndLogEx(DEBUG, "cc: %s", sprint_hex_inrow(cc, 8)); - PrintAndLogEx(DEBUG, "rapdu: %s", sprint_hex_inrow(rapdu, rapdulength)); - PrintAndLogEx(DEBUG, "rapdu cut: %s", sprint_hex_inrow(rapdu + (rapdulength - 8), 8)); - PrintAndLogEx(DEBUG, "k: %s", sprint_hex_inrow(k, klength)); - - return memcmp(cc, rapdu + (rapdulength - 8), 8) == 0; -} - -static bool emrtd_secure_select_file_by_ef(uint8_t *kenc, uint8_t *kmac, uint8_t *ssc, uint16_t file) { - uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 }; - size_t resplen = 0; - - // convert fileid to bytes - uint8_t file_id[2] = { 0x00 }; - _emrtd_convert_fileid(file, file_id); - - uint8_t iv[8] = { 0x00 }; - uint8_t cmd[8] = { 0x00 }; - uint8_t data[21] = { 0x00 }; - uint8_t temp[8] = {0x0c, 0xa4, EMRTD_P1_SELECT_BY_EF, 0x0c}; - - int cmdlen = pad_block(temp, 4, cmd); - int datalen = pad_block(file_id, 2, data); - PrintAndLogEx(DEBUG, "cmd: %s", sprint_hex_inrow(cmd, cmdlen)); - PrintAndLogEx(DEBUG, "data: %s", sprint_hex_inrow(data, datalen)); - - des3_encrypt_cbc(iv, kenc, data, datalen, temp); - PrintAndLogEx(DEBUG, "temp: %s", sprint_hex_inrow(temp, datalen)); - uint8_t do87[11] = {0x87, 0x09, 0x01}; - memcpy(do87 + 3, temp, datalen); - PrintAndLogEx(DEBUG, "do87: %s", sprint_hex_inrow(do87, datalen + 3)); - - uint8_t m[19]; - memcpy(m, cmd, cmdlen); - memcpy(m + cmdlen, do87, (datalen + 3)); - PrintAndLogEx(DEBUG, "m: %s", sprint_hex_inrow(m, datalen + cmdlen + 3)); - - emrtd_bump_ssc(ssc); - - uint8_t n[27]; - memcpy(n, ssc, 8); - memcpy(n + 8, m, (cmdlen + datalen + 3)); - PrintAndLogEx(DEBUG, "n: %s", sprint_hex_inrow(n, (cmdlen + datalen + 11))); - - uint8_t cc[8]; - retail_mac(kmac, n, (cmdlen + datalen + 11), cc); - PrintAndLogEx(DEBUG, "cc: %s", sprint_hex_inrow(cc, 8)); - - uint8_t do8e[10] = {0x8E, 0x08}; - memcpy(do8e + 2, cc, 8); - PrintAndLogEx(DEBUG, "do8e: %s", sprint_hex_inrow(do8e, 10)); - - int lc = datalen + 3 + 10; - PrintAndLogEx(DEBUG, "lc: %i", lc); - - memcpy(data, do87, datalen + 3); - memcpy(data + (datalen + 3), do8e, 10); - PrintAndLogEx(DEBUG, "data: %s", sprint_hex_inrow(data, lc)); - - if (emrtd_exchange_commands((sAPDU_t) {0x0C, ISO7816_SELECT_FILE, EMRTD_P1_SELECT_BY_EF, 0x0C, lc, data}, true, 0, response, sizeof(response), &resplen, false, true) == false) { + if (emrtd_sm_split_rapdu(rapdu, rapdulength, &off8e, &do87, &do87len) == false) { return false; } - return emrtd_check_cc(ssc, kmac, response, resplen); + if ((ssn->ssclen + off8e) > sizeof(k)) { + PrintAndLogEx(ERR, "error (emrtd_check_cc) response out-of-bounds"); + return false; + } + + memcpy(k, ssn->ssc, ssn->ssclen); + memcpy(k + ssn->ssclen, rapdu, off8e); + size_t klength = ssn->ssclen + off8e; + + if (emrtd_sm_mac(ssn, k, klength, cc) != PM3_SUCCESS) { + return false; + } + + PrintAndLogEx(DEBUG, "cc: %s", sprint_hex_inrow(cc, 8)); + PrintAndLogEx(DEBUG, "rapdu: %s", sprint_hex_inrow(rapdu, rapdulength)); + PrintAndLogEx(DEBUG, "rapdu cc: %s", sprint_hex_inrow(rapdu + off8e + 2, 8)); + PrintAndLogEx(DEBUG, "k: %s", sprint_hex_inrow(k, klength)); + + return memcmp(cc, rapdu + off8e + 2, 8) == 0; } -static bool _emrtd_secure_read_binary(uint8_t *kmac, uint8_t *ssc, int offset, int bytes_to_read, uint8_t *dataout, size_t maxdataoutlen, size_t *dataoutlen) { - uint8_t cmd[8] = { 0x00 }; - uint8_t data[21] = { 0x00 }; - uint8_t temp[8] = {0x0c, 0xb0}; +// Builds the trailing DO'8E' of a protected command over +// SSC || padded command header || the command DOs +static bool emrtd_sm_finish_command(emrtd_session_t *ssn, const uint8_t *header, const uint8_t *dos, + size_t doslen, uint8_t *out, size_t outlen, size_t *lc) { + uint8_t n[EMRTD_SM_MAX_BLOCK_LEN * 2 + 64] = { 0x00 }; + size_t blocksize = emrtd_sm_blocksize(ssn); + size_t nlen = 0; - PrintAndLogEx(DEBUG, "kmac: %s", sprint_hex_inrow(kmac, EMRTD_KMAC_LEN)); + if ((ssn->ssclen + blocksize + doslen) > sizeof(n)) { + PrintAndLogEx(ERR, "error (emrtd_sm_finish_command) command out-of-bounds"); + return false; + } - // Set p1 and p2 - temp[2] = (uint8_t)(offset >> 8); - temp[3] = (uint8_t)(offset >> 0); - - int cmdlen = pad_block(temp, 4, cmd); - PrintAndLogEx(DEBUG, "cmd: %s", sprint_hex_inrow(cmd, cmdlen)); - - uint8_t do97[3] = {0x97, 0x01, bytes_to_read}; - - uint8_t m[11] = { 0x00 }; - memcpy(m, cmd, 8); - memcpy(m + 8, do97, 3); - - emrtd_bump_ssc(ssc); - - uint8_t n[19] = { 0x00 }; - memcpy(n, ssc, 8); - memcpy(n + 8, m, 11); - PrintAndLogEx(DEBUG, "n: %s", sprint_hex_inrow(n, sizeof(n))); + memcpy(n, ssn->ssc, ssn->ssclen); + nlen += ssn->ssclen; + nlen += emrtd_pad_block(header, 4, blocksize, n + nlen); + memcpy(n + nlen, dos, doslen); + nlen += doslen; + PrintAndLogEx(DEBUG, "n: %s", sprint_hex_inrow(n, nlen)); uint8_t cc[8] = { 0x00 }; - retail_mac(kmac, n, 19, cc); - PrintAndLogEx(DEBUG, "cc: %s", sprint_hex_inrow(cc, sizeof(cc))); + if (emrtd_sm_mac(ssn, n, nlen, cc) != PM3_SUCCESS) { + return false; + } + PrintAndLogEx(DEBUG, "cc: %s", sprint_hex_inrow(cc, 8)); - uint8_t do8e[10] = {0x8E, 0x08}; - memcpy(do8e + 2, cc, 8); - PrintAndLogEx(DEBUG, "do8e: %s", sprint_hex_inrow(do8e, sizeof(do8e))); + if ((doslen + 10) > outlen) { + PrintAndLogEx(ERR, "error (emrtd_sm_finish_command) data out-of-bounds"); + return false; + } - int lc = 13; - PrintAndLogEx(DEBUG, "lc: %i", lc); + memcpy(out, dos, doslen); + out[doslen] = 0x8E; + out[doslen + 1] = 0x08; + memcpy(out + doslen + 2, cc, 8); + *lc = doslen + 10; + PrintAndLogEx(DEBUG, "data: %s", sprint_hex_inrow(out, *lc)); + return true; +} - memcpy(data, do97, 3); - memcpy(data + 3, do8e, 10); - PrintAndLogEx(DEBUG, "data: %s", sprint_hex_inrow(data, lc)); +static bool emrtd_secure_select(emrtd_session_t *ssn, uint8_t p1, const uint8_t *sel, size_t sellen); + +static bool emrtd_secure_select_file_by_ef(emrtd_session_t *ssn, uint16_t file) { + uint8_t file_id[2] = { 0x00 }; + _emrtd_convert_fileid(file, file_id); + return emrtd_secure_select(ssn, EMRTD_P1_SELECT_BY_EF, file_id, sizeof(file_id)); +} + +static bool _emrtd_secure_read_binary(emrtd_session_t *ssn, int offset, int bytes_to_read, uint8_t *dataout, size_t maxdataoutlen, size_t *dataoutlen) { + const uint8_t header[4] = {0x0C, ISO7816_READ_BINARY, (uint8_t)(offset >> 8), (uint8_t)(offset & 0xFF)}; + uint8_t do97[3] = {0x97, 0x01, (uint8_t)bytes_to_read}; + + emrtd_sm_bump_ssc(ssn); + + uint8_t data[16] = { 0x00 }; + size_t lc = 0; + if (emrtd_sm_finish_command(ssn, header, do97, sizeof(do97), data, sizeof(data), &lc) == false) { + return false; + } if (emrtd_exchange_commands((sAPDU_t) {0x0C, ISO7816_READ_BINARY, offset >> 8, offset & 0xFF, lc, data}, true, 0, dataout, maxdataoutlen, dataoutlen, false, true) == false) { return false; } - return emrtd_check_cc(ssc, kmac, dataout, *dataoutlen); + return emrtd_check_cc(ssn, dataout, *dataoutlen); } -static bool _emrtd_secure_read_binary_decrypt(uint8_t *kenc, uint8_t *kmac, uint8_t *ssc, int offset, int bytes_to_read, uint8_t *dataout, size_t *dataoutlen) { +static bool _emrtd_secure_read_binary_decrypt(emrtd_session_t *ssn, int offset, int bytes_to_read, uint8_t *dataout, size_t *dataoutlen) { uint8_t response[500] = { 0x00 }; uint8_t temp[500] = { 0x00 }; - size_t resplen, cutat = 0; - uint8_t iv[8] = { 0x00 }; + size_t resplen = 0; + size_t off8e = 0; + const uint8_t *do87 = NULL; + size_t do87len = 0; - if (_emrtd_secure_read_binary(kmac, ssc, offset, bytes_to_read, response, sizeof(response), &resplen) == false) { + if (_emrtd_secure_read_binary(ssn, offset, bytes_to_read, response, sizeof(response), &resplen) == false) { return false; } PrintAndLogEx(DEBUG, "secreadbindec, offset %i on read %i: encrypted: %s", offset, bytes_to_read, sprint_hex_inrow(response, resplen)); - cutat = ((int) response[1]) - 1; + if (emrtd_sm_split_rapdu(response, resplen, &off8e, &do87, &do87len) == false) { + return false; + } + + // DO'87' content is 01 || cryptogram + if ((do87 == NULL) || (do87len < 2) || (do87[0] != 0x01)) { + PrintAndLogEx(ERR, "error (emrtd_secure_read_binary_decrypt) no encrypted data in response"); + return false; + } + + size_t cryptolen = do87len - 1; + if ((cryptolen > sizeof(temp)) || ((cryptolen % emrtd_sm_blocksize(ssn)) != 0)) { + PrintAndLogEx(ERR, "error (emrtd_secure_read_binary_decrypt) cryptogram out-of-bounds, %zu bytes", cryptolen); + return false; + } + + if ((size_t)bytes_to_read > cryptolen) { + PrintAndLogEx(ERR, "error (emrtd_secure_read_binary_decrypt) short read, wanted %i got %zu", bytes_to_read, cryptolen); + return false; + } + + if (emrtd_sm_decrypt(ssn, do87 + 1, cryptolen, temp) != PM3_SUCCESS) { + return false; + } - des3_decrypt_cbc(iv, kenc, response + 3, cutat, temp); memcpy(dataout, temp, bytes_to_read); - PrintAndLogEx(DEBUG, "secreadbindec, offset %i on read %i: decrypted: %s", offset, bytes_to_read, sprint_hex_inrow(temp, cutat)); + PrintAndLogEx(DEBUG, "secreadbindec, offset %i on read %i: decrypted: %s", offset, bytes_to_read, sprint_hex_inrow(temp, cryptolen)); PrintAndLogEx(DEBUG, "secreadbindec, offset %i on read %i: decrypted and cut: %s", offset, bytes_to_read, sprint_hex_inrow(dataout, bytes_to_read)); *dataoutlen = bytes_to_read; return true; } -static int emrtd_read_file(uint8_t *dataout, size_t *dataoutlen, uint8_t *kenc, uint8_t *kmac, uint8_t *ssc, bool use_secure) { +static int emrtd_read_file(uint8_t *dataout, size_t *dataoutlen, emrtd_session_t *ssn) { uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; size_t resplen = 0; uint8_t tempresponse[500] = { 0x00 }; size_t tempresplen = 0; int toread = 4; int offset = 0; + bool use_secure = (ssn->type != EMRTD_SM_NONE); if (use_secure) { - if (_emrtd_secure_read_binary_decrypt(kenc, kmac, ssc, offset, toread, response, &resplen) == false) { + if (_emrtd_secure_read_binary_decrypt(ssn, offset, toread, response, &resplen) == false) { return false; } } else { @@ -665,7 +539,7 @@ static int emrtd_read_file(uint8_t *dataout, size_t *dataoutlen, uint8_t *kenc, } if (use_secure) { - if (_emrtd_secure_read_binary_decrypt(kenc, kmac, ssc, offset, toread, tempresponse, &tempresplen) == false) { + if (_emrtd_secure_read_binary_decrypt(ssn, offset, toread, tempresponse, &tempresplen) == false) { PrintAndLogEx(NORMAL, ""); return false; } @@ -745,9 +619,9 @@ static bool emrtd_lds_get_data_by_tag(uint8_t *datain, size_t datainlen, uint8_t return false; } -static bool emrtd_select_and_read(uint8_t *dataout, size_t *dataoutlen, uint16_t file, uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, bool use_secure) { - if (use_secure) { - if (emrtd_secure_select_file_by_ef(ks_enc, ks_mac, ssc, file) == false) { +static bool emrtd_select_and_read(uint8_t *dataout, size_t *dataoutlen, uint16_t file, emrtd_session_t *ssn) { + if (ssn->type != EMRTD_SM_NONE) { + if (emrtd_secure_select_file_by_ef(ssn, file) == false) { PrintAndLogEx(ERR, "Failed to secure select %04X", file); return false; } @@ -758,7 +632,7 @@ static bool emrtd_select_and_read(uint8_t *dataout, size_t *dataoutlen, uint16_t } } - if (emrtd_read_file(dataout, dataoutlen, ks_enc, ks_mac, ssc, use_secure) == false) { + if (emrtd_read_file(dataout, dataoutlen, ssn) == false) { PrintAndLogEx(ERR, "Failed to read %04X", file); return false; } @@ -899,14 +773,7 @@ static int emrtd_dump_ef_sod(uint8_t *file_contents, size_t file_length, const c return PM3_ESOFT; } -static bool emrtd_dump_file(uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, uint16_t file, const char *name, bool use_secure, const char *path) { - uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; - size_t resplen = 0; - - if (emrtd_select_and_read(response, &resplen, file, ks_enc, ks_mac, ssc, use_secure) == false) { - return false; - } - +static bool emrtd_save_file(uint8_t *response, size_t resplen, uint16_t file, const char *name, const char *path) { char *filepath = calloc(strlen(path) + 100, sizeof(char)); if (filepath == NULL) { PrintAndLogEx(WARNING, "Failed to allocate memory"); @@ -933,15 +800,28 @@ static bool emrtd_dump_file(uint8_t *ks_enc, uint8_t *ks_mac, uint8_t *ssc, uint return true; } -static void rng(int length, uint8_t *dataout) { - // Do very very secure prng operations - //for (int i = 0; i < (length / 4); i++) { - // num_to_bytes(prng_successor(msclock() + i, 32), 4, &dataout[i * 4]); - //} - memset(dataout, 0x00, length); +static bool emrtd_dump_file(emrtd_session_t *ssn, uint16_t file, const char *name, const char *path) { + uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; + size_t resplen = 0; + + if (emrtd_select_and_read(response, &resplen, file, ssn) == false) { + return false; + } + + return emrtd_save_file(response, resplen, file, name, path); } -static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t *ssc, uint8_t *ks_enc, uint8_t *ks_mac) { +static void rng(int length, uint8_t *dataout) { + // Zero nonces are fatal for PACE and were never a good idea for BAC either, + // so this is a real CSPRNG (mbedtls CTR_DRBG seeded from mbedtls entropy). + if (pcrypto_rng_fill_oneshot(dataout, length, "emrtd") != PM3_SUCCESS) { + // Never hand back a predictable nonce, the caller has to fail instead + memset(dataout, 0x00, length); + PrintAndLogEx(ERR, "Failed to generate random data"); + } +} + +static bool emrtd_do_bac(const char *documentnumber, const char *dob, const char *expiry, emrtd_session_t *ssn) { uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; size_t resplen = 0; @@ -951,7 +831,8 @@ static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t uint8_t k_icc[16] = { 0x00 }; uint8_t S[32] = { 0x00 }; - uint8_t rnd_ifd[8], k_ifd[16]; + uint8_t rnd_ifd[8] = { 0x00 }; + uint8_t k_ifd[16] = { 0x00 }; rng(8, rnd_ifd); rng(16, k_ifd); @@ -959,12 +840,11 @@ static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t PrintAndLogEx(DEBUG, "dob............... " _GREEN_("%s"), dob); PrintAndLogEx(DEBUG, "exp............... " _GREEN_("%s"), expiry); - char documentnumbercd = emrtd_calculate_check_digit(documentnumber); - char dobcd = emrtd_calculate_check_digit(dob); - char expirycd = emrtd_calculate_check_digit(expiry); - char kmrz[25] = { 0x00 }; - snprintf(kmrz, sizeof(kmrz), "%s%i%s%i%s%i", documentnumber, documentnumbercd, dob, dobcd, expiry, expirycd); + if (emrtd_pace_kmrz(documentnumber, dob, expiry, kmrz, sizeof(kmrz)) != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Couldn't build the MRZ information string."); + return false; + } PrintAndLogEx(DEBUG, "kmrz.............. " _GREEN_("%s"), kmrz); uint8_t kseed[20] = { 0x00 }; @@ -992,12 +872,12 @@ static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t uint8_t iv[8] = { 0x00 }; uint8_t e_ifd[32] = { 0x00 }; - des3_encrypt_cbc(iv, kenc, S, sizeof(S), e_ifd); + emrtd_des3_encrypt_cbc(iv, kenc, S, sizeof(S), e_ifd); PrintAndLogEx(DEBUG, "e_ifd............. %s", sprint_hex_inrow(e_ifd, 32)); uint8_t m_ifd[8] = { 0x00 }; - retail_mac(kmac, e_ifd, 32, m_ifd); + emrtd_retail_mac(kmac, e_ifd, 32, m_ifd); PrintAndLogEx(DEBUG, "m_ifd............. %s", sprint_hex_inrow(m_ifd, 8)); uint8_t cmd_data[40]; @@ -1012,7 +892,7 @@ static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t PrintAndLogEx(INFO, "External authentication with BAC successful"); uint8_t dec_output[32] = { 0x00 }; - des3_decrypt_cbc(iv, kenc, response, 32, dec_output); + emrtd_des3_decrypt_cbc(iv, kenc, response, 32, dec_output); PrintAndLogEx(DEBUG, "dec_output........ %s", sprint_hex_inrow(dec_output, 32)); if (memcmp(rnd_ifd, dec_output + 8, 8) != 0) { @@ -1029,16 +909,22 @@ static bool emrtd_do_bac(char *documentnumber, char *dob, char *expiry, uint8_t PrintAndLogEx(DEBUG, "kseed............ %s", sprint_hex_inrow(kseed, 16)); + uint8_t ks_enc[EMRTD_KMAC_LEN] = { 0x00 }; + uint8_t ks_mac[EMRTD_KMAC_LEN] = { 0x00 }; emrtd_deskey(kseed, KENC_type, 16, ks_enc); emrtd_deskey(kseed, KMAC_type, 16, ks_mac); PrintAndLogEx(DEBUG, "ks_enc........ %s", sprint_hex_inrow(ks_enc, 16)); PrintAndLogEx(DEBUG, "ks_mac........ %s", sprint_hex_inrow(ks_mac, 16)); - memcpy(ssc, rnd_ic + 4, 4); - memcpy(ssc + 4, rnd_ifd + 4, 4); + if (emrtd_sm_setup(ssn, EMRTD_PACE_CIPHER_3DES, ks_enc, ks_mac) != PM3_SUCCESS) { + return false; + } - PrintAndLogEx(DEBUG, "ssc........... %s", sprint_hex_inrow(ssc, 8)); + memcpy(ssn->ssc, rnd_ic + 4, 4); + memcpy(ssn->ssc + 4, rnd_ifd + 4, 4); + + PrintAndLogEx(DEBUG, "ssc........... %s", sprint_hex_inrow(ssn->ssc, ssn->ssclen)); return true; } @@ -1048,10 +934,627 @@ static bool emrtd_connect(void) { return res == PM3_SUCCESS; } -static bool emrtd_do_auth(char *documentnumber, char *dob, char *expiry, bool BAC_available, bool *BAC, uint8_t *ssc, uint8_t *ks_enc, uint8_t *ks_mac) { +//----------------------------------------------------------------------------- +// PACE, ICAO 9303-11 4.4 and TR-03110 part 3, 3.2 +//----------------------------------------------------------------------------- + +#define EMRTD_INS_MSE 0x22 +#define EMRTD_INS_GENERAL_AUTHENTICATE 0x86 + +#define EMRTD_PACE_PWD_MRZ 0x01 +#define EMRTD_PACE_PWD_CAN 0x02 + +// Like emrtd_exchange_commands(), but hands the status word back so that the +// caller can report the 63CX retry counter of a wrong PACE password. +static bool emrtd_exchange_commands_sw(sAPDU_t apdu, bool include_le, uint16_t le, uint8_t *dataout, + size_t maxdataoutlen, size_t *dataoutlen, uint16_t *sw) { + uint16_t lsw = 0; + int res = Iso7816ExchangeEx(CC_CONTACTLESS, false, true, apdu, include_le, le, dataout, maxdataoutlen, dataoutlen, &lsw); + + *sw = lsw; + + if ((res != PM3_SUCCESS) && (lsw == 0)) { + return false; + } + + if (lsw != ISO7816_OK) { + PrintAndLogEx(DEBUG, "Command failed (%04x - %s).", lsw, GetAPDUCodeDescription(lsw >> 8, lsw & 0xff)); + return false; + } + return true; +} + +static bool emrtd_secure_select(emrtd_session_t *ssn, uint8_t p1, const uint8_t *sel, size_t sellen) { + uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 }; + size_t resplen = 0; + + size_t blocksize = emrtd_sm_blocksize(ssn); + const uint8_t header[4] = {0x0C, ISO7816_SELECT_FILE, p1, 0x0C}; + + uint8_t plain[EMRTD_SM_MAX_BLOCK_LEN * 2] = { 0x00 }; + if ((sellen + 1) > sizeof(plain)) { + return false; + } + size_t plainlen = emrtd_pad_block(sel, sellen, blocksize, plain); + + // the AES IV depends on the SSC, so it has to be bumped before encrypting + emrtd_sm_bump_ssc(ssn); + + uint8_t cryptogram[sizeof(plain)] = { 0x00 }; + if (emrtd_sm_encrypt(ssn, plain, plainlen, cryptogram) != PM3_SUCCESS) { + return false; + } + + uint8_t do87[sizeof(plain) + 3] = {0x87, 0x00, 0x01}; + do87[1] = (uint8_t)(plainlen + 1); + memcpy(do87 + 3, cryptogram, plainlen); + PrintAndLogEx(DEBUG, "do87: %s", sprint_hex_inrow(do87, plainlen + 3)); + + uint8_t data[sizeof(do87) + 16] = { 0x00 }; + size_t lc = 0; + if (emrtd_sm_finish_command(ssn, header, do87, plainlen + 3, data, sizeof(data), &lc) == false) { + return false; + } + + uint16_t sw = 0; + if (emrtd_exchange_commands_sw((sAPDU_t) {0x0C, ISO7816_SELECT_FILE, p1, 0x0C, lc, data}, true, 0, response, sizeof(response), &resplen, &sw) == false) { + if (sw != 0) { + PrintAndLogEx(ERR, "Secure select rejected by the document (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } else { + PrintAndLogEx(ERR, "Secure select got no response"); + } + return false; + } + + if (emrtd_check_cc(ssn, response, resplen) == false) { + PrintAndLogEx(ERR, "Secure select response failed the MAC check"); + PrintAndLogEx(ERR, "response.......... %s", sprint_hex_inrow(response, resplen)); + return false; + } + return true; +} + +// MSE:Set AT, ICAO 9303-11 4.4.4.1 +static bool emrtd_mse_set_at(const emrtd_paceinfo_t *info, uint8_t password_ref) { + uint8_t data[32] = { 0x00 }; + size_t o = 0; + + data[o++] = 0x80; + data[o++] = (uint8_t)info->oidlen; + memcpy(data + o, info->oid, info->oidlen); + o += info->oidlen; + + data[o++] = 0x83; + data[o++] = 0x01; + data[o++] = password_ref; + + if (info->has_param) { + data[o++] = 0x84; + data[o++] = 0x01; + data[o++] = info->param_id; + } + + PrintAndLogEx(DEBUG, "MSE:Set AT........ %s", sprint_hex_inrow(data, o)); + + uint8_t response[16] = { 0x00 }; + size_t resplen = 0; + uint16_t sw = 0; + + if (emrtd_exchange_commands_sw((sAPDU_t) {0x00, EMRTD_INS_MSE, 0xC1, 0xA4, o, data}, false, 0, response, sizeof(response), &resplen, &sw)) { + return true; + } + + if ((sw & 0xFFF0) == 0x63C0) { + PrintAndLogEx(ERR, "PACE: wrong password, " _RED_("%i") " attempt(s) left before the password is blocked", sw & 0x000F); + } else if (sw == 0x6A80) { + PrintAndLogEx(ERR, "PACE: the document rejected the algorithm we selected (6A80)"); + } else if (sw != 0) { + PrintAndLogEx(ERR, "PACE: MSE:Set AT failed (%04X - %s)", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } else { + PrintAndLogEx(ERR, "PACE: MSE:Set AT got no response"); + } + return false; +} + +// One step of the GENERAL AUTHENTICATE chain. inner_tag 0 sends an empty 7C. +// Pulls one data object out of the dynamic authentication data of a response +static bool emrtd_ga_get(const uint8_t *dyn, size_t dynlen, uint8_t wanted, + uint8_t *out, size_t maxout, size_t *outlen) { + const uint8_t *cur = dyn; + const uint8_t *end = dyn + dynlen; + uint32_t tag = 0; + const uint8_t *val = NULL; + size_t vlen = 0; + + while (emrtd_tlv_next(&cur, end, &tag, &val, &vlen)) { + if (tag != wanted) { + continue; + } + if (vlen > maxout) { + PrintAndLogEx(ERR, "PACE: response object %02X is too large (%zu bytes)", wanted, vlen); + return false; + } + memcpy(out, val, vlen); + *outlen = vlen; + return true; + } + return false; +} + +// Runs one step of the chain and hands back the content of the response's 7C +static bool emrtd_general_authenticate(const char *step, bool more, uint8_t inner_tag, const uint8_t *payload, size_t payloadlen, + uint8_t *out, size_t maxout, size_t *outlen) { + uint8_t inner[EMRTD_EC_POINT_MAXLEN + 8] = { 0x00 }; + size_t innerlen = 0; + + if (inner_tag != 0) { + innerlen = emrtd_tlv_write_header(inner, sizeof(inner), inner_tag, payloadlen); + if ((innerlen == 0) || ((innerlen + payloadlen) > sizeof(inner))) { + PrintAndLogEx(ERR, "PACE: general authenticate payload out-of-bounds"); + return false; + } + memcpy(inner + innerlen, payload, payloadlen); + innerlen += payloadlen; + } + + uint8_t data[sizeof(inner) + 8] = { 0x00 }; + size_t datalen = emrtd_tlv_write_header(data, sizeof(data), 0x7C, innerlen); + if (datalen == 0) { + return false; + } + memcpy(data + datalen, inner, innerlen); + datalen += innerlen; + + if (datalen > 0xFF) { + PrintAndLogEx(ERR, "PACE: general authenticate command too long for a short APDU"); + return false; + } + + PrintAndLogEx(DEBUG, "GA >>............. %s", sprint_hex_inrow(data, datalen)); + + uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 }; + size_t resplen = 0; + uint16_t sw = 0; + + // CLA 0x10 marks every step of the chain except the last one + uint8_t cla = more ? 0x10 : 0x00; + + if (emrtd_exchange_commands_sw((sAPDU_t) {cla, EMRTD_INS_GENERAL_AUTHENTICATE, 0x00, 0x00, datalen, data}, true, 0, response, sizeof(response), &resplen, &sw) == false) { + if ((sw & 0xFFF0) == 0x63C0) { + PrintAndLogEx(ERR, "PACE: wrong password, " _RED_("%i") " attempt(s) left before the password is blocked", sw & 0x000F); + } else if (sw == 0x6300) { + // no counter given, but at the mutual authentication step this can + // only mean our token did not match, i.e. the password is wrong + PrintAndLogEx(ERR, "PACE: %s failed (6300), the document rejected it", step); + } else if (sw != 0) { + PrintAndLogEx(ERR, "PACE: %s failed (%04X - %s)", step, sw, GetAPDUCodeDescription(sw >> 8, sw & 0xFF)); + } else { + PrintAndLogEx(ERR, "PACE: %s got no response", step); + } + return false; + } + + PrintAndLogEx(DEBUG, "GA <<............. %s", sprint_hex_inrow(response, resplen)); + + const uint8_t *cur = response; + const uint8_t *end = response + resplen; + uint32_t tag = 0; + const uint8_t *val = NULL; + size_t vlen = 0; + + if ((emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) || (tag != 0x7C)) { + PrintAndLogEx(ERR, "PACE: %s returned malformed dynamic authentication data", step); + return false; + } + + if (vlen > maxout) { + PrintAndLogEx(ERR, "PACE: %s response is too large (%zu bytes)", step, vlen); + return false; + } + + memcpy(out, val, vlen); + *outlen = vlen; + return true; +} + +// Runs one step and picks a single expected data object out of the response +static bool emrtd_general_authenticate_one(const char *step, bool more, uint8_t inner_tag, + const uint8_t *payload, size_t payloadlen, + uint8_t expect_tag, uint8_t *out, size_t maxout, size_t *outlen) { + uint8_t dyn[PM3_CMD_DATA_SIZE] = { 0x00 }; + size_t dynlen = 0; + + if (emrtd_general_authenticate(step, more, inner_tag, payload, payloadlen, dyn, sizeof(dyn), &dynlen) == false) { + return false; + } + + if (emrtd_ga_get(dyn, dynlen, expect_tag, out, maxout, outlen) == false) { + PrintAndLogEx(ERR, "PACE: %s response is missing data object %02X", step, expect_tag); + return false; + } + return true; +} + +static int emrtd_do_pace(const emrtd_paceinfo_t *info, const uint8_t *password, size_t passwordlen, + uint8_t password_ref, emrtd_session_t *ssn) { + const emrtd_pacealg_t *alg = info->alg; + mbedtls_ecp_group_id curve = info->sdp->curve; + + uint8_t kpi[EMRTD_SM_MAX_KEY_LEN] = { 0x00 }; + size_t kpilen = 0; + + // Kpi = KDF(K, 3) + if (emrtd_pace_kdf(alg->cipher, password, passwordlen, 3, kpi, &kpilen) != PM3_SUCCESS) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "kpi............... %s", sprint_hex_inrow(kpi, kpilen)); + + if (emrtd_mse_set_at(info, password_ref) == false) { + return PM3_ESOFT; + } + + uint8_t response[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t resplen = 0; + + // Step 1, encrypted nonce + if (emrtd_general_authenticate_one("step 1 (encrypted nonce)", true, 0x00, NULL, 0, 0x80, response, sizeof(response), &resplen) == false) { + return PM3_ESOFT; + } + + uint8_t s[32] = { 0x00 }; + if (emrtd_pace_decrypt_nonce(alg->cipher, kpi, response, resplen, s) != PM3_SUCCESS) { + return PM3_ESOFT; + } + size_t slen = resplen; + PrintAndLogEx(DEBUG, "nonce s........... %s", sprint_hex_inrow(s, slen)); + + // Step 2, map the nonce + uint8_t priv1[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + uint8_t pub1[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t priv1len = 0, pub1len = 0; + + if (emrtd_pace_ec_keygen(curve, NULL, 0, priv1, &priv1len, pub1, &pub1len) != PM3_SUCCESS) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "PK.Map.IFD........ %s", sprint_hex_inrow(pub1, pub1len)); + + if (emrtd_general_authenticate_one("step 2 (map nonce)", true, 0x81, pub1, pub1len, 0x82, response, sizeof(response), &resplen) == false) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "PK.Map.IC......... %s", sprint_hex_inrow(response, resplen)); + + // Chip Authentication Mapping proves this key belongs to the chip's static + // CA key, which can only be checked once EF_DG14 is readable + if (alg->mapping == EMRTD_PACE_MAP_CAM) { + ssn->cam.negotiated = true; + ssn->cam.curve = curve; + memcpy(ssn->cam.pk_map_ic, response, resplen); + ssn->cam.pk_map_iclen = resplen; + // the terminal half of the Chip Authentication ECDH + memcpy(ssn->cam.sk_map_ifd, priv1, priv1len); + ssn->cam.sk_map_ifdlen = priv1len; + } + + uint8_t mapped[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t mappedlen = 0; + if (emrtd_pace_ec_gm(curve, s, slen, priv1, priv1len, response, resplen, mapped, &mappedlen) != PM3_SUCCESS) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "mapped generator.. %s", sprint_hex_inrow(mapped, mappedlen)); + + // Step 3, key agreement over the mapped generator + uint8_t priv2[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + uint8_t pub2[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t priv2len = 0, pub2len = 0; + + if (emrtd_pace_ec_keygen(curve, mapped, mappedlen, priv2, &priv2len, pub2, &pub2len) != PM3_SUCCESS) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "PK.DH.IFD......... %s", sprint_hex_inrow(pub2, pub2len)); + + if (ssn->cam.negotiated) { + memcpy(ssn->cam.sk_dh_ifd, priv2, priv2len); + ssn->cam.sk_dh_ifdlen = priv2len; + } + + uint8_t pk2_ic[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t pk2_iclen = 0; + if (emrtd_general_authenticate_one("step 3 (key agreement)", true, 0x83, pub2, pub2len, 0x84, pk2_ic, sizeof(pk2_ic), &pk2_iclen) == false) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "PK.DH.IC.......... %s", sprint_hex_inrow(pk2_ic, pk2_iclen)); + + if (ssn->cam.negotiated) { + memcpy(ssn->cam.pk_dh_ic, pk2_ic, pk2_iclen); + ssn->cam.pk_dh_iclen = pk2_iclen; + } + + // ICAO 9303-11 4.4.3.3, the two ephemeral keys must differ + if ((pk2_iclen == pub2len) && (memcmp(pk2_ic, pub2, pub2len) == 0)) { + PrintAndLogEx(ERR, "PACE: the document echoed our ephemeral public key back, aborting"); + return PM3_ESOFT; + } + + uint8_t shared[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + size_t sharedlen = 0; + if (emrtd_pace_ec_shared_x(curve, priv2, priv2len, pk2_ic, pk2_iclen, shared, &sharedlen) != PM3_SUCCESS) { + return PM3_ESOFT; + } + + // Step 4, session keys and mutual authentication tokens + uint8_t ks_enc[EMRTD_SM_MAX_KEY_LEN] = { 0x00 }; + uint8_t ks_mac[EMRTD_SM_MAX_KEY_LEN] = { 0x00 }; + size_t kslen = 0; + + if ((emrtd_pace_kdf(alg->cipher, shared, sharedlen, 1, ks_enc, &kslen) != PM3_SUCCESS) || + (emrtd_pace_kdf(alg->cipher, shared, sharedlen, 2, ks_mac, &kslen) != PM3_SUCCESS)) { + return PM3_ESOFT; + } + PrintAndLogEx(DEBUG, "ks_enc............ %s", sprint_hex_inrow(ks_enc, kslen)); + PrintAndLogEx(DEBUG, "ks_mac............ %s", sprint_hex_inrow(ks_mac, kslen)); + + uint8_t t_ifd[8] = { 0x00 }; + if (emrtd_pace_token(alg, ks_mac, pk2_ic, pk2_iclen, t_ifd) != PM3_SUCCESS) { + return PM3_ESOFT; + } + + uint8_t dyn[PM3_CMD_DATA_SIZE] = { 0x00 }; + size_t dynlen = 0; + if (emrtd_general_authenticate("step 4 (mutual authentication)", false, 0x85, t_ifd, sizeof(t_ifd), dyn, sizeof(dyn), &dynlen) == false) { + return PM3_ESOFT; + } + + uint8_t t_ic[8] = { 0x00 }; + size_t t_iclen = 0; + if (emrtd_ga_get(dyn, dynlen, 0x86, t_ic, sizeof(t_ic), &t_iclen) == false) { + PrintAndLogEx(ERR, "PACE: step 4 (mutual authentication) response is missing data object 86"); + return PM3_ESOFT; + } + + if (ssn->cam.negotiated) { + // DO'8A', TR-03110 part 3, 3.4.4 + if (emrtd_ga_get(dyn, dynlen, 0x8A, ssn->cam.enc_data, sizeof(ssn->cam.enc_data), &ssn->cam.enc_datalen) == false) { + PrintAndLogEx(WARNING, "PACE-CAM: the document returned no encrypted chip authentication data"); + ssn->cam.negotiated = false; + } else { + PrintAndLogEx(DEBUG, "CAM data.......... %s", sprint_hex_inrow(ssn->cam.enc_data, ssn->cam.enc_datalen)); + } + } + + uint8_t t_ic_expected[8] = { 0x00 }; + if (emrtd_pace_token(alg, ks_mac, pub2, pub2len, t_ic_expected) != PM3_SUCCESS) { + return PM3_ESOFT; + } + + if ((t_iclen != sizeof(t_ic_expected)) || (memcmp(t_ic, t_ic_expected, sizeof(t_ic_expected)) != 0)) { + PrintAndLogEx(ERR, "PACE: the document's authentication token is wrong, aborting"); + PrintAndLogEx(DEBUG, "T_IC got.......... %s", sprint_hex_inrow(t_ic, t_iclen)); + PrintAndLogEx(DEBUG, "T_IC expected..... %s", sprint_hex_inrow(t_ic_expected, sizeof(t_ic_expected))); + return PM3_ESOFT; + } + + if (emrtd_sm_setup(ssn, alg->cipher, ks_enc, ks_mac) != PM3_SUCCESS) { + return PM3_ESOFT; + } + + // SSC starts at zero after PACE, ICAO 9303-11 9.8.6.3 + ssn->pace = true; + ssn->pace_alg = alg->name; + ssn->pace_curve = info->sdp->name; + + PrintAndLogEx(INFO, "Authentication with PACE successful ( " _GREEN_("%s") ", %s )", alg->name, info->sdp->name); + return PM3_SUCCESS; +} + +// Picks the PACE password out of what the user supplied +static int emrtd_pace_password(const emrtd_auth_t *auth, uint8_t *k, size_t *klen, uint8_t *password_ref) { + if (auth->can_available) { + if (emrtd_pace_password_can(auth->can, k, klen) != PM3_SUCCESS) { + PrintAndLogEx(ERR, "PACE: invalid CAN"); + return PM3_EINVARG; + } + *password_ref = EMRTD_PACE_PWD_CAN; + return PM3_SUCCESS; + } + + if (auth->mrz_available) { + if (emrtd_pace_password_mrz(auth->documentnumber, auth->dob, auth->expiry, k, klen) != PM3_SUCCESS) { + PrintAndLogEx(ERR, "PACE: invalid MRZ data"); + return PM3_EINVARG; + } + *password_ref = EMRTD_PACE_PWD_MRZ; + return PM3_SUCCESS; + } + + PrintAndLogEx(ERR, "PACE needs a password, supply `" _YELLOW_("--can") "` or `" _YELLOW_("-n") "` `" _YELLOW_("-d") "` `" _YELLOW_("-e") "`"); + return PM3_EINVARG; +} + +// Orders every usable SecurityInfo strongest first, returns how many there are +static size_t emrtd_pace_candidates(const emrtd_cardaccess_t *ca, size_t *order, size_t maxorder) { + size_t count = 0; + + for (size_t i = 0; i < ca->count; i++) { + + if (emrtd_pace_rank(&ca->infos[i]) <= 0) { + continue; + } + + if (count >= maxorder) { + break; + } + + // insertion sort, the list is never longer than EMRTD_PACE_MAX_INFOS + size_t pos = count; + while ((pos > 0) && (emrtd_pace_rank(&ca->infos[order[pos - 1]]) < emrtd_pace_rank(&ca->infos[i]))) { + order[pos] = order[pos - 1]; + pos--; + } + order[pos] = i; + count++; + } + + return count; +} + +// Reads EF_DG14 over the freshly established session and checks the chip's +// Chip Authentication Mapping proof against the key it publishes there. +// +// Note: while no encoding of DO'8A' has been confirmed against real hardware, a +// check that does not come out is reported as "unverified" rather than as a +// failure, because our own support is the far likelier culprit. Once a document +// verifies, drop the probing in emrtd_pace_cam_verify(), keep only the encoding +// that worked, and make a mismatch loud again: at that point it means a clone. +static void emrtd_check_cam(emrtd_session_t *ssn) { + uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; + size_t resplen = 0; + + PrintAndLogEx(INFO, "Verifying Chip Authentication Mapping"); + + if (emrtd_select_and_read(response, &resplen, dg_table[EF_DG14].fileid, ssn) == false) { + PrintAndLogEx(WARNING, "Chip Authentication.. " _YELLOW_("unverified") " ( couldn't read EF_DG14 )"); + return; + } + + uint8_t pk_icc[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t pk_icclen = 0; + size_t expected = emrtd_pace_ec_pointlen(ssn->cam.curve); + bool found_any = false; + + // a document may publish more than one chip authentication key + for (size_t i = 0; i < EMRTD_PACE_MAX_INFOS; i++) { + + if (emrtd_pace_find_ca_pubkey(response, resplen, i, pk_icc, &pk_icclen) != PM3_SUCCESS) { + break; + } + + found_any = true; + PrintAndLogEx(DEBUG, "PK.CA.IC[%zu]....... %s", i, sprint_hex_inrow(pk_icc, pk_icclen)); + + if (pk_icclen != expected) { + PrintAndLogEx(DEBUG, "CAM: key %zu is %zu bytes, the PACE curve needs %zu, skipping", i, pk_icclen, expected); + continue; + } + + const char *mode = NULL; + if (emrtd_pace_cam_verify(ssn, pk_icc, pk_icclen, &mode) == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "Chip Authentication.. " _GREEN_("verified") " ( the chip is genuine, not a clone )"); + PrintAndLogEx(INFO, "CAM encoding...... %s", mode); + return; + } + } + + if (found_any == false) { + PrintAndLogEx(WARNING, "Chip Authentication.. " _YELLOW_("unverified") " ( no EC chip authentication key in EF_DG14 )"); + return; + } + + PrintAndLogEx(WARNING, "Chip Authentication.. " _YELLOW_("not verified") " ( we cannot check this document's CAM proof )"); + PrintAndLogEx(HINT, "Hint: the secure channel is valid and every file is authentic. Only the anti-clone"); + PrintAndLogEx(HINT, "Hint: proof is unchecked, which is a known gap, not a sign of a bad document"); + PrintAndLogEx(HINT, "Hint: if you want to help close it, please report everything below"); + emrtd_pace_cam_dump(ssn, pk_icc, pk_icclen); +} + +static bool emrtd_do_auth(const emrtd_auth_t *auth, const emrtd_cardaccess_t *ca, bool ca_valid, + bool *BAC, emrtd_session_t *ssn) { + uint8_t aid[] = EMRTD_AID_MRTD; + + *BAC = false; + + //------------------------------------------------------------------------- + // PACE. EF_CardAccess lives on the MF, so this runs before the LDS applet + // is selected. On success the applet is selected under secure messaging. + //------------------------------------------------------------------------- + bool try_pace = (auth->force_bac == false) && ca_valid; + + if (auth->force_pace && (ca_valid == false)) { + PrintAndLogEx(ERR, "PACE was forced but this document has no usable EF_CardAccess."); + return false; + } + + if (try_pace) { + + size_t order[EMRTD_PACE_MAX_INFOS] = { 0 }; + size_t candidates = emrtd_pace_candidates(ca, order, ARRAYLEN(order)); + + uint8_t k[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + size_t klen = 0; + uint8_t password_ref = 0; + + if (candidates == 0) { + PrintAndLogEx(ERR, "PACE: this document offers no algorithm we can do"); + for (size_t i = 0; i < ca->count; i++) { + if (ca->infos[i].reason != NULL) { + PrintAndLogEx(ERR, " %s: %s", + (ca->infos[i].alg != NULL) ? ca->infos[i].alg->name : "unknown protocol", + ca->infos[i].reason); + } + } + } + + if ((candidates != 0) && (emrtd_pace_password(auth, k, &klen, &password_ref) == PM3_SUCCESS)) { + + PrintAndLogEx(INFO, "Trying PACE with the %s", (password_ref == EMRTD_PACE_PWD_CAN) ? "CAN" : "MRZ"); + + // strongest first, and drop down a rung if the document does not + // actually honour what it advertised + for (size_t i = 0; i < candidates; i++) { + + const emrtd_paceinfo_t *info = &ca->infos[order[i]]; + + if (i != 0) { + PrintAndLogEx(INFO, "Retrying with " _YELLOW_("%s"), info->alg->name); + DropField(); + msleep(50); + if (emrtd_connect() == false) { + PrintAndLogEx(ERR, "Couldn't reconnect to the document."); + return false; + } + } + + if (emrtd_do_pace(info, k, klen, password_ref, ssn) != PM3_SUCCESS) { + emrtd_sm_clear(ssn); + continue; + } + + if (emrtd_secure_select(ssn, EMRTD_P1_SELECT_BY_NAME, aid, sizeof(aid)) == false) { + PrintAndLogEx(ERR, "Couldn't select the MRTD application over PACE."); + emrtd_sm_clear(ssn); + continue; + } + + if (ssn->cam.negotiated) { + emrtd_check_cam(ssn); + } + + *BAC = true; + return true; + } + } + + emrtd_sm_clear(ssn); + + if (auth->force_pace) { + PrintAndLogEx(ERR, "PACE was forced, not falling back to BAC."); + return false; + } + + PrintAndLogEx(INFO, "PACE failed, falling back to BAC"); + // the document is in an undefined state after a failed PACE run + DropField(); + msleep(50); + if (emrtd_connect() == false) { + PrintAndLogEx(ERR, "Couldn't reconnect to the document."); + return false; + } + } + + //------------------------------------------------------------------------- + // BAC + //------------------------------------------------------------------------- // Select MRTD applet - uint8_t aid[] = EMRTD_AID_MRTD; if (emrtd_select_file_by_name(sizeof(aid), aid) == false) { PrintAndLogEx(ERR, "Couldn't select the MRTD application."); return false; @@ -1069,7 +1572,9 @@ static bool emrtd_do_auth(char *documentnumber, char *dob, char *expiry, bool BA size_t resplen = 0; uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; - if (emrtd_read_file(response, &resplen, NULL, NULL, NULL, false) == false) { + emrtd_session_t plain; + emrtd_sm_clear(&plain); + if (emrtd_read_file(response, &resplen, &plain) == false) { *BAC = true; PrintAndLogEx(INFO, "Authentication is enforced"); PrintAndLogEx(INFO, "Switching to external authentication"); @@ -1081,47 +1586,58 @@ static bool emrtd_do_auth(char *documentnumber, char *dob, char *expiry, bool BA // Do Basic Access Control if (*BAC) { // If BAC isn't available, exit out and warn user. - if (BAC_available == false) { + if (auth->mrz_available == false) { PrintAndLogEx(ERR, "This eMRTD enforces authentication, but you didn't supply MRZ data. Cannot proceed."); PrintAndLogEx(HINT, "Hint: Check out `" _YELLOW_("hf emrtd info/dump --h") "`, supply data with `-n` `-d` and `-e`"); return false; } - if (emrtd_do_bac(documentnumber, dob, expiry, ssc, ks_enc, ks_mac) == false) { + if (emrtd_do_bac(auth->documentnumber, auth->dob, auth->expiry, ssn) == false) { return false; } } return true; } -int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available, const char *path) { +int dumpHF_EMRTD(const emrtd_auth_t *auth, const char *path) { uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; size_t resplen = 0; - uint8_t ssc[8] = { 0x00 }; - uint8_t ks_enc[EMRTD_KMAC_LEN] = { 0x00 }; - uint8_t ks_mac[EMRTD_KMAC_LEN] = { 0x00 }; + emrtd_session_t ssn; + emrtd_cardaccess_t ca; + bool ca_valid = false; bool BAC = false; + emrtd_sm_clear(&ssn); + memset(&ca, 0, sizeof(ca)); + ca.best = -1; + // Select the eMRTD if (emrtd_connect() == false) { DropField(); return PM3_ESOFT; } - // Dump EF_CardAccess (if available) - if (emrtd_dump_file(ks_enc, ks_mac, ssc, dg_table[EF_CardAccess].fileid, dg_table[EF_CardAccess].filename, BAC, path) == false) { - PrintAndLogEx(INFO, "Couldn't dump EF_CardAccess, card does not support PACE"); + // Read and dump EF_CardAccess (if available). This lives on the MF and is + // readable without authentication, so it has to happen before anything else. + if (emrtd_select_and_read(response, &resplen, dg_table[EF_CardAccess].fileid, &ssn) == false) { + PrintAndLogEx(INFO, "Couldn't read EF_CardAccess, card does not support PACE"); PrintAndLogEx(HINT, "Hint: This is expected behavior for cards without PACE and isn't something to be worried about"); + } else { + emrtd_save_file(response, resplen, dg_table[EF_CardAccess].fileid, dg_table[EF_CardAccess].filename, path); + ca_valid = (emrtd_pace_parse_cardaccess(response, resplen, &ca) == PM3_SUCCESS); + if (ca_valid == false) { + PrintAndLogEx(WARNING, "Couldn't parse EF_CardAccess, PACE is not available"); + } } // Authenticate with the eMRTD - if (emrtd_do_auth(documentnumber, dob, expiry, BAC_available, &BAC, ssc, ks_enc, ks_mac) == false) { + if (emrtd_do_auth(auth, &ca, ca_valid, &BAC, &ssn) == false) { DropField(); return PM3_ESOFT; } // Select EF_COM - if (emrtd_select_and_read(response, &resplen, dg_table[EF_COM].fileid, ks_enc, ks_mac, ssc, BAC) == false) { + if (emrtd_select_and_read(response, &resplen, dg_table[EF_COM].fileid, &ssn) == false) { PrintAndLogEx(ERR, "Failed to read EF_COM"); DropField(); return PM3_ESOFT; @@ -1164,8 +1680,10 @@ int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab continue; } PrintAndLogEx(DEBUG, "Current file... %s", dg->filename); - if (!dg->pace && !dg->eac) { - emrtd_dump_file(ks_enc, ks_mac, ssc, dg->fileid, dg->filename, BAC, path); + // dg->pace files are only reachable once a PACE session is up, dg->eac + // files need EAC which we do not implement at all + if ((!dg->pace || ssn.pace) && !dg->eac) { + emrtd_dump_file(&ssn, dg->fileid, dg->filename, path); } } DropField(); @@ -1893,7 +2411,13 @@ static int emrtd_print_ef_sod_info(uint8_t *dg_hashes_calc, uint8_t *dg_hashes_s if (calc_all_zero == true) { - if (fastdump && !dg_table[i].fastdump && !dg_table[i].pace && !dg_table[i].eac) { + if (dg_table[i].eac) { + // Terminal Authentication with a country signed inspection + // system certificate, which we neither have nor implement + PrintAndLogEx(SUCCESS, _YELLOW_("EF_DG%-2i") " %s%.*s " _YELLOW_("Needs EAC"), i, dg_table[i].desc, n, pad); + } else if (dg_table[i].pace) { + PrintAndLogEx(SUCCESS, _YELLOW_("EF_DG%-2i") " %s%.*s " _YELLOW_("Needs PACE"), i, dg_table[i].desc, n, pad); + } else if (fastdump && !dg_table[i].fastdump) { PrintAndLogEx(SUCCESS, _YELLOW_("EF_DG%-2i") " %s%.*s File was skipped, but is in EF_SOD", i, dg_table[i].desc, n, pad); } else { PrintAndLogEx(SUCCESS, _YELLOW_("EF_DG%-2i") " %s%.*s File couldn't be read, but is in EF_SOD", i, dg_table[i].desc, n, pad); @@ -1912,72 +2436,80 @@ static int emrtd_print_ef_sod_info(uint8_t *dg_hashes_calc, uint8_t *dg_hashes_s return PM3_SUCCESS; } -static int emrtd_print_ef_cardaccess_info(uint8_t *data, size_t datalen) { - uint8_t dataset[100] = { 0x00 }; - size_t datasetlen = 0; - uint8_t datafromtag[100] = { 0x00 }; - size_t datafromtaglen = 0; - uint8_t parsednum = 0; - +static void emrtd_print_cardaccess(const emrtd_cardaccess_t *ca) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "--------------------- " _CYAN_("EF_CardAccess") " --------------------"); - if (emrtd_lds_get_data_by_tag(data, datalen, dataset, &datasetlen, 0x30, 0x00, false, true, 0) == false) { - PrintAndLogEx(ERR, "Failed to read set from EF_CardAccess."); - return PM3_ESOFT; - } + for (size_t i = 0; i < ca->count; i++) { + const emrtd_paceinfo_t *info = &ca->infos[i]; - // Get PACE version - if (emrtd_lds_get_data_by_tag(dataset, datasetlen, datafromtag, &datafromtaglen, 0x02, 0x00, false, false, 0) == false) { - PrintAndLogEx(ERR, "Failed to read PACE version from EF_CardAccess."); - return PM3_ESOFT; - } - // TODO: hack!!! - memcpy(&parsednum, datafromtag, datafromtaglen); - PrintAndLogEx(SUCCESS, "PACE version............. " _YELLOW_("%i"), parsednum); + if (i != 0) { + PrintAndLogEx(SUCCESS, ""); + } - // Get PACE algorithm - if (emrtd_lds_get_data_by_tag(dataset, datasetlen, datafromtag, &datafromtaglen, 0x06, 0x00, false, false, 0) == false) { - PrintAndLogEx(ERR, "Failed to read PACE algorithm from EF_CardAccess."); - return PM3_ESOFT; - } + if (info->alg != NULL) { + PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("%s"), info->alg->name); + } else { + PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("unknown") " ( OID %s )", + sprint_hex_inrow((uint8_t *)info->oid, info->oidlen)); + } - for (int pacei = 0; pacealg_table[pacei].name != NULL; pacei++) { - PrintAndLogEx(DEBUG, "Trying: %s", pacealg_table[pacei].name); + if (info->version != 0) { + PrintAndLogEx(SUCCESS, "PACE version............. " _YELLOW_("%u"), info->version); + } - if (memcmp(pacealg_table[pacei].descriptor, datafromtag, datafromtaglen) == 0) { - PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("%s"), pacealg_table[pacei].name); + if (info->has_param) { + if (info->sdp != NULL) { + PrintAndLogEx(SUCCESS, "PACE parameter........... " _YELLOW_("%s") " ( id %u )", info->sdp->name, info->param_id); + } else { + // TR-03110 part 3, table A.2 leaves 3-7 and 19-31 reserved + PrintAndLogEx(SUCCESS, "PACE parameter........... " _YELLOW_("RFU / unknown") " ( id %u )", info->param_id); + } + } + + if (info->supported) { + PrintAndLogEx(SUCCESS, "Supported by this client. " _GREEN_("yes") + "%s", ((int)i == ca->best) ? _GREEN_(" (selected)") : ""); + } else { + PrintAndLogEx(SUCCESS, "Supported by this client. " _YELLOW_("no") " ( %s )", + (info->reason != NULL) ? info->reason : "unsupported"); } } - // Get PACE parameter ID - if (emrtd_lds_get_data_by_tag(dataset, datasetlen, datafromtag, &datafromtaglen, 0x02, 0x00, false, false, 1) == false) { - PrintAndLogEx(ERR, "Failed to read PACE parameter ID from EF_CardAccess."); - return PM3_ESOFT; + if (ca->best < 0) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(WARNING, "None of the offered PACE algorithms is supported by this client"); } +} - // TODO: hack!!! - memcpy(&parsednum, datafromtag, datafromtaglen); - for (int pacepari = 0; pacesdp_table[pacepari].id != 32; pacepari++) { - PrintAndLogEx(DEBUG, "Trying: %s", pacesdp_table[pacepari].name); +// dg_table parser entry point, used by the offline path +static int emrtd_print_ef_cardaccess_info(uint8_t *data, size_t datalen) { + emrtd_cardaccess_t ca; - if (pacesdp_table[pacepari].id == parsednum) { - PrintAndLogEx(SUCCESS, "PACE parameter........... " _YELLOW_("%s"), pacesdp_table[pacepari].name); - } - // TODO: account for RFU + int res = emrtd_pace_parse_cardaccess(data, datalen, &ca); + if (res != PM3_SUCCESS) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--------------------- " _CYAN_("EF_CardAccess") " --------------------"); + PrintAndLogEx(ERR, "Failed to parse EF_CardAccess."); + return res; } + emrtd_print_cardaccess(&ca); return PM3_SUCCESS; } -int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available, bool only_fast) { +int infoHF_EMRTD(const emrtd_auth_t *auth, bool only_fast) { uint8_t response[EMRTD_MAX_FILE_SIZE] = { 0x00 }; size_t resplen = 0; - uint8_t ssc[8] = { 0x00 }; - uint8_t ks_enc[16] = { 0x00 }; - uint8_t ks_mac[16] = { 0x00 }; - bool BAC = false; + emrtd_session_t ssn; + emrtd_cardaccess_t ca; + bool ca_valid = false; bool PACE_available = true; + bool BAC = false; + + emrtd_sm_clear(&ssn); + memset(&ca, 0, sizeof(ca)); + ca.best = -1; // Select the eMRTD if (emrtd_connect() == false) { @@ -1987,13 +2519,18 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab bool use14b = (GetISODEPState() == ISODEP_NFCB); // Read EF_CardAccess - if (emrtd_select_and_read(response, &resplen, dg_table[EF_CardAccess].fileid, ks_enc, ks_mac, ssc, BAC) == false) { + if (emrtd_select_and_read(response, &resplen, dg_table[EF_CardAccess].fileid, &ssn) == false) { PACE_available = false; PrintAndLogEx(HINT, "Hint: The error above this is normal. It just means that your eMRTD lacks PACE."); + } else { + ca_valid = (emrtd_pace_parse_cardaccess(response, resplen, &ca) == PM3_SUCCESS); + if (ca_valid == false) { + PrintAndLogEx(WARNING, "Couldn't parse EF_CardAccess, PACE is not available"); + } } // Select and authenticate with the eMRTD - bool auth_result = emrtd_do_auth(documentnumber, dob, expiry, BAC_available, &BAC, ssc, ks_enc, ks_mac); + bool auth_result = emrtd_do_auth(auth, &ca, ca_valid, &BAC, &ssn); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "---------------------- " _CYAN_("Basic Info") " ----------------------"); @@ -2002,8 +2539,18 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab PrintAndLogEx(SUCCESS, "PACE..................... %s", PACE_available ? _GREEN_("Available") : _YELLOW_("Not available")); PrintAndLogEx(SUCCESS, "Authentication result.... %s", auth_result ? _GREEN_("Successful") : _RED_("Failed")); - if (PACE_available) { - emrtd_print_ef_cardaccess_info(response, resplen); + if (auth_result) { + if (ssn.pace) { + PrintAndLogEx(SUCCESS, "Session.................. " _GREEN_("PACE") " ( %s, %s )", ssn.pace_alg, ssn.pace_curve); + } else if (ssn.type == EMRTD_SM_3DES) { + PrintAndLogEx(SUCCESS, "Session.................. " _GREEN_("BAC") " ( 3DES-CBC-CBC )"); + } else { + PrintAndLogEx(SUCCESS, "Session.................. " _YELLOW_("plain") " ( no secure messaging )"); + } + } + + if (ca_valid) { + emrtd_print_cardaccess(&ca); } if (auth_result == false) { @@ -2012,7 +2559,7 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab } // Read EF_COM to get file list - if (emrtd_select_and_read(response, &resplen, dg_table[EF_COM].fileid, ks_enc, ks_mac, ssc, BAC) == false) { + if (emrtd_select_and_read(response, &resplen, dg_table[EF_COM].fileid, &ssn) == false) { PrintAndLogEx(ERR, "Failed to read EF_COM"); DropField(); return PM3_ESOFT; @@ -2038,7 +2585,7 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab uint8_t dg_hashes_calc[17][64] = { { 0 } }; int hash_algo = 0; - if (!emrtd_select_and_read(response, &resplen, dg_table[EF_SOD].fileid, ks_enc, ks_mac, ssc, BAC)) { + if (!emrtd_select_and_read(response, &resplen, dg_table[EF_SOD].fileid, &ssn)) { PrintAndLogEx(ERR, "Failed to read EF_SOD."); DropField(); return PM3_ESOFT; @@ -2061,8 +2608,10 @@ int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_availab continue; } - if (((dg->fastdump && only_fast) || !only_fast) && !dg->pace && !dg->eac) { - if (emrtd_select_and_read(response, &resplen, dg->fileid, ks_enc, ks_mac, ssc, BAC)) { + // dg->pace files are only reachable once a PACE session is up, dg->eac + // files need EAC which we do not implement at all + if (((dg->fastdump && only_fast) || !only_fast) && (!dg->pace || ssn.pace) && !dg->eac) { + if (emrtd_select_and_read(response, &resplen, dg->fileid, &ssn)) { if (dg->parser != NULL) dg->parser(response, resplen); @@ -2217,13 +2766,74 @@ static bool validate_date(uint8_t *data, int datalen) { return !(day <= 0 || day > 31 || month <= 0 || month > 12); } +static bool emrtd_validate_can(const char *can, int canlen) { + if ((canlen < 1) || (canlen > 14)) { + PrintAndLogEx(ERR, "CAN length is incorrect, it should be 1 to 14 chars, not %i", canlen); + return false; + } + + for (int i = 0; i < canlen; i++) { + if (isdigit((unsigned char)can[i]) == false) { + PrintAndLogEx(ERR, "CAN has to be numeric."); + return false; + } + } + + if (canlen != 6) { + PrintAndLogEx(WARNING, "CAN is usually 6 digits, yours is %i. Continuing anyway.", canlen); + } + return true; +} + +static bool emrtd_check_auth_args(bool mrz, bool can, bool force_pace, bool force_bac) { + if (mrz && can) { + PrintAndLogEx(ERR, "`" _YELLOW_("--can") "` and the MRZ arguments are mutually exclusive as PACE passwords."); + PrintAndLogEx(HINT, "Hint: pick one, the CAN with `" _YELLOW_("--can") "` or the MRZ with `" _YELLOW_("-n") "` `" _YELLOW_("-d") "` `" _YELLOW_("-e") "`"); + return false; + } + + if (force_pace && force_bac) { + PrintAndLogEx(ERR, "`" _YELLOW_("--pace") "` and `" _YELLOW_("--bac") "` are mutually exclusive."); + return false; + } + + if (force_bac && can && (mrz == false)) { + PrintAndLogEx(ERR, "BAC needs MRZ data, the CAN is a PACE only password."); + return false; + } + + if (force_pace && (mrz == false) && (can == false)) { + PrintAndLogEx(ERR, "PACE needs a password, supply `" _YELLOW_("--can") "` or `" _YELLOW_("-n") "` `" _YELLOW_("-d") "` `" _YELLOW_("-e") "`"); + return false; + } + + return true; +} + +static void emrtd_fill_auth(emrtd_auth_t *auth, const char *docnum, const char *dob, const char *expiry, + const char *can, bool mrz_available, bool can_available, + bool force_pace, bool force_bac) { + memset(auth, 0, sizeof(emrtd_auth_t)); + snprintf(auth->documentnumber, sizeof(auth->documentnumber), "%s", docnum); + snprintf(auth->dob, sizeof(auth->dob), "%s", dob); + snprintf(auth->expiry, sizeof(auth->expiry), "%s", expiry); + snprintf(auth->can, sizeof(auth->can), "%s", can); + auth->mrz_available = mrz_available; + auth->can_available = can_available; + auth->force_pace = force_pace; + auth->force_bac = force_bac; +} + static int CmdHFeMRTDDump(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf emrtd dump", "Dump all files on an eMRTD", "hf emrtd dump\n" "hf emrtd dump --dir ../dump\n" - "hf emrtd dump -n 123456789 -d 890101 -e 250401" + "hf emrtd dump -n 123456789 -d 890101 -e 250401\n" + "hf emrtd dump --can 123456 -> PACE with the Card Access Number\n" + "hf emrtd dump --can 123456 --pace -> PACE only, no BAC fallback\n" + "hf emrtd dump -n 123456789 -d 890101 -e 250401 --bac -> force BAC" ); void *argtable[] = { @@ -2232,6 +2842,9 @@ static int CmdHFeMRTDDump(const char *Cmd) { arg_str0("d", "date", "", "date of birth in YYMMDD format"), arg_str0("e", "expiry", "", "expiry in YYMMDD format"), arg_str0("m", "mrz", "<[0-9A-Z<]>", "2nd line of MRZ, 44 chars"), + arg_str0(NULL, "can", "", "Card Access Number, PACE password instead of the MRZ"), + arg_lit0(NULL, "pace", "force PACE, fail instead of falling back to BAC"), + arg_lit0(NULL, "bac", "force BAC, skip PACE"), arg_str0(NULL, "dir", "", "save dump to the given dirpath"), arg_param_end }; @@ -2299,12 +2912,29 @@ static int CmdHFeMRTDDump(const char *Cmd) { } } + uint8_t can[15] = { 0x00 }; + bool CAN = false; + if (CLIParamStrToBuf(arg_get_str(ctx, 5), can, sizeof(can) - 1, &slen) == 0 && slen != 0) { + CAN = true; + if (emrtd_validate_can((const char *)can, slen) == false) { + error = true; + } + } + + bool force_pace = arg_get_lit(ctx, 6); + bool force_bac = arg_get_lit(ctx, 7); + uint8_t path[FILENAME_MAX] = { 0x00 }; - if (CLIParamStrToBuf(arg_get_str(ctx, 5), path, sizeof(path), &slen) != 0 || slen == 0) { + if (CLIParamStrToBuf(arg_get_str(ctx, 8), path, sizeof(path), &slen) != 0 || slen == 0) { path[0] = '.'; } CLIParserFree(ctx); + + if (emrtd_check_auth_args(BAC, CAN, force_pace, force_bac) == false) { + error = true; + } + if (error) { return PM3_ESOFT; } @@ -2315,7 +2945,11 @@ static int CmdHFeMRTDDump(const char *Cmd) { uint64_t t1 = msclock(); - int res = dumpHF_EMRTD((char *)docnum, (char *)dob, (char *)expiry, BAC, (const char *)path); + emrtd_auth_t auth; + emrtd_fill_auth(&auth, (const char *)docnum, (const char *)dob, (const char *)expiry, + (const char *)can, BAC, CAN, force_pace, force_bac); + + int res = dumpHF_EMRTD(&auth, (const char *)path); PrintAndLogEx(SUCCESS, "time: %" PRIu64 " seconds\n", (msclock() - t1) / 1000); @@ -2330,7 +2964,9 @@ static int CmdHFeMRTDInfo(const char *Cmd) { "hf emrtd info\n" "hf emrtd info --dir ../dumps\n" "hf emrtd info -n 123456789 -d 890101 -e 250401\n" - "hf emrtd info -n 123456789 -d 890101 -e 250401 -i" + "hf emrtd info -n 123456789 -d 890101 -e 250401 -i\n" + "hf emrtd info --can 123456 -> PACE with the Card Access Number\n" + "hf emrtd info --can 123456 --pace -> PACE only, no BAC fallback" ); void *argtable[] = { @@ -2339,6 +2975,9 @@ static int CmdHFeMRTDInfo(const char *Cmd) { arg_str0("d", "date", "", "date of birth in YYMMDD format"), arg_str0("e", "expiry", "", "expiry in YYMMDD format"), arg_str0("m", "mrz", "<[0-9A-Z<]>", "2nd line of MRZ, 44 chars (passports only)"), + arg_str0(NULL, "can", "", "Card Access Number, PACE password instead of the MRZ"), + arg_lit0(NULL, "pace", "force PACE, fail instead of falling back to BAC"), + arg_lit0(NULL, "bac", "force BAC, skip PACE"), arg_str0(NULL, "dir", "", "display info from offline dump stored in dirpath"), arg_lit0("i", "images", "show images"), arg_param_end @@ -2405,9 +3044,21 @@ static int CmdHFeMRTDInfo(const char *Cmd) { } } } + uint8_t can[15] = { 0x00 }; + bool CAN = false; + if (CLIParamStrToBuf(arg_get_str(ctx, 5), can, sizeof(can) - 1, &slen) == 0 && slen != 0) { + CAN = true; + if (emrtd_validate_can((const char *)can, slen) == false) { + error = true; + } + } + + bool force_pace = arg_get_lit(ctx, 6); + bool force_bac = arg_get_lit(ctx, 7); + uint8_t path[FILENAME_MAX] = { 0x00 }; - bool is_offline = CLIParamStrToBuf(arg_get_str(ctx, 5), path, sizeof(path), &slen) == 0 && slen > 0; - bool show_images = arg_get_lit(ctx, 6); + bool is_offline = CLIParamStrToBuf(arg_get_str(ctx, 8), path, sizeof(path), &slen) == 0 && slen > 0; + bool show_images = arg_get_lit(ctx, 9); CLIParserFree(ctx); if ((IfPm3Iso14443() == false) && (is_offline == false)) { @@ -2415,6 +3066,10 @@ static int CmdHFeMRTDInfo(const char *Cmd) { error = true; } + if ((is_offline == false) && (emrtd_check_auth_args(BAC, CAN, force_pace, force_bac) == false)) { + error = true; + } + if (error) { return PM3_ESOFT; } @@ -2426,12 +3081,32 @@ static int CmdHFeMRTDInfo(const char *Cmd) { if (g_debugMode >= 2) { SetAPDULogging(true); } - int res = infoHF_EMRTD((char *)docnum, (char *)dob, (char *)expiry, BAC, !show_images); + emrtd_auth_t auth; + emrtd_fill_auth(&auth, (const char *)docnum, (const char *)dob, (const char *)expiry, + (const char *)can, BAC, CAN, force_pace, force_bac); + + int res = infoHF_EMRTD(&auth, !show_images); SetAPDULogging(restore_apdu_logging); return res; } } +static int CmdHFeMRTDTest(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf emrtd test", + "Regression tests for the PACE and secure messaging primitives", + "hf emrtd test"); + + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + + return emrtd_test(true) ? PM3_SUCCESS : PM3_ESOFT; +} + static int CmdHFeMRTDList(const char *Cmd) { return CmdTraceListAlias(Cmd, "hf emrtd", "7816"); } @@ -2442,6 +3117,7 @@ static command_t CommandTable[] = { {"dump", CmdHFeMRTDDump, IfPm3Iso14443, "Dump eMRTD files to binary files"}, {"info", CmdHFeMRTDInfo, AlwaysAvailable, "Tag information"}, {"list", CmdHFeMRTDList, AlwaysAvailable, "List ISO 14443A/7816 history"}, + {"test", CmdHFeMRTDTest, AlwaysAvailable, "Regression tests"}, {NULL, NULL, NULL, NULL} }; diff --git a/client/src/cmdhfemrtd.h b/client/src/cmdhfemrtd.h index 962501331..e8ce57709 100644 --- a/client/src/cmdhfemrtd.h +++ b/client/src/cmdhfemrtd.h @@ -47,23 +47,22 @@ typedef struct emrtd_hashalg_s { const uint8_t descriptor[15]; } emrtd_hashalg_t; -typedef struct emrtd_pacealg_s { - const char *name; - int (*keygenerator)(uint8_t *datain, int datainlen, uint8_t *dataout); - const uint8_t descriptor[10]; -} emrtd_pacealg_t; - -// Standardized Domain Parameters -typedef struct emrtd_pacesdp_s { - uint8_t id; - const char *name; - size_t size; -} emrtd_pacesdp_t; +// Everything needed to authenticate to a document, either with BAC or with PACE +typedef struct emrtd_auth_s { + char documentnumber[10]; + char dob[7]; + char expiry[7]; + char can[15]; + bool mrz_available; + bool can_available; + bool force_pace; // fail rather than falling back to BAC + bool force_bac; // skip PACE even when EF_CardAccess is present +} emrtd_auth_t; int CmdHFeMRTD(const char *Cmd); -int dumpHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available, const char *path); -int infoHF_EMRTD(char *documentnumber, char *dob, char *expiry, bool BAC_available, bool only_fast); +int dumpHF_EMRTD(const emrtd_auth_t *auth, const char *path); +int infoHF_EMRTD(const emrtd_auth_t *auth, bool only_fast); int infoHF_EMRTD_offline(const char *path); #ifdef __cplusplus diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c index 74ec9cbe7..1b307e2bd 100644 --- a/client/src/cmdhfmfu.c +++ b/client/src/cmdhfmfu.c @@ -7402,6 +7402,431 @@ int CmdHF14MfuNDEFRead(const char *Cmd) { return status; } + +// Build a NDEF message from the CLI options and write it into the data area of a +// MIFARE Ultralight / NTAG tag. The tag has to be NDEF formatted already, this +// command never touches the Capability Container in block 3. +int CmdHF14MfuNDEFWrite(const char *Cmd) { + + int ak_len = 0; + bool has_auth_key = false; + bool has_pwd = false; + bool swap_endian = false; + + iso14a_card_select_t card; + uint8_t data[16] = {0x00}; + uint8_t authenticationkey[16] = {0x00}; + uint8_t *auth_key_ptr = authenticationkey; + uint8_t pack[4] = {0, 0, 0, 0}; + + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf mfu ndefwrite", + "Write NFC Data Exchange Format (NDEF) records to a MIFARE Ultralight / NTAG tag.\n" + "The tag must already be NDEF formatted, ie carry a Capability Container in block 3.\n" + "\n" + "Combine several of --uri, --text and --aar to build a multi record message,\n" + "records are added in that order. Alternatively supply raw NDEF bytes with -d\n" + "or -f, those get wrapped in a TLV container automatically when they are not\n" + "already. Use `nfc encode` to build such raw bytes offline.\n" + "\n" + "Note: the tag is re-selected and re-authenticated for every block written,\n" + "so a large message takes a while.", + "hf mfu ndefwrite --uri https://proxmark.com\n" + "hf mfu ndefwrite --uri tel:+123456789\n" + "hf mfu ndefwrite --text \"hello world\"\n" + "hf mfu ndefwrite --aar com.example.app\n" + "hf mfu ndefwrite --uri https://proxmark.com --aar com.example.app\n" + "hf mfu ndefwrite --uri https://proxmark.com -k ffffffff\n" + "hf mfu ndefwrite -d 0311D1010D550270726F786D61726B2E636F6DFE\n" + "hf mfu ndefwrite -f myfilename" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("k", "key", "", "Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)"), + arg_lit0("l", NULL, "Swap entered key endianness"), + arg_str0(NULL, "uri", "", "URI record. URL, tel:, mailto:, ..."), + arg_str0(NULL, "text", "", "Text record"), + arg_str0(NULL, "lang", "", "language code for the text record (default: en)"), + arg_str0(NULL, "aar", "", "Android Application Record, ie an app package name"), + arg_str0("d", "data", "", "Raw NDEF bytes to write"), + arg_str0("f", "file", "", "Raw NDEF file to write"), + arg_lit0("v", "verbose", "Verbose output"), + arg_lit0(NULL, "schann", "use secure channel. Must have key"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + CLIGetHexWithReturn(ctx, 1, authenticationkey, &ak_len); + swap_endian = arg_get_lit(ctx, 2); + + // CLIParamStrToBuf copies the trailing NUL as well but only rejects lengths + // strictly above maxdatalen, so leave room for that byte + int urilen = 0; + char uri[1024] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 3), (uint8_t *)uri, sizeof(uri) - 1, &urilen); + + int textlen = 0; + char text[1024] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 4), (uint8_t *)text, sizeof(text) - 1, &textlen); + + int langlen = 0; + char lang[32] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 5), (uint8_t *)lang, sizeof(lang) - 1, &langlen); + + int aarlen = 0; + char aar[256] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 6), (uint8_t *)aar, sizeof(aar) - 1, &aarlen); + + int rawlen = 0; + uint8_t raw[MFU_NDEF_MAX_BYTES] = {0}; + CLIGetHexWithReturn(ctx, 7, raw, &rawlen); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 8), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + bool verbose = arg_get_lit(ctx, 9); + bool use_schann = arg_get_lit(ctx, 10); + CLIParserFree(ctx); + + bool has_records = (urilen || textlen || aarlen); + int sources = (has_records ? 1 : 0) + (rawlen ? 1 : 0) + (fnlen ? 1 : 0); + if (sources == 0) { + PrintAndLogEx(ERR, "Nothing to write. See `" _YELLOW_("hf mfu ndefwrite -h") "`"); + return PM3_EINVARG; + } + if (sources > 1) { + PrintAndLogEx(ERR, "Use either the record options, -d or -f, not a mix of them"); + return PM3_EINVARG; + } + + if ((langlen != 0) && (textlen == 0)) { + PrintAndLogEx(WARNING, "--lang only applies to a text record, ignoring"); + } + + switch (ak_len) { + case 0: + break; + case 4: + has_pwd = true; + break; + case 16: + has_auth_key = true; + break; + default: + PrintAndLogEx(WARNING, "ERROR: Key is incorrect length\n"); + return PM3_EINVARG; + } + + if (use_schann && (has_auth_key == false)) { + PrintAndLogEx(WARNING, "Secure channel must be called with key"); + return PM3_EINVARG; + } + + // ------------------------------------------------------------------ + // build the TLV block that goes onto the tag + // ------------------------------------------------------------------ + uint8_t tlv[MFU_NDEF_MAX_BYTES] = {0}; + size_t tlv_len = 0; + int res = PM3_SUCCESS; + + if (has_records) { + + NDEFRecordDesc_t recs[3] = {{0}}; + size_t count = 0; + + uint8_t p_uri[sizeof(uri) + 1] = {0}; + size_t p_uri_len = 0; + if (urilen) { + res = NDEFEncodePayloadURI(uri, p_uri, sizeof(p_uri), &p_uri_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode URI record"); + return res; + } + recs[count].tnf = tnfWellKnownRecord; + recs[count].type = (const uint8_t *)NDEF_TYPE_URI; + recs[count].typeLen = strlen(NDEF_TYPE_URI); + recs[count].payload = p_uri; + recs[count].payloadLen = p_uri_len; + count++; + } + + uint8_t p_text[sizeof(text) + sizeof(lang) + 1] = {0}; + size_t p_text_len = 0; + if (textlen) { + res = NDEFEncodePayloadText(text, lang, p_text, sizeof(p_text), &p_text_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode Text record"); + return res; + } + recs[count].tnf = tnfWellKnownRecord; + recs[count].type = (const uint8_t *)NDEF_TYPE_TEXT; + recs[count].typeLen = strlen(NDEF_TYPE_TEXT); + recs[count].payload = p_text; + recs[count].payloadLen = p_text_len; + count++; + } + + uint8_t p_aar[sizeof(aar)] = {0}; + size_t p_aar_len = 0; + if (aarlen) { + res = NDEFEncodePayloadAAR(aar, p_aar, sizeof(p_aar), &p_aar_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode Android Application Record"); + return res; + } + recs[count].tnf = tnfExternalRecord; + recs[count].type = (const uint8_t *)NDEF_ANDROID_AAR; + recs[count].typeLen = strlen(NDEF_ANDROID_AAR); + recs[count].payload = p_aar; + recs[count].payloadLen = p_aar_len; + count++; + } + + uint8_t msg[MFU_NDEF_MAX_BYTES] = {0}; + size_t msg_len = 0; + res = NDEFEncodeMessage(recs, count, msg, sizeof(msg), &msg_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode NDEF message"); + return res; + } + + res = NDEFEncodeTLV(msg, msg_len, tlv, sizeof(tlv), &tlv_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to wrap NDEF message in a TLV container"); + return res; + } + + } else { + + uint8_t *src = raw; + size_t src_len = (size_t)rawlen; + uint8_t *dump = NULL; + + if (fnlen) { + size_t bytes_read = 0; + res = pm3_load_dump(filename, (void **)&dump, &bytes_read, sizeof(raw)); + if (res != PM3_SUCCESS) { + return res; + } + src = dump; + src_len = bytes_read; + } + + if (src_len == 0) { + PrintAndLogEx(ERR, "No NDEF data supplied"); + free(dump); + return PM3_EINVARG; + } + + // is it a TLV block already? + bool is_tlv = false; + switch (src[0]) { + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0xFD: + case 0xFE: + is_tlv = true; + break; + default: + break; + } + + if (is_tlv) { + if (src_len > sizeof(tlv)) { + PrintAndLogEx(ERR, "NDEF data too large, %zu bytes", src_len); + free(dump); + return PM3_EINVARG; + } + memcpy(tlv, src, src_len); + tlv_len = src_len; + } else { + if (verbose) { + PrintAndLogEx(INFO, "Raw data is not TLV wrapped, adding container"); + } + res = NDEFEncodeTLV(src, src_len, tlv, sizeof(tlv), &tlv_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to wrap NDEF message in a TLV container"); + free(dump); + return res; + } + } + + free(dump); + } + + if (verbose) { + PrintAndLogEx(INFO, "TLV block [%zu]...", tlv_len); + print_hex_noascii_break(tlv, tlv_len, 32); + } + + // ------------------------------------------------------------------ + // find the tag and check the message fits + // ------------------------------------------------------------------ + uint64_t tagtype = GetHF14AMfU_Type(); + if (tagtype == MFU_TT_UL_ERROR) { + PrintAndLogEx(WARNING, "No Ultralight / NTAG based tag found"); + return PM3_ESOFT; + } + + ul_print_type(tagtype, 0); + + if (swap_endian) { + if (ak_len == 16) { + if (((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C)) { + auth_key_ptr = SwapEndian64(authenticationkey, ak_len, 8); + } else if (((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES)) { + auth_key_ptr = SwapEndian64(authenticationkey, ak_len, 16); + } + } else if (ak_len == 4) { + auth_key_ptr = SwapEndian64(authenticationkey, ak_len, 4); + } + } + + if (ul_auth_select(&card, tagtype, (has_auth_key || has_pwd), auth_key_ptr, pack, sizeof(pack), use_schann) == PM3_ESOFT) { + return PM3_ESOFT; + } + + // read blocks 0..3 to get at the Capability Container + int status = ul_read(0, data, sizeof(data), use_schann); + if (status <= 0) { + DropField(); + PrintAndLogEx(ERR, "Error: tag didnt answer to READ"); + return PM3_ESOFT; + } + + if (status != 16) { + DropField(); + PrintAndLogEx(ERR, "Error: tag returned %d bytes, need 16 to read the NDEF Container", status); + return PM3_ESOFT; + } + + if (ndef_print_CC(data + 12) == PM3_ESOFT) { + DropField(); + PrintAndLogEx(ERR, "Error: tag didnt contain a NDEF Container"); + PrintAndLogEx(HINT, "Hint: the tag needs to be NDEF formatted first"); + return PM3_ESOFT; + } + + // size of the NDEF data area + uint16_t ndef_size = ndef_get_maxsize(data + 12); + if (ndef_size == 0) { + DropField(); + PrintAndLogEx(ERR, "Error: tag announces an empty NDEF data area"); + return PM3_ESOFT; + } + + // The data area starts at block 4, so cap the announced size to what the + // identified tag can physically hold. UL_MEMORY_ARRAY holds the last valid + // block number, hence the +1. + for (uint8_t idx = 1; idx < ARRAYLEN(UL_TYPES_ARRAY); idx++) { + if ((tagtype & UL_TYPES_ARRAY[idx]) == UL_TYPES_ARRAY[idx]) { + + int avail = (UL_MEMORY_ARRAY[idx] + 1 - MFU_NDEF_FIRST_BLOCK) * MFU_BLOCK_SIZE; + if (avail > 0 && ndef_size > avail) { + PrintAndLogEx(INFO, "NDEF data area (%u bytes) is larger than the tag (%d bytes), using tag size" + , ndef_size + , avail + ); + ndef_size = avail; + } + break; + } + } + + // MLEN can announce up to 2040 bytes but WRITE addresses blocks with a single + // byte, so block 255 is the last one we can reach. + if (ndef_size > MFU_NDEF_MAX_BYTES) { + ndef_size = MFU_NDEF_MAX_BYTES; + } + + if (tlv_len > ndef_size) { + DropField(); + PrintAndLogEx(ERR, "NDEF message is too large for this tag"); + PrintAndLogEx(ERR, " message..... " _RED_("%zu") " bytes", tlv_len); + PrintAndLogEx(ERR, " tag holds... " _GREEN_("%u") " bytes", ndef_size); + return PM3_EINVARG; + } + + DropField(); + + // ------------------------------------------------------------------ + // write it out, one block at a time + // ------------------------------------------------------------------ + uint8_t keytype = 0; + if (has_auth_key || has_pwd) { + if ((tagtype & MFU_TT_UL_C) == MFU_TT_UL_C) { + keytype = 1; // UL_C auth + } else if ((tagtype & MFU_TT_UL_AES) == MFU_TT_UL_AES) { + keytype = 3; // UL_AES auth + } else { + keytype = 2; // UL_EV1/NTAG auth + } + } + + // pad the tail so the last block is complete + size_t padded_len = (tlv_len + (MFU_BLOCK_SIZE - 1)) & ~((size_t)MFU_BLOCK_SIZE - 1); + uint16_t blocks = (uint16_t)(padded_len / MFU_BLOCK_SIZE); + + PrintAndLogEx(INFO, "Writing " _YELLOW_("%u") " blocks ( %zu bytes ) from block " _YELLOW_("%d") + , blocks + , padded_len + , MFU_NDEF_FIRST_BLOCK + ); + PrintAndLogEx(INFO, "Press " _GREEN_("") " to abort"); + + for (uint16_t i = 0; i < blocks; i++) { + + if (kbd_enter_pressed()) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(WARNING, "aborted via keyboard!"); + if (i > 0) { + PrintAndLogEx(WARNING, "tag holds a partially written NDEF message, blocks %d..%u" + , MFU_NDEF_FIRST_BLOCK + , MFU_NDEF_FIRST_BLOCK + i - 1 + ); + } + return PM3_EOPABORTED; + } + + uint8_t blockno = (uint8_t)(MFU_NDEF_FIRST_BLOCK + i); + + res = mfu_write_block(tlv + (i * MFU_BLOCK_SIZE), MFU_BLOCK_SIZE, keytype, auth_key_ptr, blockno, use_schann); + if (res != PM3_SUCCESS) { + PrintAndLogEx(NORMAL, ""); + + // a protected tag simply stops answering, so the write times out + // rather than coming back with an explicit error + if (res == PM3_ETIMEOUT) { + PrintAndLogEx(FAILED, "Write block %u ( " _RED_("timeout") " )", blockno); + } else { + PrintAndLogEx(FAILED, "Write block %u ( " _RED_("fail") " )", blockno); + } + PrintAndLogEx(HINT, "Hint: Check password / key!"); + + if (i > 0) { + PrintAndLogEx(WARNING, "tag holds a partially written NDEF message, blocks %d..%u" + , MFU_NDEF_FIRST_BLOCK + , blockno - 1 + ); + } + return PM3_ESOFT; + } + + PrintAndLogEx(INPLACE, "Block %u / %u", i + 1, blocks); + } + + DropField(); + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(SUCCESS, "Write ( " _GREEN_("ok") " )"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf mfu ndefread") "` to verify"); + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; +} // utility function. Retrieves emulator memory static int GetMfuDumpFromEMul(mfu_dump_t **buf) { @@ -8274,6 +8699,7 @@ static command_t CommandTable[] = { {"incr", CmdHF14AMfUIncr, IfPm3Iso14443a, "Increments Ev1/NTAG counter"}, {"info", CmdHF14AMfUInfo, IfPm3Iso14443a, "Tag information"}, {"ndefread", CmdHF14MfuNDEFRead, IfPm3Iso14443a, "Prints NDEF records from card"}, + {"ndefwrite", CmdHF14MfuNDEFWrite, IfPm3Iso14443a, "Write NDEF records to card"}, {"rdbl", CmdHF14AMfURdBl, IfPm3Iso14443a, "Read block"}, {"restore", CmdHF14AMfURestore, IfPm3Iso14443a, "Restore a dump file onto a tag"}, {"tamper", CmdHF14MfUTamper, IfPm3Iso14443a, "NTAG 213TT - Configure the tamper feature"}, diff --git a/client/src/cmdhfmfu.h b/client/src/cmdhfmfu.h index d283665ad..1eb49488b 100644 --- a/client/src/cmdhfmfu.h +++ b/client/src/cmdhfmfu.h @@ -57,7 +57,8 @@ int mfu_get_version_uid(uint8_t *version, uint8_t *uid); int mfuc_test_authentication_support(void); int CmdHFMFUltra(const char *Cmd); -int CmdHF14MfuNDEFRead(const char *Cmd); +int CmdHF14MfuNDEFRead(const char *Cmd); // used by cmdnfc.c +int CmdHF14MfuNDEFWrite(const char *Cmd); // used by cmdnfc.c int CmdHF14MfUTamper(const char *Cmd); #define MFU_TT_UNKNOWN 0x0ULL diff --git a/client/src/cmdhfsaflok.c b/client/src/cmdhfsaflok.c index d7fe63b51..61219d771 100644 --- a/client/src/cmdhfsaflok.c +++ b/client/src/cmdhfsaflok.c @@ -673,7 +673,7 @@ static saflok_mfc_datetime_t add_offset(const saflok_mfc_datetime_t *base, const // variable days per month ... loop is simplest option uint8_t curr_days_in_month = get_days_in_month(tm.tm_year + 1900, tm.tm_mon + 1); - for (; ((tm.tm_mday & 0xFF) > curr_days_in_month); curr_days_in_month = get_days_in_month(tm.tm_year + 1900, tm.tm_mon + 1)) { + for (; (tm.tm_mday > (int)curr_days_in_month); curr_days_in_month = get_days_in_month(tm.tm_year + 1900, tm.tm_mon + 1)) { tm.tm_mon ++; tm.tm_mday -= curr_days_in_month; diff --git a/client/src/cmdnfc.c b/client/src/cmdnfc.c index fe58e5aba..67dfa2720 100644 --- a/client/src/cmdnfc.c +++ b/client/src/cmdnfc.c @@ -178,6 +178,183 @@ static int CmdNfcDecode(const char *Cmd) { return res; } +static int CmdNfcEncode(const char *Cmd) { + +#ifndef MAX_NDEF_LEN +#define MAX_NDEF_LEN 2048 +#endif + + CLIParserContext *ctx; + CLIParserInit(&ctx, "nfc encode", + "Encode NFC Data Exchange Format (NDEF) records.\n" + "Combine several options to build a multi record message,\n" + "records are added in the order listed below.\n" + "\n" + "By default a bare NDEF message is emitted. Use `--tlv` to wrap it in a\n" + "NFC Forum Type 2 tag container ( 03 ... FE ), which is what the\n" + "`-d` parameter of `hf mf ndefwrite` and `hf 14a ndefwrite` expects.\n" + "`hf mfu ndefwrite` adds the container itself, so it does not need `--tlv`", + "nfc encode --uri https://proxmark.com\n" + "nfc encode --uri tel:+123456789\n" + "nfc encode --text \"hello world\"\n" + "nfc encode --aar com.example.app\n" + "nfc encode --uri https://proxmark.com --aar com.example.app\n" + "nfc encode --uri https://proxmark.com --tlv -f myfilename" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0(NULL, "uri", "", "URI record. URL, tel:, mailto:, ..."), + arg_str0(NULL, "text", "", "Text record"), + arg_str0(NULL, "lang", "", "language code for the text record (default: en)"), + arg_str0(NULL, "aar", "", "Android Application Record, ie an app package name"), + arg_lit0(NULL, "tlv", "wrap message in a NFC Forum Type 2 tag TLV container"), + arg_str0("f", "file", "", "save raw bytes to file"), + arg_lit0("v", "verbose", "verbose output"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, false); + + // CLIParamStrToBuf copies the trailing NUL as well but only rejects lengths + // strictly above maxdatalen, so leave room for that byte + int urilen = 0; + char uri[1024] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)uri, sizeof(uri) - 1, &urilen); + + int textlen = 0; + char text[1024] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 2), (uint8_t *)text, sizeof(text) - 1, &textlen); + + int langlen = 0; + char lang[32] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 3), (uint8_t *)lang, sizeof(lang) - 1, &langlen); + + int aarlen = 0; + char aar[256] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 4), (uint8_t *)aar, sizeof(aar) - 1, &aarlen); + + bool use_tlv = arg_get_lit(ctx, 5); + + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 6), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + bool verbose = arg_get_lit(ctx, 7); + CLIParserFree(ctx); + + if ((urilen == 0) && (textlen == 0) && (aarlen == 0)) { + PrintAndLogEx(ERR, "Must specify at least one record. See `" _YELLOW_("nfc encode -h") "`"); + return PM3_EINVARG; + } + + if ((langlen != 0) && (textlen == 0)) { + PrintAndLogEx(WARNING, "`--lang` only applies to a text record, ignoring"); + } + + NDEFRecordDesc_t recs[3] = {{0}}; + size_t count = 0; + int res = PM3_SUCCESS; + + uint8_t p_uri[sizeof(uri) + 1] = {0}; + size_t p_uri_len = 0; + if (urilen) { + res = NDEFEncodePayloadURI(uri, p_uri, sizeof(p_uri), &p_uri_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode URI record"); + return res; + } + recs[count].tnf = tnfWellKnownRecord; + recs[count].type = (const uint8_t *)NDEF_TYPE_URI; + recs[count].typeLen = strlen(NDEF_TYPE_URI); + recs[count].payload = p_uri; + recs[count].payloadLen = p_uri_len; + count++; + } + + uint8_t p_text[sizeof(text) + sizeof(lang) + 1] = {0}; + size_t p_text_len = 0; + if (textlen) { + res = NDEFEncodePayloadText(text, lang, p_text, sizeof(p_text), &p_text_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode Text record"); + return res; + } + recs[count].tnf = tnfWellKnownRecord; + recs[count].type = (const uint8_t *)NDEF_TYPE_TEXT; + recs[count].typeLen = strlen(NDEF_TYPE_TEXT); + recs[count].payload = p_text; + recs[count].payloadLen = p_text_len; + count++; + } + + uint8_t p_aar[sizeof(aar)] = {0}; + size_t p_aar_len = 0; + if (aarlen) { + res = NDEFEncodePayloadAAR(aar, p_aar, sizeof(p_aar), &p_aar_len); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode Android Application Record"); + return res; + } + recs[count].tnf = tnfExternalRecord; + recs[count].type = (const uint8_t *)NDEF_ANDROID_AAR; + recs[count].typeLen = strlen(NDEF_ANDROID_AAR); + recs[count].payload = p_aar; + recs[count].payloadLen = p_aar_len; + count++; + } + + uint8_t msg[MAX_NDEF_LEN] = {0}; + size_t msglen = 0; + res = NDEFEncodeMessage(recs, count, msg, sizeof(msg), &msglen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to encode NDEF message"); + return res; + } + + uint8_t tlv[MAX_NDEF_LEN] = {0}; + uint8_t *out = msg; + size_t outlen = msglen; + + if (use_tlv) { + size_t tlvlen = 0; + res = NDEFEncodeTLV(msg, msglen, tlv, sizeof(tlv), &tlvlen); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "Failed to wrap NDEF message in a TLV container"); + return res; + } + out = tlv; + outlen = tlvlen; + } + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("NDEF encoding") " ----------------"); + PrintAndLogEx(SUCCESS, "Records......... " _YELLOW_("%zu"), count); + PrintAndLogEx(SUCCESS, "Message size.... " _YELLOW_("%zu") " bytes", msglen); + if (use_tlv) { + PrintAndLogEx(SUCCESS, "TLV size........ " _YELLOW_("%zu") " bytes", outlen); + } + + PrintAndLogEx(NORMAL, ""); + if (outlen > 64) { + print_hex_noascii_break(out, outlen, 32); + } else { + PrintAndLogEx(SUCCESS, _GREEN_("%s"), sprint_hex_inrow(out, outlen)); + } + + if (fnlen) { + saveFile(filename, ".bin", out, outlen); + } + + // round trip it back through the decoder, so the user can see what a reader will see + if (use_tlv) { + NDEFDecodeAndPrint(out, outlen, verbose); + } else { + NDEFRecordsDecodeAndPrint(out, outlen, verbose); + } + + return PM3_SUCCESS; +} + static int CmdNFCType1Read(const char *Cmd) { return CmdHFTopazInfo(Cmd); } @@ -210,6 +387,10 @@ static int CmdNFCType2Read(const char *Cmd) { return CmdHF14MfuNDEFRead(Cmd); } +static int CmdNFCType2Write(const char *Cmd) { + return CmdHF14MfuNDEFWrite(Cmd); +} + static int CmdNFCType2Help(const char *Cmd); static command_t CommandNFCType2Table[] = { @@ -217,7 +398,7 @@ static command_t CommandNFCType2Table[] = { {"--------", CmdNFCType2Help, AlwaysAvailable, "-------------- " _CYAN_("NFC Forum Tag Type 2") " ---------------"}, // {"format", CmdNFCType2Format, IfPm3Iso14443a, "format ISO-14443-a tag as NFC Tag"}, {"read", CmdNFCType2Read, IfPm3Iso14443a, "read NFC Forum Tag Type 2"}, -// {"write", CmdNFCType2Write, IfPm3Iso14443a, "write NFC Forum Tag Type 2"}, + {"write", CmdNFCType2Write, IfPm3Iso14443a, "write NFC Forum Tag Type 2"}, {"--------", CmdNFCType2Help, AlwaysAvailable, "--------------------- " _CYAN_("General") " ---------------------"}, {"help", CmdNFCType2Help, AlwaysAvailable, "This help"}, {NULL, NULL, NULL, NULL} @@ -459,7 +640,7 @@ static command_t CommandTable[] = { {"--------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("General") " ---------------------"}, {"help", CmdHelp, AlwaysAvailable, "This help"}, {"decode", CmdNfcDecode, AlwaysAvailable, "Decode NDEF records"}, -// {"encode", CmdNfcEncode, AlwaysAvailable, "Encode NDEF records"}, + {"encode", CmdNfcEncode, AlwaysAvailable, "Encode NDEF records"}, {NULL, NULL, NULL, NULL} }; diff --git a/client/src/emrtd/emrtd_pace.c b/client/src/emrtd/emrtd_pace.c new file mode 100644 index 000000000..1af3a8674 --- /dev/null +++ b/client/src/emrtd/emrtd_pace.c @@ -0,0 +1,1488 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// PACE (Password Authenticated Connection Establishment) primitives for eMRTD +//----------------------------------------------------------------------------- + +#include "emrtd_pace.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include "crypto/libpcrypto.h" // sha1hash, sha256hash, des_encrypt/decrypt, pcrypto_rng_* +#include "ui.h" // PrintAndLogEx +#include "util.h" // sprint_hex_inrow +#include "commonutil.h" // ARRAYLEN + +//----------------------------------------------------------------------------- +// Tables +//----------------------------------------------------------------------------- + +// TR-03110 part 3, table A.1. The OID bodies are what follows the "06 " +// header, i.e. 0.4.0.127.0.7.2.2.4.x.y +static const emrtd_pacealg_t pacealg_table[] = { +// name key agreement mapping cipher keylen oidlen oid + {"DH, Generic Mapping, 3DES-CBC-CBC", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_3DES, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x01}}, + {"DH, Generic Mapping, AES-CMAC-128", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_AES128, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x02}}, + {"DH, Generic Mapping, AES-CMAC-192", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_AES192, 24, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x03}}, + {"DH, Generic Mapping, AES-CMAC-256", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_AES256, 32, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01, 0x04}}, + {"ECDH, Generic Mapping, 3DES-CBC-CBC", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_3DES, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x01}}, + {"ECDH, Generic Mapping, AES-CMAC-128", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_AES128, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x02}}, + {"ECDH, Generic Mapping, AES-CMAC-192", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_AES192, 24, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x03}}, + {"ECDH, Generic Mapping, AES-CMAC-256", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_GM, EMRTD_PACE_CIPHER_AES256, 32, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x04}}, + {"DH, Integrated Mapping, 3DES-CBC-CBC", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_3DES, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x01}}, + {"DH, Integrated Mapping, AES-CMAC-128", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_AES128, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x02}}, + {"DH, Integrated Mapping, AES-CMAC-192", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_AES192, 24, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x03}}, + {"DH, Integrated Mapping, AES-CMAC-256", EMRTD_PACE_KA_DH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_AES256, 32, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x03, 0x04}}, + {"ECDH, Integrated Mapping, 3DES-CBC-CBC", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_3DES, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x01}}, + {"ECDH, Integrated Mapping, AES-CMAC-128", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_AES128, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x02}}, + {"ECDH, Integrated Mapping, AES-CMAC-192", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_AES192, 24, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x03}}, + {"ECDH, Integrated Mapping, AES-CMAC-256", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_IM, EMRTD_PACE_CIPHER_AES256, 32, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x04, 0x04}}, + // Chip Authentication Mapping, TR-03110 part 3, A.1.1 + {"ECDH, CA Mapping, AES-CMAC-128", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_CAM, EMRTD_PACE_CIPHER_AES128, 16, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x06, 0x02}}, + {"ECDH, CA Mapping, AES-CMAC-192", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_CAM, EMRTD_PACE_CIPHER_AES192, 24, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x06, 0x03}}, + {"ECDH, CA Mapping, AES-CMAC-256", EMRTD_PACE_KA_ECDH, EMRTD_PACE_MAP_CAM, EMRTD_PACE_CIPHER_AES256, 32, 10, {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x06, 0x04}}, + {NULL, 0, 0, 0, 0, 0, {0}} +}; + +// TR-03110 part 3, table A.2. +// The curve column is MBEDTLS_ECP_DP_NONE for every curve this tree's mbedtls +// does not carry, see common/mbedtls/config.h. That must stay an explicit +// "unsupported" instead of silently picking a near neighbour. +static const emrtd_pacesdp_t pacesdp_table[] = { +// id name size is_ec mbedtls curve + {0, "1024-bit MODP Group with 160-bit Prime Order Subgroup", 1024, false, MBEDTLS_ECP_DP_NONE}, + {1, "2048-bit MODP Group with 224-bit Prime Order Subgroup", 2048, false, MBEDTLS_ECP_DP_NONE}, + {2, "2048-bit MODP Group with 256-bit Prime Order Subgroup", 2048, false, MBEDTLS_ECP_DP_NONE}, + {8, "NIST P-192 (secp192r1)", 192, true, MBEDTLS_ECP_DP_SECP192R1}, + {9, "BrainpoolP192r1", 192, true, MBEDTLS_ECP_DP_NONE}, + {10, "NIST P-224 (secp224r1)", 224, true, MBEDTLS_ECP_DP_SECP224R1}, + {11, "BrainpoolP224r1", 224, true, MBEDTLS_ECP_DP_NONE}, + {12, "NIST P-256 (secp256r1)", 256, true, MBEDTLS_ECP_DP_SECP256R1}, + {13, "BrainpoolP256r1", 256, true, MBEDTLS_ECP_DP_BP256R1}, + {14, "BrainpoolP320r1", 320, true, MBEDTLS_ECP_DP_NONE}, + {15, "NIST P-384 (secp384r1)", 384, true, MBEDTLS_ECP_DP_SECP384R1}, + {16, "BrainpoolP384r1", 384, true, MBEDTLS_ECP_DP_BP384R1}, + {17, "BrainpoolP512r1", 512, true, MBEDTLS_ECP_DP_BP512R1}, + {18, "NIST P-521 (secp521r1)", 521, true, MBEDTLS_ECP_DP_SECP521R1}, + {32, NULL, 0, false, MBEDTLS_ECP_DP_NONE} +}; + +const emrtd_pacealg_t *emrtd_pace_alg_by_oid(const uint8_t *oid, size_t oidlen) { + for (int i = 0; pacealg_table[i].name != NULL; i++) { + if (pacealg_table[i].oidlen == oidlen && memcmp(pacealg_table[i].oid, oid, oidlen) == 0) { + return &pacealg_table[i]; + } + } + return NULL; +} + +const emrtd_pacesdp_t *emrtd_pace_sdp_by_id(uint8_t id) { + for (int i = 0; pacesdp_table[i].id != 32; i++) { + if (pacesdp_table[i].id == id) { + return &pacesdp_table[i]; + } + } + return NULL; +} + +const char *emrtd_pace_cipher_name(emrtd_pace_cipher_t cipher) { + switch (cipher) { + case EMRTD_PACE_CIPHER_3DES: + return "3DES-CBC-CBC"; + case EMRTD_PACE_CIPHER_AES128: + return "AES-CMAC-128"; + case EMRTD_PACE_CIPHER_AES192: + return "AES-CMAC-192"; + case EMRTD_PACE_CIPHER_AES256: + return "AES-CMAC-256"; + } + return "unknown"; +} + +//----------------------------------------------------------------------------- +// 3DES / ISO 9797-1 helpers +//----------------------------------------------------------------------------- + +void emrtd_des3_encrypt_cbc(uint8_t *iv, const uint8_t *key, const uint8_t *input, size_t inputlen, uint8_t *output) { + mbedtls_des3_context ctx; + mbedtls_des3_set2key_enc(&ctx, key); + mbedtls_des3_crypt_cbc(&ctx, MBEDTLS_DES_ENCRYPT, inputlen, iv, input, output); + mbedtls_des3_free(&ctx); +} + +void emrtd_des3_decrypt_cbc(uint8_t *iv, const uint8_t *key, const uint8_t *input, size_t inputlen, uint8_t *output) { + mbedtls_des3_context ctx; + mbedtls_des3_set2key_dec(&ctx, key); + mbedtls_des3_crypt_cbc(&ctx, MBEDTLS_DES_DECRYPT, inputlen, iv, input, output); + mbedtls_des3_free(&ctx); +} + +size_t emrtd_pad_block(const uint8_t *input, size_t inputlen, size_t blocksize, uint8_t *output) { + if (inputlen) { + memmove(output, input, inputlen); + } + output[inputlen] = 0x80; + size_t padded = inputlen + 1; + while ((padded % blocksize) != 0) { + output[padded++] = 0x00; + } + return padded; +} + +#define EMRTD_RETAIL_MAC_MAXLEN 512 +#define EMRTD_SM_MAC_MAXLEN 576 + +int emrtd_retail_mac(const uint8_t *key, const uint8_t *input, size_t inputlen, uint8_t *output) { + // ISO 9797-1 MAC algorithm 3 with padding method 2, block length 8. + // Takes inspiration from https://github.com/devinvenable/iso9797algorithm3 + uint8_t message[EMRTD_RETAIL_MAC_MAXLEN] = { 0x00 }; + + if (inputlen + 8 > sizeof(message)) { + PrintAndLogEx(ERR, "error (emrtd_retail_mac) input out-of-bounds, %zu bytes", inputlen); + return PM3_EOUTOFBOUND; + } + + const uint8_t *k0 = key; + const uint8_t *k1 = key + 8; + + size_t blocksize = emrtd_pad_block(input, inputlen, 8, message); + + uint8_t intermediate[8] = { 0x00 }; + uint8_t intermediate_des[8] = { 0x00 }; + + for (size_t i = 0; i < (blocksize / 8); i++) { + for (int x = 0; x < 8; x++) { + intermediate[x] ^= message[(i * 8) + x]; + } + des_encrypt(intermediate_des, intermediate, k0); + memcpy(intermediate, intermediate_des, 8); + } + + des_decrypt(intermediate_des, intermediate, k1); + des_encrypt(output, intermediate_des, k0); + return PM3_SUCCESS; +} + +//----------------------------------------------------------------------------- +// Secure messaging session +//----------------------------------------------------------------------------- + +void emrtd_sm_clear(emrtd_session_t *ssn) { + memset(ssn, 0, sizeof(emrtd_session_t)); + ssn->type = EMRTD_SM_NONE; +} + +int emrtd_sm_setup(emrtd_session_t *ssn, emrtd_pace_cipher_t cipher, const uint8_t *ks_enc, const uint8_t *ks_mac) { + size_t keylen; + switch (cipher) { + case EMRTD_PACE_CIPHER_3DES: + ssn->type = EMRTD_SM_3DES; + ssn->ssclen = 8; + keylen = 16; + break; + case EMRTD_PACE_CIPHER_AES128: + ssn->type = EMRTD_SM_AES; + ssn->ssclen = 16; + keylen = 16; + break; + case EMRTD_PACE_CIPHER_AES192: + ssn->type = EMRTD_SM_AES; + ssn->ssclen = 16; + keylen = 24; + break; + case EMRTD_PACE_CIPHER_AES256: + ssn->type = EMRTD_SM_AES; + ssn->ssclen = 16; + keylen = 32; + break; + default: + return PM3_EINVARG; + } + + ssn->keylen = keylen; + memcpy(ssn->ks_enc, ks_enc, keylen); + memcpy(ssn->ks_mac, ks_mac, keylen); + memset(ssn->ssc, 0x00, sizeof(ssn->ssc)); + return PM3_SUCCESS; +} + +size_t emrtd_sm_blocksize(const emrtd_session_t *ssn) { + return (ssn->type == EMRTD_SM_AES) ? 16 : 8; +} + +void emrtd_sm_bump_ssc(emrtd_session_t *ssn) { + PrintAndLogEx(DEBUG, "ssc-b: %s", sprint_hex_inrow(ssn->ssc, ssn->ssclen)); + for (int i = (int)ssn->ssclen - 1; i >= 0; i--) { + ssn->ssc[i]++; + if (ssn->ssc[i] != 0x00) { + break; + } + } + PrintAndLogEx(DEBUG, "ssc-a: %s", sprint_hex_inrow(ssn->ssc, ssn->ssclen)); +} + +static int emrtd_aes_setkey_enc(mbedtls_aes_context *aes, const emrtd_session_t *ssn, const uint8_t *key) { + return mbedtls_aes_setkey_enc(aes, key, ssn->keylen * 8); +} + +// IV for AES secure messaging: E(KSenc, SSC) in ECB mode, ICAO 9303-11 9.8.6.1 +static int emrtd_sm_aes_iv(const emrtd_session_t *ssn, uint8_t *iv) { + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + int res = emrtd_aes_setkey_enc(&aes, ssn, ssn->ks_enc); + if (res == 0) { + res = mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, ssn->ssc, iv); + } + mbedtls_aes_free(&aes); + return (res == 0) ? PM3_SUCCESS : PM3_ESOFT; +} + +// The MAC algorithm that belongs to a cipher, applied to the data as given. +// 3DES is ISO 9797-1 MAC algorithm 3, which pads internally; AES is CMAC, which +// takes any length. Used directly for the PACE authentication tokens. +static int emrtd_mac_raw(emrtd_pace_cipher_t cipher, const uint8_t *key, size_t keylen, + const uint8_t *input, size_t inputlen, uint8_t *mac) { + if (cipher == EMRTD_PACE_CIPHER_3DES) { + return emrtd_retail_mac(key, input, inputlen, mac); + } + + // Note: libpcrypto's aes_cmac()/aes_cmac8() are not usable here. The former + // is AES-CMAC-PRF-128 (RFC 4615) and the latter truncates by taking every + // second byte, neither of which is what ICAO 9303-11 asks for. + mbedtls_cipher_type_t ct; + switch (keylen) { + case 16: + ct = MBEDTLS_CIPHER_AES_128_ECB; + break; + case 24: + ct = MBEDTLS_CIPHER_AES_192_ECB; + break; + case 32: + ct = MBEDTLS_CIPHER_AES_256_ECB; + break; + default: + return PM3_EINVARG; + } + + const mbedtls_cipher_info_t *ci = mbedtls_cipher_info_from_type(ct); + if (ci == NULL) { + return PM3_ESOFT; + } + + uint8_t full[16] = { 0x00 }; + if (mbedtls_cipher_cmac(ci, key, keylen * 8, input, inputlen, full) != 0) { + return PM3_ESOFT; + } + + // ICAO 9303-11 9.8.6 asks for a MAC length of 8 bytes + memcpy(mac, full, 8); + return PM3_SUCCESS; +} + +int emrtd_sm_mac(const emrtd_session_t *ssn, const uint8_t *input, size_t inputlen, uint8_t *mac) { + if (ssn->type == EMRTD_SM_3DES) { + // the retail MAC pads the input itself, which is step e.2 + return emrtd_mac_raw(EMRTD_PACE_CIPHER_3DES, ssn->ks_mac, ssn->keylen, input, inputlen, mac); + } + + if (ssn->type != EMRTD_SM_AES) { + return PM3_EINVARG; + } + + // ICAO 9303-11 9.8.6.1 step e.2: "Concatenate SSC and M and add padding". + // CMAC does not need the padding, but the step applies to AES all the same, + // verified against a document doing PACE with AES-CMAC-256 (a chip that is + // sent the unpadded input answers 6988, incorrect SM data object). + uint8_t padded[EMRTD_SM_MAC_MAXLEN] = { 0x00 }; + if ((inputlen + 16) > sizeof(padded)) { + PrintAndLogEx(ERR, "error (emrtd_sm_mac) input out-of-bounds, %zu bytes", inputlen); + return PM3_EOUTOFBOUND; + } + + size_t paddedlen = emrtd_pad_block(input, inputlen, 16, padded); + return emrtd_mac_raw(EMRTD_PACE_CIPHER_AES128, ssn->ks_mac, ssn->keylen, padded, paddedlen, mac); +} + +int emrtd_sm_encrypt(const emrtd_session_t *ssn, const uint8_t *input, size_t inputlen, uint8_t *output) { + if (ssn->type == EMRTD_SM_3DES) { + uint8_t iv[8] = { 0x00 }; + emrtd_des3_encrypt_cbc(iv, ssn->ks_enc, input, inputlen, output); + return PM3_SUCCESS; + } + + if (ssn->type != EMRTD_SM_AES) { + return PM3_EINVARG; + } + + uint8_t iv[16] = { 0x00 }; + int res = emrtd_sm_aes_iv(ssn, iv); + if (res != PM3_SUCCESS) { + return res; + } + + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + res = emrtd_aes_setkey_enc(&aes, ssn, ssn->ks_enc); + if (res == 0) { + res = mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, inputlen, iv, input, output); + } + mbedtls_aes_free(&aes); + return (res == 0) ? PM3_SUCCESS : PM3_ESOFT; +} + +int emrtd_sm_decrypt(const emrtd_session_t *ssn, const uint8_t *input, size_t inputlen, uint8_t *output) { + if (ssn->type == EMRTD_SM_3DES) { + uint8_t iv[8] = { 0x00 }; + emrtd_des3_decrypt_cbc(iv, ssn->ks_enc, input, inputlen, output); + return PM3_SUCCESS; + } + + if (ssn->type != EMRTD_SM_AES) { + return PM3_EINVARG; + } + + uint8_t iv[16] = { 0x00 }; + int res = emrtd_sm_aes_iv(ssn, iv); + if (res != PM3_SUCCESS) { + return res; + } + + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + res = mbedtls_aes_setkey_dec(&aes, ssn->ks_enc, ssn->keylen * 8); + if (res == 0) { + res = mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, inputlen, iv, input, output); + } + mbedtls_aes_free(&aes); + return (res == 0) ? PM3_SUCCESS : PM3_ESOFT; +} + +//----------------------------------------------------------------------------- +// BER-TLV +//----------------------------------------------------------------------------- + +bool emrtd_tlv_next(const uint8_t **cur, const uint8_t *end, uint32_t *tag, const uint8_t **value, size_t *valuelen) { + const uint8_t *p = *cur; + + if (p >= end) { + return false; + } + + uint32_t t = *p++; + if ((t & 0x1F) == 0x1F) { + // multi byte tag + do { + if (p >= end || (t > 0x00FFFFFF)) { + return false; + } + t = (t << 8) | *p; + } while ((*p++ & 0x80) != 0); + } + + if (p >= end) { + return false; + } + + size_t len = *p++; + if (len > 0x80) { + size_t lenlen = len & 0x7F; + if ((lenlen > 4) || ((size_t)(end - p) < lenlen)) { + return false; + } + len = 0; + for (size_t i = 0; i < lenlen; i++) { + len = (len << 8) | *p++; + } + } else if (len == 0x80) { + // indefinite length, not valid in the structures we parse + return false; + } + + if ((size_t)(end - p) < len) { + return false; + } + + *tag = t; + *value = p; + *valuelen = len; + *cur = p + len; + return true; +} + +size_t emrtd_tlv_write_header(uint8_t *out, size_t outlen, uint32_t tag, size_t len) { + size_t taglen = (tag > 0xFF) ? 2 : 1; + size_t lenlen; + + if (len < 0x80) { + lenlen = 1; + } else if (len <= 0xFF) { + lenlen = 2; + } else if (len <= 0xFFFF) { + lenlen = 3; + } else { + return 0; + } + + if (outlen < taglen + lenlen) { + return 0; + } + + size_t o = 0; + if (taglen == 2) { + out[o++] = (tag >> 8) & 0xFF; + } + out[o++] = tag & 0xFF; + + if (lenlen == 1) { + out[o++] = (uint8_t)len; + } else if (lenlen == 2) { + out[o++] = 0x81; + out[o++] = (uint8_t)len; + } else { + out[o++] = 0x82; + out[o++] = (uint8_t)(len >> 8); + out[o++] = (uint8_t)len; + } + return o; +} + +//----------------------------------------------------------------------------- +// EF_CardAccess +//----------------------------------------------------------------------------- + +#define ASN1_TAG_INTEGER 0x02 +#define ASN1_TAG_OID 0x06 +#define ASN1_TAG_SEQUENCE 0x30 +#define ASN1_TAG_SET 0x31 + +static bool emrtd_asn1_uint(const uint8_t *value, size_t valuelen, uint32_t *out) { + if ((valuelen == 0) || (valuelen > 5)) { + return false; + } + // skip a single leading zero used to keep the value positive + if ((valuelen == 5) && (value[0] != 0x00)) { + return false; + } + uint32_t v = 0; + for (size_t i = 0; i < valuelen; i++) { + v = (v << 8) | value[i]; + } + *out = v; + return true; +} + +// The PACEDomainParameterInfo protocol OIDs, TR-03110 part 3, A.1.1. +// 0.4.0.127.0.7.2.2.4.1 (DH) and .2 (ECDH) +static const uint8_t oid_pace_dh_dp[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01}; +static const uint8_t oid_pace_ecdh_dp[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02}; + +static void emrtd_pace_classify(emrtd_paceinfo_t *info) { + info->supported = false; + + if (info->alg == NULL) { + info->reason = "unknown protocol OID"; + return; + } + + if (info->alg->ka == EMRTD_PACE_KA_DH) { + // MBEDTLS_DHM_C is deliberately left out of common/mbedtls/config.h and + // enabling it is out of scope, so DH (MODP) mapping cannot be done here. + info->reason = "unsupported (DH not compiled in)"; + return; + } + + if (info->alg->mapping == EMRTD_PACE_MAP_IM) { + info->reason = "unsupported (Integrated Mapping not implemented)"; + return; + } + + if (info->has_param == false) { + info->reason = "no standardized domain parameter id"; + return; + } + + if (info->sdp == NULL) { + info->reason = "unknown domain parameter id"; + return; + } + + if (info->sdp->is_ec == false) { + info->reason = "unsupported (MODP group, DH not compiled in)"; + return; + } + + if (info->sdp->curve == MBEDTLS_ECP_DP_NONE) { + info->reason = "unsupported curve (not compiled into mbedtls)"; + return; + } + + info->supported = true; + info->reason = NULL; +} + +static int emrtd_pace_cipher_rank(emrtd_pace_cipher_t cipher) { + switch (cipher) { + case EMRTD_PACE_CIPHER_3DES: + return 1; + case EMRTD_PACE_CIPHER_AES128: + return 2; + case EMRTD_PACE_CIPHER_AES192: + return 3; + case EMRTD_PACE_CIPHER_AES256: + return 4; + } + return 0; +} + +// Chip Authentication Mapping would be the stronger choice, since it proves the +// chip is not a clone. We cannot complete that proof yet (see +// emrtd_pace_cam_verify), so a CAM session buys nothing over a Generic Mapping +// one and costs an EF_DG14 read. Prefer GM until the proof works, and fall back +// to CAM only for documents that offer nothing else. +int emrtd_pace_rank(const emrtd_paceinfo_t *info) { + if ((info->supported == false) || (info->alg == NULL)) { + return 0; + } + int rank = emrtd_pace_cipher_rank(info->alg->cipher) * 2; + if (info->alg->mapping == EMRTD_PACE_MAP_GM) { + rank += 1; + } + return rank; +} + +// One SecurityInfo: SEQUENCE { OID protocol, ... } +static void emrtd_pace_parse_securityinfo(const uint8_t *seq, size_t seqlen, emrtd_cardaccess_t *out) { + const uint8_t *cur = seq; + const uint8_t *end = seq + seqlen; + uint32_t tag; + const uint8_t *val; + size_t vlen; + + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + return; + } + + if ((tag != ASN1_TAG_OID) || (vlen == 0) || (vlen > EMRTD_PACE_OID_MAXLEN)) { + return; + } + + // PACEDomainParameterInfo carries the algorithm identifier instead of a + // version number. We only report it, the parameters we act on come from + // the PACEInfo entries. + bool is_domain_param = ((vlen == sizeof(oid_pace_dh_dp)) && + ((memcmp(val, oid_pace_dh_dp, vlen) == 0) || + (memcmp(val, oid_pace_ecdh_dp, vlen) == 0))); + + if (out->count >= EMRTD_PACE_MAX_INFOS) { + return; + } + + emrtd_paceinfo_t *info = &out->infos[out->count]; + memset(info, 0, sizeof(emrtd_paceinfo_t)); + memcpy(info->oid, val, vlen); + info->oidlen = vlen; + info->alg = emrtd_pace_alg_by_oid(val, vlen); + + if (is_domain_param) { + // SEQUENCE { OID, AlgorithmIdentifier, INTEGER parameterId OPTIONAL } + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + return; + } + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { + uint32_t v = 0; + if (emrtd_asn1_uint(val, vlen, &v) && (v <= 0xFF)) { + info->has_param = true; + info->param_id = (uint8_t)v; + info->sdp = emrtd_pace_sdp_by_id(info->param_id); + } + } + info->supported = false; + info->reason = "domain parameter definition, informational"; + out->count++; + return; + } + + // PACEInfo ::= SEQUENCE { protocol OID, version INTEGER, parameterId INTEGER OPTIONAL } + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + return; + } + if (tag != ASN1_TAG_INTEGER) { + return; + } + if (emrtd_asn1_uint(val, vlen, &info->version) == false) { + return; + } + + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { + uint32_t v = 0; + if (emrtd_asn1_uint(val, vlen, &v) && (v <= 0xFF)) { + info->has_param = true; + info->param_id = (uint8_t)v; + info->sdp = emrtd_pace_sdp_by_id(info->param_id); + } + } + + emrtd_pace_classify(info); + out->count++; +} + +int emrtd_pace_parse_cardaccess(const uint8_t *data, size_t datalen, emrtd_cardaccess_t *out) { + memset(out, 0, sizeof(emrtd_cardaccess_t)); + out->best = -1; + + if ((data == NULL) || (datalen == 0)) { + return PM3_EINVARG; + } + + const uint8_t *cur = data; + const uint8_t *end = data + datalen; + uint32_t tag; + const uint8_t *val; + size_t vlen; + + // EF_CardAccess is a SET OF SecurityInfo. Accept a SEQUENCE too, some + // documents in the wild get this wrong. + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + PrintAndLogEx(DEBUG, "EF_CardAccess: not a valid TLV"); + return PM3_ESOFT; + } + + if ((tag != ASN1_TAG_SET) && (tag != ASN1_TAG_SEQUENCE)) { + PrintAndLogEx(DEBUG, "EF_CardAccess: unexpected top level tag %02X", tag); + return PM3_ESOFT; + } + + const uint8_t *icur = val; + const uint8_t *iend = val + vlen; + + while (emrtd_tlv_next(&icur, iend, &tag, &val, &vlen)) { + if (tag != ASN1_TAG_SEQUENCE) { + continue; + } + emrtd_pace_parse_securityinfo(val, vlen, out); + } + + if (out->count == 0) { + return PM3_ESOFT; + } + + // Pick the strongest usable algorithm + int bestrank = 0; + for (size_t i = 0; i < out->count; i++) { + int rank = emrtd_pace_rank(&out->infos[i]); + if (rank > bestrank) { + bestrank = rank; + out->best = (int)i; + } + } + + return PM3_SUCCESS; +} + +//----------------------------------------------------------------------------- +// PACE key derivation +//----------------------------------------------------------------------------- + +char emrtd_calculate_check_digit(const char *data) { + const int mrz_weight[] = {7, 3, 1}; + int value, cd = 0; + + for (size_t i = 0; i < strlen(data); i++) { + char d = data[i]; + if ('A' <= d && d <= 'Z') { + value = d - 55; + } else if ('a' <= d && d <= 'z') { + value = d - 87; + } else if (d == '<') { + value = 0; + } else { // Numbers + value = d - 48; + } + cd += value * mrz_weight[i % 3]; + } + return cd % 10; +} + +int emrtd_pace_kmrz(const char *documentnumber, const char *dob, const char *expiry, char *out, size_t outlen) { + if ((documentnumber == NULL) || (dob == NULL) || (expiry == NULL)) { + return PM3_EINVARG; + } + + char docnumcd = emrtd_calculate_check_digit(documentnumber); + char dobcd = emrtd_calculate_check_digit(dob); + char expirycd = emrtd_calculate_check_digit(expiry); + + int n = snprintf(out, outlen, "%s%i%s%i%s%i", documentnumber, docnumcd, dob, dobcd, expiry, expirycd); + if ((n < 0) || ((size_t)n >= outlen)) { + return PM3_EOUTOFBOUND; + } + return PM3_SUCCESS; +} + +int emrtd_pace_password_mrz(const char *documentnumber, const char *dob, const char *expiry, uint8_t *k, size_t *klen) { + char kmrz[25] = { 0x00 }; + + int res = emrtd_pace_kmrz(documentnumber, dob, expiry, kmrz, sizeof(kmrz)); + if (res != PM3_SUCCESS) { + return res; + } + + PrintAndLogEx(DEBUG, "kmrz.............. %s", kmrz); + sha1hash((uint8_t *)kmrz, strlen(kmrz), k); + *klen = 20; + return PM3_SUCCESS; +} + +int emrtd_pace_password_can(const char *can, uint8_t *k, size_t *klen) { + if (can == NULL) { + return PM3_EINVARG; + } + + size_t len = strlen(can); + if ((len == 0) || (len > EMRTD_PACE_SECRET_MAXLEN)) { + return PM3_EINVARG; + } + + // The CAN is used as is, ICAO 9303-11 9.7.2 + memcpy(k, can, len); + *klen = len; + return PM3_SUCCESS; +} + +int emrtd_pace_kdf(emrtd_pace_cipher_t cipher, const uint8_t *k, size_t klen, uint32_t counter, uint8_t *out, size_t *outlen) { + // TR-03110 part 3, A.2.3 + uint8_t buf[EMRTD_PACE_SECRET_MAXLEN + 4] = { 0x00 }; + + if (klen > EMRTD_PACE_SECRET_MAXLEN) { + PrintAndLogEx(ERR, "error (emrtd_pace_kdf) secret out-of-bounds, %zu bytes", klen); + return PM3_EOUTOFBOUND; + } + + memcpy(buf, k, klen); + buf[klen + 0] = (counter >> 24) & 0xFF; + buf[klen + 1] = (counter >> 16) & 0xFF; + buf[klen + 2] = (counter >> 8) & 0xFF; + buf[klen + 3] = counter & 0xFF; + + uint8_t hash[64] = { 0x00 }; + size_t keylen; + + switch (cipher) { + case EMRTD_PACE_CIPHER_3DES: + case EMRTD_PACE_CIPHER_AES128: + sha1hash(buf, klen + 4, hash); + keylen = 16; + break; + case EMRTD_PACE_CIPHER_AES192: + sha256hash(buf, klen + 4, hash); + keylen = 24; + break; + case EMRTD_PACE_CIPHER_AES256: + sha256hash(buf, klen + 4, hash); + keylen = 32; + break; + default: + return PM3_EINVARG; + } + + memcpy(out, hash, keylen); + + if (cipher == EMRTD_PACE_CIPHER_3DES) { + // two key 3DES, odd parity per byte + mbedtls_des_key_set_parity(out); + mbedtls_des_key_set_parity(out + 8); + } + + *outlen = keylen; + return PM3_SUCCESS; +} + +int emrtd_pace_decrypt_nonce(emrtd_pace_cipher_t cipher, const uint8_t *kpi, const uint8_t *z, size_t zlen, uint8_t *s) { + size_t blocksize = (cipher == EMRTD_PACE_CIPHER_3DES) ? 8 : 16; + + if ((zlen == 0) || ((zlen % blocksize) != 0) || (zlen > 32)) { + PrintAndLogEx(ERR, "PACE: bad encrypted nonce length %zu", zlen); + return PM3_EINVARG; + } + + if (cipher == EMRTD_PACE_CIPHER_3DES) { + uint8_t iv[8] = { 0x00 }; + emrtd_des3_decrypt_cbc(iv, kpi, z, zlen, s); + return PM3_SUCCESS; + } + + size_t keybits; + switch (cipher) { + case EMRTD_PACE_CIPHER_3DES: + // handled above + return PM3_EINVARG; + case EMRTD_PACE_CIPHER_AES128: + keybits = 128; + break; + case EMRTD_PACE_CIPHER_AES192: + keybits = 192; + break; + case EMRTD_PACE_CIPHER_AES256: + keybits = 256; + break; + default: + return PM3_EINVARG; + } + + uint8_t iv[16] = { 0x00 }; + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + int res = mbedtls_aes_setkey_dec(&aes, kpi, keybits); + if (res == 0) { + res = mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, zlen, iv, z, s); + } + mbedtls_aes_free(&aes); + return (res == 0) ? PM3_SUCCESS : PM3_ESOFT; +} + +//----------------------------------------------------------------------------- +// ECDH with Generic Mapping +//----------------------------------------------------------------------------- + +size_t emrtd_pace_ec_pointlen(mbedtls_ecp_group_id curve) { + mbedtls_ecp_group grp; + mbedtls_ecp_group_init(&grp); + + size_t len = 0; + if (mbedtls_ecp_group_load(&grp, curve) == 0) { + len = 1 + (2 * ((grp.pbits + 7) / 8)); + } + + mbedtls_ecp_group_free(&grp); + return len; +} + +static int emrtd_ecp_write(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt, uint8_t *out, size_t *outlen) { + size_t written = 0; + int res = mbedtls_ecp_point_write_binary(grp, pt, MBEDTLS_ECP_PF_UNCOMPRESSED, &written, out, EMRTD_EC_POINT_MAXLEN); + if (res != 0) { + return PM3_ESOFT; + } + *outlen = written; + return PM3_SUCCESS; +} + +// Note: mbedtls builds the standard groups out of static const MPI limbs, so +// grp->G must never be written to. A caller supplied generator is parsed into +// a point of its own and handed back through *out instead. +static int emrtd_ecp_group_with_base(mbedtls_ecp_group *grp, mbedtls_ecp_group_id curve, + const uint8_t *base, size_t baselen, + mbedtls_ecp_point *custom, const mbedtls_ecp_point **out) { + if (mbedtls_ecp_group_load(grp, curve) != 0) { + PrintAndLogEx(ERR, "PACE: failed to load curve"); + return PM3_ESOFT; + } + + if (out == NULL) { + return PM3_SUCCESS; + } + + if (base == NULL) { + *out = &grp->G; + return PM3_SUCCESS; + } + + if (mbedtls_ecp_point_read_binary(grp, custom, base, baselen) != 0) { + PrintAndLogEx(ERR, "PACE: failed to parse mapped generator"); + return PM3_ESOFT; + } + + if (mbedtls_ecp_check_pubkey(grp, custom) != 0) { + PrintAndLogEx(ERR, "PACE: mapped generator is not on the curve"); + return PM3_ESOFT; + } + + *out = custom; + return PM3_SUCCESS; +} + +int emrtd_pace_ec_pubkey(mbedtls_ecp_group_id curve, const uint8_t *base, size_t baselen, + const uint8_t *priv, size_t privlen, uint8_t *pub, size_t *publen) { + mbedtls_ecp_group grp; + mbedtls_mpi d; + mbedtls_ecp_point Q, custom; + const mbedtls_ecp_point *G = NULL; + + mbedtls_ecp_group_init(&grp); + mbedtls_mpi_init(&d); + mbedtls_ecp_point_init(&Q); + mbedtls_ecp_point_init(&custom); + + int res = emrtd_ecp_group_with_base(&grp, curve, base, baselen, &custom, &G); + if (res != PM3_SUCCESS) { + goto out; + } + + res = PM3_ESOFT; + if (mbedtls_mpi_read_binary(&d, priv, privlen) != 0) { + goto out; + } + if (mbedtls_ecp_mul(&grp, &Q, &d, G, NULL, NULL) != 0) { + goto out; + } + res = emrtd_ecp_write(&grp, &Q, pub, publen); + +out: + mbedtls_ecp_point_free(&custom); + mbedtls_ecp_point_free(&Q); + mbedtls_mpi_free(&d); + mbedtls_ecp_group_free(&grp); + return res; +} + +int emrtd_pace_ec_keygen(mbedtls_ecp_group_id curve, const uint8_t *base, size_t baselen, + uint8_t *priv, size_t *privlen, uint8_t *pub, size_t *publen) { + mbedtls_ecp_group grp; + mbedtls_mpi d; + mbedtls_ecp_point Q, custom; + const mbedtls_ecp_point *G = NULL; + pcrypto_rng_t rng = {0}; + + mbedtls_ecp_group_init(&grp); + mbedtls_mpi_init(&d); + mbedtls_ecp_point_init(&Q); + mbedtls_ecp_point_init(&custom); + + int res = pcrypto_rng_init(&rng, (const uint8_t *)"emrtd-pace", 10); + if (res != PM3_SUCCESS) { + goto out; + } + + res = emrtd_ecp_group_with_base(&grp, curve, base, baselen, &custom, &G); + if (res != PM3_SUCCESS) { + goto out; + } + + res = PM3_ESOFT; + if (mbedtls_ecp_gen_keypair_base(&grp, G, &d, &Q, mbedtls_ctr_drbg_random, &rng.ctr_drbg) != 0) { + PrintAndLogEx(ERR, "PACE: ephemeral key generation failed"); + goto out; + } + + *privlen = (grp.nbits + 7) / 8; + if (mbedtls_mpi_write_binary(&d, priv, *privlen) != 0) { + goto out; + } + + res = emrtd_ecp_write(&grp, &Q, pub, publen); + +out: + pcrypto_rng_free(&rng); + mbedtls_ecp_point_free(&custom); + mbedtls_ecp_point_free(&Q); + mbedtls_mpi_free(&d); + mbedtls_ecp_group_free(&grp); + return res; +} + +int emrtd_pace_ec_gm(mbedtls_ecp_group_id curve, const uint8_t *s, size_t slen, + const uint8_t *priv, size_t privlen, const uint8_t *pk_ic, size_t pk_ic_len, + uint8_t *mapped, size_t *mappedlen) { + mbedtls_ecp_group grp; + mbedtls_mpi d, sm, one; + mbedtls_ecp_point PK, H, G; + + mbedtls_ecp_group_init(&grp); + mbedtls_mpi_init(&d); + mbedtls_mpi_init(&sm); + mbedtls_mpi_init(&one); + mbedtls_ecp_point_init(&PK); + mbedtls_ecp_point_init(&H); + mbedtls_ecp_point_init(&G); + + int res = emrtd_ecp_group_with_base(&grp, curve, NULL, 0, NULL, NULL); + if (res != PM3_SUCCESS) { + goto out; + } + + res = PM3_ESOFT; + if (mbedtls_ecp_point_read_binary(&grp, &PK, pk_ic, pk_ic_len) != 0) { + PrintAndLogEx(ERR, "PACE: chip mapping key is not a valid point"); + goto out; + } + if (mbedtls_ecp_check_pubkey(&grp, &PK) != 0) { + PrintAndLogEx(ERR, "PACE: chip mapping key is not on the curve"); + goto out; + } + if (mbedtls_mpi_read_binary(&d, priv, privlen) != 0) { + goto out; + } + if (mbedtls_mpi_read_binary(&sm, s, slen) != 0) { + goto out; + } + if (mbedtls_mpi_lset(&one, 1) != 0) { + goto out; + } + + // H = x * PK_IC + if (mbedtls_ecp_mul(&grp, &H, &d, &PK, NULL, NULL) != 0) { + goto out; + } + + // G' = s*G + H + if (mbedtls_ecp_muladd(&grp, &G, &sm, &grp.G, &one, &H) != 0) { + goto out; + } + + if (mbedtls_ecp_is_zero(&G)) { + PrintAndLogEx(ERR, "PACE: mapped generator is the point at infinity"); + goto out; + } + + res = emrtd_ecp_write(&grp, &G, mapped, mappedlen); + +out: + mbedtls_ecp_point_free(&G); + mbedtls_ecp_point_free(&H); + mbedtls_ecp_point_free(&PK); + mbedtls_mpi_free(&one); + mbedtls_mpi_free(&sm); + mbedtls_mpi_free(&d); + mbedtls_ecp_group_free(&grp); + return res; +} + +int emrtd_pace_ec_shared_x(mbedtls_ecp_group_id curve, const uint8_t *priv, size_t privlen, + const uint8_t *pk_ic, size_t pk_ic_len, uint8_t *out, size_t *outlen) { + mbedtls_ecp_group grp; + mbedtls_mpi d; + mbedtls_ecp_point PK, K; + + mbedtls_ecp_group_init(&grp); + mbedtls_mpi_init(&d); + mbedtls_ecp_point_init(&PK); + mbedtls_ecp_point_init(&K); + + int res = emrtd_ecp_group_with_base(&grp, curve, NULL, 0, NULL, NULL); + if (res != PM3_SUCCESS) { + goto out; + } + + res = PM3_ESOFT; + if (mbedtls_ecp_point_read_binary(&grp, &PK, pk_ic, pk_ic_len) != 0) { + goto out; + } + if (mbedtls_ecp_check_pubkey(&grp, &PK) != 0) { + PrintAndLogEx(ERR, "PACE: chip agreement key is not on the curve"); + goto out; + } + if (mbedtls_mpi_read_binary(&d, priv, privlen) != 0) { + goto out; + } + if (mbedtls_ecp_mul(&grp, &K, &d, &PK, NULL, NULL) != 0) { + goto out; + } + if (mbedtls_ecp_is_zero(&K)) { + PrintAndLogEx(ERR, "PACE: shared secret is the point at infinity"); + goto out; + } + + // ICAO 9303-11 4.4.3.3, only the x coordinate is used + *outlen = (grp.pbits + 7) / 8; + if (mbedtls_mpi_write_binary(&K.X, out, *outlen) != 0) { + goto out; + } + res = PM3_SUCCESS; + +out: + mbedtls_ecp_point_free(&K); + mbedtls_ecp_point_free(&PK); + mbedtls_mpi_free(&d); + mbedtls_ecp_group_free(&grp); + return res; +} + +int emrtd_pace_token(const emrtd_pacealg_t *alg, const uint8_t *ks_mac, + const uint8_t *pubkey, size_t pubkeylen, uint8_t *token) { + // ICAO 9303-11 4.4.3.4: + // T = MAC(KSmac, 7F49 || 06 || 86 ) + uint8_t inner[EMRTD_EC_POINT_MAXLEN + 32] = { 0x00 }; + size_t o = 0; + + o += emrtd_tlv_write_header(inner + o, sizeof(inner) - o, 0x06, alg->oidlen); + memcpy(inner + o, alg->oid, alg->oidlen); + o += alg->oidlen; + + size_t hdr = emrtd_tlv_write_header(inner + o, sizeof(inner) - o, 0x86, pubkeylen); + if ((hdr == 0) || (o + hdr + pubkeylen > sizeof(inner))) { + return PM3_EOUTOFBOUND; + } + o += hdr; + memcpy(inner + o, pubkey, pubkeylen); + o += pubkeylen; + + uint8_t data[sizeof(inner) + 8] = { 0x00 }; + size_t dlen = emrtd_tlv_write_header(data, sizeof(data), 0x7F49, o); + if (dlen == 0) { + return PM3_EOUTOFBOUND; + } + memcpy(data + dlen, inner, o); + dlen += o; + + PrintAndLogEx(DEBUG, "token input....... %s", sprint_hex_inrow(data, dlen)); + + // The token is the plain MAC of the data block, it carries no SSC and gets + // none of the secure messaging padding of ICAO 9303-11 9.8.6.1 step e.2 + return emrtd_mac_raw(alg->cipher, ks_mac, alg->keylen, data, dlen, token); +} + +//----------------------------------------------------------------------------- +// Chip Authentication Mapping +//----------------------------------------------------------------------------- + +// TR-03110 part 3, A.1.1.1: id-PK-ECDH is 0.4.0.127.0.7.2.2.1.2 +static const uint8_t oid_pk_ecdh[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x01, 0x02}; + +#define ASN1_TAG_BITSTRING 0x03 + +int emrtd_pace_find_ca_pubkey(const uint8_t *data, size_t datalen, size_t index, uint8_t *pub, size_t *publen) { + if ((data == NULL) || (datalen == 0)) { + return PM3_EINVARG; + } + + const uint8_t *cur = data; + const uint8_t *end = data + datalen; + uint32_t tag = 0; + const uint8_t *val = NULL; + size_t vlen = 0; + + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + return PM3_ESOFT; + } + + // EF_DG14 wraps the SET in tag 6E, EF_CardSecurity hands us the SET directly + if (tag == 0x6E) { + cur = val; + end = val + vlen; + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { + return PM3_ESOFT; + } + } + + if ((tag != ASN1_TAG_SET) && (tag != ASN1_TAG_SEQUENCE)) { + return PM3_ESOFT; + } + + const uint8_t *icur = val; + const uint8_t *iend = val + vlen; + size_t seen = 0; + + // SET OF SecurityInfo, we want ChipAuthenticationPublicKeyInfo + while (emrtd_tlv_next(&icur, iend, &tag, &val, &vlen)) { + + if (tag != ASN1_TAG_SEQUENCE) { + continue; + } + + const uint8_t *scur = val; + const uint8_t *send = val + vlen; + const uint8_t *sval = NULL; + size_t svlen = 0; + uint32_t stag = 0; + + if (emrtd_tlv_next(&scur, send, &stag, &sval, &svlen) == false) { + continue; + } + if ((stag != ASN1_TAG_OID) || (svlen != sizeof(oid_pk_ecdh)) || + (memcmp(sval, oid_pk_ecdh, svlen) != 0)) { + continue; + } + + // chipAuthenticationPublicKey ::= SubjectPublicKeyInfo + if ((emrtd_tlv_next(&scur, send, &stag, &sval, &svlen) == false) || (stag != ASN1_TAG_SEQUENCE)) { + continue; + } + + const uint8_t *kcur = sval; + const uint8_t *kend = sval + svlen; + + // AlgorithmIdentifier, skipped. The curve has to match the one PACE + // negotiated anyway, and that is what the caller checks against. + if (emrtd_tlv_next(&kcur, kend, &stag, &sval, &svlen) == false) { + continue; + } + + if ((emrtd_tlv_next(&kcur, kend, &stag, &sval, &svlen) == false) || (stag != ASN1_TAG_BITSTRING)) { + continue; + } + + // first byte of a BIT STRING is the number of unused bits + if ((svlen < 2) || (sval[0] != 0x00)) { + continue; + } + + if ((svlen - 1) > EMRTD_EC_POINT_MAXLEN) { + PrintAndLogEx(ERR, "error (emrtd_pace_find_ca_pubkey) key out-of-bounds, %zu bytes", svlen - 1); + return PM3_EOUTOFBOUND; + } + + if (seen++ < index) { + continue; + } + + memcpy(pub, sval + 1, svlen - 1); + *publen = svlen - 1; + return PM3_SUCCESS; + } + + return PM3_ESOFT; +} + +static const char *cam_encnames[] = { "CBC zero IV", "ECB", "CBC IV=E(KSenc,0)", "CBC IV=E(KSenc,1)", "not encrypted" }; +#define CAM_ENC_VARIANTS 5 + +// One candidate decryption of DO'8A'. Returns PM3_SUCCESS when it produced +// something, which says nothing about whether it is the right something. +static int emrtd_cam_decrypt(const emrtd_session_t *ssn, int variant, uint8_t *plain) { + + if (variant == 4) { + memcpy(plain, ssn->cam.enc_data, ssn->cam.enc_datalen); + return PM3_SUCCESS; + } + + mbedtls_aes_context aes; + mbedtls_aes_init(&aes); + + int mres = mbedtls_aes_setkey_dec(&aes, ssn->ks_enc, ssn->keylen * 8); + + if ((mres == 0) && (variant == 1)) { + for (size_t o = 0; (o < ssn->cam.enc_datalen) && (mres == 0); o += 16) { + mres = mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_DECRYPT, ssn->cam.enc_data + o, plain + o); + } + } else if (mres == 0) { + uint8_t iv[16] = { 0x00 }; + + if (variant >= 2) { + // the secure messaging IV construction, over the first two SSC values + uint8_t ssc[16] = { 0x00 }; + ssc[15] = (variant == 3) ? 0x01 : 0x00; + + mbedtls_aes_context ecb; + mbedtls_aes_init(&ecb); + if (mbedtls_aes_setkey_enc(&ecb, ssn->ks_enc, ssn->keylen * 8) == 0) { + mbedtls_aes_crypt_ecb(&ecb, MBEDTLS_AES_ENCRYPT, ssc, iv); + } + mbedtls_aes_free(&ecb); + } + + mres = mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, ssn->cam.enc_datalen, iv, + ssn->cam.enc_data, plain); + } + + mbedtls_aes_free(&aes); + return (mres == 0) ? PM3_SUCCESS : PM3_ESOFT; +} + +// Compares the part of a CBC plaintext that does not depend on the IV. +// Decrypting block i>0 uses only ciphertext, so everything past the first block +// is fixed no matter what IV the chip used. That makes it possible to confirm +// what CA_IC contains while still not knowing how the IV is built. +static bool emrtd_cam_tail_matches(const uint8_t *a, const uint8_t *b, size_t len) { + return (len > 16) && (memcmp(a + 16, b + 16, len - 16) == 0); +} + +void emrtd_pace_cam_dump(const emrtd_session_t *ssn, const uint8_t *pk_icc, size_t pk_icc_len) { + const emrtd_cam_t *cam = &ssn->cam; + + PrintAndLogEx(INFO, "CAM DO'8A' (%zu)... %s", cam->enc_datalen, + sprint_hex_inrow(cam->enc_data, cam->enc_datalen)); + PrintAndLogEx(INFO, "CAM PK.Map.IC..... %s", sprint_hex_inrow(cam->pk_map_ic, cam->pk_map_iclen)); + PrintAndLogEx(INFO, "CAM PK.DH.IC...... %s", sprint_hex_inrow(cam->pk_dh_ic, cam->pk_dh_iclen)); + PrintAndLogEx(INFO, "CAM PK.CA.IC...... %s", sprint_hex_inrow((uint8_t *)pk_icc, pk_icc_len)); + PrintAndLogEx(INFO, "CAM SK.Map.IFD.... %s", sprint_hex_inrow((uint8_t *)cam->sk_map_ifd, cam->sk_map_ifdlen)); + PrintAndLogEx(INFO, "CAM SK.DH.IFD..... %s", sprint_hex_inrow((uint8_t *)cam->sk_dh_ifd, cam->sk_dh_ifdlen)); + PrintAndLogEx(INFO, "CAM KSenc......... %s", sprint_hex_inrow((uint8_t *)ssn->ks_enc, ssn->keylen)); + + uint8_t plain[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + if (emrtd_cam_decrypt(ssn, 0, plain) != PM3_SUCCESS) { + return; + } + + size_t content = FindISO9797M2PaddingDataLen(plain, cam->enc_datalen); + if (content == 0) { + content = cam->enc_datalen; + } + + PrintAndLogEx(INFO, "CAM plaintext..... %s", sprint_hex_inrow(plain, content)); + PrintAndLogEx(INFO, " (first block depends on the IV, the rest does not)"); + + // Two readings of what the chip is proving, both testable on the tail alone + struct { + const char *name; + const uint8_t *priv; + size_t privlen; + } guesses[] = { + { "x( SK.Map.IFD * PK.CA.IC )", cam->sk_map_ifd, cam->sk_map_ifdlen }, + { "x( SK.DH.IFD * PK.CA.IC )", cam->sk_dh_ifd, cam->sk_dh_ifdlen }, + }; + + for (size_t i = 0; i < ARRAYLEN(guesses); i++) { + + if (guesses[i].privlen == 0) { + continue; + } + + uint8_t expected[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + size_t expectedlen = 0; + + if (emrtd_pace_ec_shared_x(cam->curve, guesses[i].priv, guesses[i].privlen, + pk_icc, pk_icc_len, expected, &expectedlen) != PM3_SUCCESS) { + continue; + } + + PrintAndLogEx(INFO, "CAM %s = %s", guesses[i].name, sprint_hex_inrow(expected, expectedlen)); + + if ((expectedlen == content) && emrtd_cam_tail_matches(expected, plain, content)) { + + // The content is confirmed, so the only thing still wrong is the + // IV, and it can be read straight off: with a zero IV the first + // plaintext block is D(C1), so IV = D(C1) xor the real first block. + uint8_t iv[16] = { 0x00 }; + for (int b = 0; b < 16; b++) { + iv[b] = plain[b] ^ expected[b]; + } + + PrintAndLogEx(SUCCESS, "CAM " _GREEN_("content confirmed") ", the chip proves %s", guesses[i].name); + PrintAndLogEx(SUCCESS, "CAM required IV... %s", sprint_hex_inrow(iv, sizeof(iv))); + return; + } + } + + PrintAndLogEx(WARNING, "CAM neither reading matches, the content is something else"); +} + +// The chip's proof, US 9215230 (Kuegler / Bender) and TR-03110 part 3: +// it sends t = SK.Map.IC * SK.CA.IC^-1 mod n, so that t * PK.CA.IC reproduces +// the ephemeral PACE key it used. Only a chip holding the static Chip +// Authentication private key can produce such a t. +static int emrtd_cam_check_scalar(mbedtls_ecp_group_id curve, const uint8_t *t, size_t tlen, + const uint8_t *pk_icc, size_t pk_icc_len, + const uint8_t *ephemeral, size_t ephemerallen) { + mbedtls_ecp_group grp; + mbedtls_mpi d; + mbedtls_ecp_point PK, R, expected; + + if ((ephemerallen == 0) || (pk_icc_len == 0)) { + return PM3_EINVARG; + } + + mbedtls_ecp_group_init(&grp); + mbedtls_mpi_init(&d); + mbedtls_ecp_point_init(&PK); + mbedtls_ecp_point_init(&R); + mbedtls_ecp_point_init(&expected); + + int res = emrtd_ecp_group_with_base(&grp, curve, NULL, 0, NULL, NULL); + if (res != PM3_SUCCESS) { + goto out; + } + + res = PM3_EWRONGANSWER; + + if (mbedtls_ecp_point_read_binary(&grp, &PK, pk_icc, pk_icc_len) != 0) { + goto out; + } + if (mbedtls_ecp_point_read_binary(&grp, &expected, ephemeral, ephemerallen) != 0) { + goto out; + } + if (mbedtls_mpi_read_binary(&d, t, tlen) != 0) { + goto out; + } + // a t outside [1, n-1] can never be the right answer + if (mbedtls_ecp_check_privkey(&grp, &d) != 0) { + goto out; + } + if (mbedtls_ecp_mul(&grp, &R, &d, &PK, NULL, NULL) != 0) { + goto out; + } + + res = (mbedtls_ecp_point_cmp(&R, &expected) == 0) ? PM3_SUCCESS : PM3_EWRONGANSWER; + +out: + mbedtls_ecp_point_free(&expected); + mbedtls_ecp_point_free(&R); + mbedtls_ecp_point_free(&PK); + mbedtls_mpi_free(&d); + mbedtls_ecp_group_free(&grp); + return res; +} + +int emrtd_pace_cam_verify(const emrtd_session_t *ssn, const uint8_t *pk_icc, size_t pk_icc_len, + const char **mode) { + const emrtd_cam_t *cam = &ssn->cam; + + if ((cam->negotiated == false) || (cam->enc_datalen == 0)) { + return PM3_EINVARG; + } + + if ((cam->enc_datalen % 16) != 0) { + PrintAndLogEx(ERR, "CAM: encrypted authentication data is not a whole number of blocks (%zu)", cam->enc_datalen); + return PM3_ESOFT; + } + + static char modebuf[80]; + uint8_t plain[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + + // "the chip's private ephemeral key from PACE" is ambiguous: PACE generates + // two of them, the mapping key of step 2 and the agreement key of step 3. + struct { + const char *name; + const uint8_t *key; + size_t keylen; + } ephemerals[] = { + { "PK.Map.IC", cam->pk_map_ic, cam->pk_map_iclen }, + { "PK.DH.IC", cam->pk_dh_ic, cam->pk_dh_iclen }, + }; + + for (int enc = 0; enc < CAM_ENC_VARIANTS; enc++) { + + if (emrtd_cam_decrypt(ssn, enc, plain) != PM3_SUCCESS) { + continue; + } + + size_t tlen = FindISO9797M2PaddingDataLen(plain, cam->enc_datalen); + if (tlen == 0) { + tlen = cam->enc_datalen; + } + + PrintAndLogEx(DEBUG, "CAM candidate (%s)... %s", cam_encnames[enc], sprint_hex_inrow(plain, tlen)); + + for (size_t e = 0; e < ARRAYLEN(ephemerals); e++) { + + if (emrtd_cam_check_scalar(cam->curve, plain, tlen, pk_icc, pk_icc_len, + ephemerals[e].key, ephemerals[e].keylen) == PM3_SUCCESS) { + snprintf(modebuf, sizeof(modebuf), "%s, t * PK.CA.IC == %s", cam_encnames[enc], ephemerals[e].name); + if (mode != NULL) { + *mode = modebuf; + } + return PM3_SUCCESS; + } + } + } + + return PM3_EWRONGANSWER; +} diff --git a/client/src/emrtd/emrtd_pace.h b/client/src/emrtd/emrtd_pace.h new file mode 100644 index 000000000..e42f8189d --- /dev/null +++ b/client/src/emrtd/emrtd_pace.h @@ -0,0 +1,245 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// PACE (Password Authenticated Connection Establishment) primitives for eMRTD +// +// ICAO Doc 9303 Part 11, section 4.4 and BSI TR-03110 part 3, section 3.2. +// Everything in here is pure crypto / parsing so that it can be regression +// tested offline by `hf emrtd test` without a card on the reader. +//----------------------------------------------------------------------------- + +#ifndef EMRTD_PACE_H__ +#define EMRTD_PACE_H__ + +#include "common.h" +#include + +// Longest OID body (the bytes after the 06 header) we know about +#define EMRTD_PACE_OID_MAXLEN 10 +// AES-256 +#define EMRTD_SM_MAX_KEY_LEN 32 +// AES block, and the SSC length for AES secure messaging +#define EMRTD_SM_MAX_BLOCK_LEN 16 +// Uncompressed EC point of the largest curve we support (P-521): 04 || X || Y +#define EMRTD_EC_POINT_MAXLEN (1 + (2 * 66)) +// Largest raw secret fed to the KDF (a P-521 x-coordinate) +#define EMRTD_PACE_SECRET_MAXLEN 66 +// Number of SecurityInfos we keep out of EF_CardAccess +#define EMRTD_PACE_MAX_INFOS 16 + +typedef enum { + EMRTD_PACE_KA_DH = 0, + EMRTD_PACE_KA_ECDH, +} emrtd_pace_ka_t; + +typedef enum { + EMRTD_PACE_MAP_GM = 0, // Generic Mapping + EMRTD_PACE_MAP_IM, // Integrated Mapping + EMRTD_PACE_MAP_CAM, // Chip Authentication Mapping +} emrtd_pace_map_t; + +typedef enum { + EMRTD_PACE_CIPHER_3DES = 0, + EMRTD_PACE_CIPHER_AES128, + EMRTD_PACE_CIPHER_AES192, + EMRTD_PACE_CIPHER_AES256, +} emrtd_pace_cipher_t; + +typedef struct emrtd_pacealg_s { + const char *name; + emrtd_pace_ka_t ka; + emrtd_pace_map_t mapping; + emrtd_pace_cipher_t cipher; + size_t keylen; // 16 / 24 / 32 + size_t oidlen; + const uint8_t oid[EMRTD_PACE_OID_MAXLEN]; +} emrtd_pacealg_t; + +// Standardized Domain Parameters, TR-03110 part 3, table A.2 +typedef struct emrtd_pacesdp_s { + uint8_t id; + const char *name; + size_t size; + bool is_ec; + // MBEDTLS_ECP_DP_NONE when the curve is not compiled into our mbedtls + mbedtls_ecp_group_id curve; +} emrtd_pacesdp_t; + +// One parsed SecurityInfo out of EF_CardAccess +typedef struct { + const emrtd_pacealg_t *alg; // NULL when the OID is unknown to us + uint8_t oid[EMRTD_PACE_OID_MAXLEN]; + size_t oidlen; + uint32_t version; + bool has_param; + uint8_t param_id; + const emrtd_pacesdp_t *sdp; // NULL when param_id is unknown/absent + bool supported; + const char *reason; // why not supported, NULL when it is +} emrtd_paceinfo_t; + +typedef struct { + emrtd_paceinfo_t infos[EMRTD_PACE_MAX_INFOS]; + size_t count; + int best; // index into infos[], -1 when none usable +} emrtd_cardaccess_t; + +typedef enum { + EMRTD_SM_NONE = 0, + EMRTD_SM_3DES, + EMRTD_SM_AES, +} emrtd_sm_t; + +// State captured during a PACE run with Chip Authentication Mapping, verified +// once the LDS applet is readable and EF_DG14 can be fetched. +typedef struct { + bool negotiated; // PACE-CAM was the chosen protocol + mbedtls_ecp_group_id curve; + uint8_t enc_data[EMRTD_EC_POINT_MAXLEN]; // DO'8A' as returned by the chip + size_t enc_datalen; + // our own mapping private key. PACE-CAM reuses it as the terminal side of + // an ECDH with the chip's static Chip Authentication key, which is what + // makes the chip prove itself without any extra round trip. + uint8_t sk_map_ifd[EMRTD_PACE_SECRET_MAXLEN]; + size_t sk_map_ifdlen; + uint8_t sk_dh_ifd[EMRTD_PACE_SECRET_MAXLEN]; // the step 3 key, over G' + size_t sk_dh_ifdlen; + uint8_t pk_map_ic[EMRTD_EC_POINT_MAXLEN]; // the chip's step 2 mapping key + size_t pk_map_iclen; + uint8_t pk_dh_ic[EMRTD_EC_POINT_MAXLEN]; // the chip's step 3 agreement key + size_t pk_dh_iclen; +} emrtd_cam_t; + +typedef struct { + emrtd_sm_t type; + uint8_t ks_enc[EMRTD_SM_MAX_KEY_LEN]; + uint8_t ks_mac[EMRTD_SM_MAX_KEY_LEN]; + size_t keylen; + uint8_t ssc[EMRTD_SM_MAX_BLOCK_LEN]; + size_t ssclen; // 8 for 3DES, 16 for AES + bool pace; // session was established with PACE + const char *pace_alg; // algorithm name, for reporting + const char *pace_curve; // domain parameter name, for reporting + emrtd_cam_t cam; +} emrtd_session_t; + +//----------------------------------------------------------------------------- +// Shared 3DES / ISO 9797-1 helpers (also used by the BAC path) +//----------------------------------------------------------------------------- +void emrtd_des3_encrypt_cbc(uint8_t *iv, const uint8_t *key, const uint8_t *input, size_t inputlen, uint8_t *output); +void emrtd_des3_decrypt_cbc(uint8_t *iv, const uint8_t *key, const uint8_t *input, size_t inputlen, uint8_t *output); + +// ISO 9797-1 padding method 2 +size_t emrtd_pad_block(const uint8_t *input, size_t inputlen, size_t blocksize, uint8_t *output); + +// ISO 9797-1 MAC algorithm 3 with padding method 2 ("retail MAC") +int emrtd_retail_mac(const uint8_t *key, const uint8_t *input, size_t inputlen, uint8_t *output); + +//----------------------------------------------------------------------------- +// Table lookups +//----------------------------------------------------------------------------- +const emrtd_pacealg_t *emrtd_pace_alg_by_oid(const uint8_t *oid, size_t oidlen); +const emrtd_pacesdp_t *emrtd_pace_sdp_by_id(uint8_t id); +const char *emrtd_pace_cipher_name(emrtd_pace_cipher_t cipher); + +//----------------------------------------------------------------------------- +// Secure messaging session +//----------------------------------------------------------------------------- +void emrtd_sm_clear(emrtd_session_t *ssn); +int emrtd_sm_setup(emrtd_session_t *ssn, emrtd_pace_cipher_t cipher, const uint8_t *ks_enc, const uint8_t *ks_mac); +size_t emrtd_sm_blocksize(const emrtd_session_t *ssn); +void emrtd_sm_bump_ssc(emrtd_session_t *ssn); +int emrtd_sm_mac(const emrtd_session_t *ssn, const uint8_t *input, size_t inputlen, uint8_t *mac); +int emrtd_sm_encrypt(const emrtd_session_t *ssn, const uint8_t *input, size_t inputlen, uint8_t *output); +int emrtd_sm_decrypt(const emrtd_session_t *ssn, const uint8_t *input, size_t inputlen, uint8_t *output); + +//----------------------------------------------------------------------------- +// BER-TLV +//----------------------------------------------------------------------------- +// Reads one TLV starting at *cur. On success *cur is advanced past it. +bool emrtd_tlv_next(const uint8_t **cur, const uint8_t *end, uint32_t *tag, const uint8_t **value, size_t *valuelen); +// Writes tag (1 or 2 bytes, big endian) + length, returns bytes written, 0 on overflow +size_t emrtd_tlv_write_header(uint8_t *out, size_t outlen, uint32_t tag, size_t len); + +//----------------------------------------------------------------------------- +// EF_CardAccess +//----------------------------------------------------------------------------- +int emrtd_pace_parse_cardaccess(const uint8_t *data, size_t datalen, emrtd_cardaccess_t *out); +// Higher is better, 0 means unusable. Used to order the algorithms we try. +int emrtd_pace_rank(const emrtd_paceinfo_t *info); + +//----------------------------------------------------------------------------- +// PACE key derivation +//----------------------------------------------------------------------------- +// MRZ check digit, ICAO 9303-3 4.9. Returns the digit as a value 0-9, not ASCII. +char emrtd_calculate_check_digit(const char *data); + +// The MRZ information string that BAC and PACE both hash: docnr||cd||dob||cd||exp||cd +int emrtd_pace_kmrz(const char *documentnumber, const char *dob, const char *expiry, char *out, size_t outlen); +// K for the MRZ password: SHA-1 of the above +int emrtd_pace_password_mrz(const char *documentnumber, const char *dob, const char *expiry, uint8_t *k, size_t *klen); +// K for the CAN password: the CAN as raw ASCII +int emrtd_pace_password_can(const char *can, uint8_t *k, size_t *klen); +// TR-03110 part 3, A.2.3 +int emrtd_pace_kdf(emrtd_pace_cipher_t cipher, const uint8_t *k, size_t klen, uint32_t counter, uint8_t *out, size_t *outlen); + +// s = D(Kpi, z), zero IV +int emrtd_pace_decrypt_nonce(emrtd_pace_cipher_t cipher, const uint8_t *kpi, const uint8_t *z, size_t zlen, uint8_t *s); + +//----------------------------------------------------------------------------- +// ECDH with Generic Mapping +//----------------------------------------------------------------------------- +size_t emrtd_pace_ec_pointlen(mbedtls_ecp_group_id curve); + +// Public key for a caller supplied private scalar over a caller supplied base point. +// base may be NULL to use the nominal generator of the curve. +int emrtd_pace_ec_pubkey(mbedtls_ecp_group_id curve, const uint8_t *base, size_t baselen, + const uint8_t *priv, size_t privlen, uint8_t *pub, size_t *publen); + +// Fresh ephemeral keypair over base (NULL == nominal generator) +int emrtd_pace_ec_keygen(mbedtls_ecp_group_id curve, const uint8_t *base, size_t baselen, + uint8_t *priv, size_t *privlen, uint8_t *pub, size_t *publen); + +// G' = s*G + (priv * pk_ic) +int emrtd_pace_ec_gm(mbedtls_ecp_group_id curve, const uint8_t *s, size_t slen, + const uint8_t *priv, size_t privlen, const uint8_t *pk_ic, size_t pk_ic_len, + uint8_t *mapped, size_t *mappedlen); + +// x-coordinate of priv * pk_ic +int emrtd_pace_ec_shared_x(mbedtls_ecp_group_id curve, const uint8_t *priv, size_t privlen, + const uint8_t *pk_ic, size_t pk_ic_len, uint8_t *out, size_t *outlen); + +// T = MAC(ks_mac, 7F49 || 06 || 86 ) truncated to 8 bytes +int emrtd_pace_token(const emrtd_pacealg_t *alg, const uint8_t *ks_mac, + const uint8_t *pubkey, size_t pubkeylen, uint8_t *token); + +//----------------------------------------------------------------------------- +// Chip Authentication Mapping +//----------------------------------------------------------------------------- +// Pulls the index'th EC ChipAuthenticationPublicKey out of a SET of +// SecurityInfos, i.e. out of the body of EF_DG14 or the eContent of +// EF_CardSecurity. A document may publish more than one. +int emrtd_pace_find_ca_pubkey(const uint8_t *data, size_t datalen, size_t index, uint8_t *pub, size_t *publen); + +// Prints everything a failed CAM check depends on, so it can be reported +void emrtd_pace_cam_dump(const emrtd_session_t *ssn, const uint8_t *pk_icc, size_t pk_icc_len); + +// Recovers the Chip Authentication Data out of the DO'8A' the chip returns and +// checks it against the ECDH the terminal can do for itself. Returns +// PM3_SUCCESS when the document has proven it holds the CA private key. +int emrtd_pace_cam_verify(const emrtd_session_t *ssn, const uint8_t *pk_icc, size_t pk_icc_len, + const char **mode); + +#endif /* emrtd_pace.h */ diff --git a/client/src/emrtd/emrtd_pacetest.c b/client/src/emrtd/emrtd_pacetest.c new file mode 100644 index 000000000..463a790b9 --- /dev/null +++ b/client/src/emrtd/emrtd_pacetest.c @@ -0,0 +1,682 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Offline regression tests for the eMRTD PACE / secure messaging primitives +// +// Unless noted otherwise every vector below is the worked example from +// ICAO Doc 9303 Part 11 (7th edition) Appendix G, "PACE-ECDH-GM-AES-CMAC-128 +// with BrainpoolP256r1", which is the same example as BSI TR-SAC 1.01 +// Appendix D.3. The BAC / 3DES secure messaging vectors are from +// ICAO Doc 9303 Part 11 Appendix D.4. +//----------------------------------------------------------------------------- + +#include "emrtd_pacetest.h" + +#include +#include + +#include "emrtd/emrtd_pace.h" +#include "crypto/libpcrypto.h" +#include "ui.h" +#include "util.h" + +static bool hexeq(const uint8_t *data, size_t datalen, const char *expected) { + char buf[512] = { 0x00 }; + + if ((datalen * 2) + 1 > sizeof(buf)) { + return false; + } + + for (size_t i = 0; i < datalen; i++) { + snprintf(buf + (i * 2), 3, "%02X", data[i]); + } + + return (strlen(expected) == (datalen * 2)) && (strcmp(buf, expected) == 0); +} + +static size_t unhex(const char *in, uint8_t *out, size_t outlen) { + size_t len = strlen(in) / 2; + if (len > outlen) { + return 0; + } + for (size_t i = 0; i < len; i++) { + unsigned int v = 0; + if (sscanf(in + (i * 2), "%2x", &v) != 1) { + return 0; + } + out[i] = (uint8_t)v; + } + return len; +} + +// ICAO 9303-11 Appendix G, the MRZ of the sample document +#define ICAO_DOCNR "T22000129" +#define ICAO_DOB "640812" +#define ICAO_EXPIRY "101031" +#define ICAO_KMRZ "T22000129364081251010318" +#define ICAO_K "7E2D2A41C74EA0B38CD36F863939BFA8E9032AAD" + +static bool test_mrz_password(void) { + char kmrz[25] = { 0x00 }; + bool res = (emrtd_pace_kmrz(ICAO_DOCNR, ICAO_DOB, ICAO_EXPIRY, kmrz, sizeof(kmrz)) == PM3_SUCCESS); + res = res && (strcmp(kmrz, ICAO_KMRZ) == 0); + + uint8_t k[64] = { 0x00 }; + size_t klen = 0; + res = res && (emrtd_pace_password_mrz(ICAO_DOCNR, ICAO_DOB, ICAO_EXPIRY, k, &klen) == PM3_SUCCESS); + res = res && (klen == 20) && hexeq(k, klen, ICAO_K); + + // Kpi = KDF(K, 3) + uint8_t kpi[32] = { 0x00 }; + size_t kpilen = 0; + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, k, klen, 3, kpi, &kpilen) == PM3_SUCCESS); + res = res && (kpilen == 16) && hexeq(kpi, kpilen, "89DED1B26624EC1E634C1989302849DD"); + + PrintAndLogEx(SUCCESS, "MRZ password..... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_can_password(void) { + uint8_t k[64] = { 0x00 }; + size_t klen = 0; + + // ICAO 9303-11 9.7.2, the CAN is used as its plain ASCII representation + bool res = (emrtd_pace_password_can("123456", k, &klen) == PM3_SUCCESS); + res = res && (klen == 6) && hexeq(k, klen, "313233343536"); + + uint8_t kpi[32] = { 0x00 }; + size_t kpilen = 0; + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, k, klen, 3, kpi, &kpilen) == PM3_SUCCESS); + // SHA-1("123456" || 00000003), first 16 bytes + res = res && (kpilen == 16) && hexeq(kpi, kpilen, "591468CDA83D65219CCCB8560233600F"); + + PrintAndLogEx(SUCCESS, "CAN password..... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_kdf(void) { + uint8_t k[20] = { 0x00 }; + unhex(ICAO_K, k, sizeof(k)); + + uint8_t out[32] = { 0x00 }; + size_t outlen = 0; + bool res = true; + + // SHA-1 based, 16 byte keys + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, k, sizeof(k), 1, out, &outlen) == PM3_SUCCESS); + res = res && (outlen == 16) && hexeq(out, outlen, "3CC5F8872F8B1471B47EEFDDFFC43F46"); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, k, sizeof(k), 2, out, &outlen) == PM3_SUCCESS); + res = res && hexeq(out, outlen, "BD651C6B2FA9B4704553332007771E84"); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, k, sizeof(k), 3, out, &outlen) == PM3_SUCCESS); + res = res && hexeq(out, outlen, "89DED1B26624EC1E634C1989302849DD"); + + // Same hash, but 3DES adds odd parity to both halves (ICAO 9303-11 9.7.1.1) + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_3DES, k, sizeof(k), 3, out, &outlen) == PM3_SUCCESS); + res = res && (outlen == 16) && hexeq(out, outlen, "89DFD0B36725EC1F624C1989312949DC"); + + // SHA-256 based, truncated to 24 bytes + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES192, k, sizeof(k), 1, out, &outlen) == PM3_SUCCESS); + res = res && (outlen == 24) && hexeq(out, outlen, "11504483F04A10A66A8FCD6D348C75A961809C54EDAA2117"); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES192, k, sizeof(k), 2, out, &outlen) == PM3_SUCCESS); + res = res && hexeq(out, outlen, "1F35D576CE54BA775A391F9749E388C48215B7D544D62D96"); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES192, k, sizeof(k), 3, out, &outlen) == PM3_SUCCESS); + res = res && hexeq(out, outlen, "D79A23C126202AC9051FEBFBC0E8A03B1C6645D85752B4B7"); + + // SHA-256 based, full 32 bytes + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES256, k, sizeof(k), 1, out, &outlen) == PM3_SUCCESS); + res = res && (outlen == 32) && hexeq(out, outlen, "11504483F04A10A66A8FCD6D348C75A961809C54EDAA21174726A97FB37DEF52"); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES256, k, sizeof(k), 2, out, &outlen) == PM3_SUCCESS); + res = res && hexeq(out, outlen, "1F35D576CE54BA775A391F9749E388C48215B7D544D62D96470ABA7B19F051A3"); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES256, k, sizeof(k), 3, out, &outlen) == PM3_SUCCESS); + res = res && hexeq(out, outlen, "D79A23C126202AC9051FEBFBC0E8A03B1C6645D85752B4B71408FA229AB6D56B"); + + PrintAndLogEx(SUCCESS, "KDF.............. ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_nonce(void) { + uint8_t kpi[16] = { 0x00 }; + uint8_t z[16] = { 0x00 }; + uint8_t s[16] = { 0x00 }; + + unhex("89DED1B26624EC1E634C1989302849DD", kpi, sizeof(kpi)); + unhex("95A3A016522EE98D01E76CB6B98B42C3", z, sizeof(z)); + + bool res = (emrtd_pace_decrypt_nonce(EMRTD_PACE_CIPHER_AES128, kpi, z, sizeof(z), s) == PM3_SUCCESS); + res = res && hexeq(s, sizeof(s), "3F00C4D39D153F2B2A214A078D899B22"); + + PrintAndLogEx(SUCCESS, "Nonce decrypt.... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +// ICAO 9303-11 Appendix G, PACE-ECDH-GM-AES-CMAC-128 over BrainpoolP256r1 +#define ICAO_S "3F00C4D39D153F2B2A214A078D899B22" +#define ICAO_SK_MAP_IFD "7F4EF07B9EA82FD78AD689B38D0BC78CF21F249D953BC46F4C6E19259C010F99" +#define ICAO_PK_MAP_IFD "047ACF3EFC982EC45565A4B155129EFBC74650DCBFA6362D896FC70262E0C2CC5E544552DCB6725218799115B55C9BAA6D9F6BC3A9618E70C25AF71777A9C4922D" +#define ICAO_PK_MAP_IC "04824FBA91C9CBE26BEF53A0EBE7342A3BF178CEA9F45DE0B70AA601651FBA3F5730D8C879AAA9C9F73991E61B58F4D52EB87A0A0C709A49DC63719363CCD13C54" +#define ICAO_G_MAPPED "048CED63C91426D4F0EB1435E7CB1D74A46723A0AF21C89634F65A9AE87A9265E28C879506743F8611AC33645C5B985C80B5F09A0B83407C1B6A4D857AE76FE522" +#define ICAO_SK_DH_IFD "A73FB703AC1436A18E0CFA5ABB3F7BEC7A070E7A6788486BEE230C4A22762595" +#define ICAO_PK_DH_IFD "042DB7A64C0355044EC9DF190514C625CBA2CEA48754887122F3A5EF0D5EDD301C3556F3B3B186DF10B857B58F6A7EB80F20BA5DC7BE1D43D9BF850149FBB36462" +#define ICAO_PK_DH_IC "049E880F842905B8B3181F7AF7CAA9F0EFB743847F44A306D2D28C1D9EC65DF6DB7764B22277A2EDDC3C265A9F018F9CB852E111B768B326904B59A0193776F094" +#define ICAO_SHARED_X "28768D20701247DAE81804C9E780EDE582A9996DB4A315020B2733197DB84925" +#define ICAO_KSENC "F5F0E35C0D7161EE6724EE513A0D9A7F" +#define ICAO_KSMAC "FE251C7858B356B24514B3BD5F4297D1" + +static bool test_gm(void) { + uint8_t s[16], x1[32], pk_map_ic[65], x2[32], pk_dh_ic[65]; + uint8_t pub[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + uint8_t mapped[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + uint8_t shared[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + size_t publen = 0, mappedlen = 0, sharedlen = 0; + + unhex(ICAO_S, s, sizeof(s)); + unhex(ICAO_SK_MAP_IFD, x1, sizeof(x1)); + unhex(ICAO_PK_MAP_IC, pk_map_ic, sizeof(pk_map_ic)); + unhex(ICAO_SK_DH_IFD, x2, sizeof(x2)); + unhex(ICAO_PK_DH_IC, pk_dh_ic, sizeof(pk_dh_ic)); + + const mbedtls_ecp_group_id curve = MBEDTLS_ECP_DP_BP256R1; + + bool res = (emrtd_pace_ec_pointlen(curve) == 65); + + // PK.Map.IFD = x1 * G + res = res && (emrtd_pace_ec_pubkey(curve, NULL, 0, x1, sizeof(x1), pub, &publen) == PM3_SUCCESS); + res = res && hexeq(pub, publen, ICAO_PK_MAP_IFD); + + // G' = s*G + x1 * PK.Map.IC + res = res && (emrtd_pace_ec_gm(curve, s, sizeof(s), x1, sizeof(x1), pk_map_ic, sizeof(pk_map_ic), + mapped, &mappedlen) == PM3_SUCCESS); + res = res && hexeq(mapped, mappedlen, ICAO_G_MAPPED); + + // PK.DH.IFD = x2 * G' + res = res && (emrtd_pace_ec_pubkey(curve, mapped, mappedlen, x2, sizeof(x2), pub, &publen) == PM3_SUCCESS); + res = res && hexeq(pub, publen, ICAO_PK_DH_IFD); + + // K = x-coordinate of x2 * PK.DH.IC + res = res && (emrtd_pace_ec_shared_x(curve, x2, sizeof(x2), pk_dh_ic, sizeof(pk_dh_ic), + shared, &sharedlen) == PM3_SUCCESS); + res = res && hexeq(shared, sharedlen, ICAO_SHARED_X); + + // KSenc = KDF(K, 1), KSmac = KDF(K, 2) + uint8_t ks[32] = { 0x00 }; + size_t kslen = 0; + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, shared, sharedlen, 1, ks, &kslen) == PM3_SUCCESS); + res = res && hexeq(ks, kslen, ICAO_KSENC); + res = res && (emrtd_pace_kdf(EMRTD_PACE_CIPHER_AES128, shared, sharedlen, 2, ks, &kslen) == PM3_SUCCESS); + res = res && hexeq(ks, kslen, ICAO_KSMAC); + + PrintAndLogEx(SUCCESS, "ECDH GM mapping.. ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_ec_keygen(void) { + // Not a published vector, just a sanity check that the ephemeral key we + // generate is a real key on the mapped generator and is not all zeroes. + uint8_t mapped[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t mappedlen = unhex(ICAO_G_MAPPED, mapped, sizeof(mapped)); + + uint8_t priv[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + uint8_t pub[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + uint8_t check[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t privlen = 0, publen = 0, checklen = 0; + + bool res = (emrtd_pace_ec_keygen(MBEDTLS_ECP_DP_BP256R1, mapped, mappedlen, + priv, &privlen, pub, &publen) == PM3_SUCCESS); + res = res && (privlen == 32) && (publen == 65) && (pub[0] == 0x04); + + uint8_t zeroes[EMRTD_PACE_SECRET_MAXLEN] = { 0x00 }; + res = res && (memcmp(priv, zeroes, privlen) != 0); + + // the generated public key has to be priv * G' + res = res && (emrtd_pace_ec_pubkey(MBEDTLS_ECP_DP_BP256R1, mapped, mappedlen, + priv, privlen, check, &checklen) == PM3_SUCCESS); + res = res && (checklen == publen) && (memcmp(check, pub, publen) == 0); + + PrintAndLogEx(SUCCESS, "Ephemeral keygen. ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_token(void) { + uint8_t ks_mac[16] = { 0x00 }; + uint8_t pk_dh_ic[65] = { 0x00 }; + uint8_t pk_dh_ifd[65] = { 0x00 }; + uint8_t token[8] = { 0x00 }; + + unhex(ICAO_KSMAC, ks_mac, sizeof(ks_mac)); + unhex(ICAO_PK_DH_IC, pk_dh_ic, sizeof(pk_dh_ic)); + unhex(ICAO_PK_DH_IFD, pk_dh_ifd, sizeof(pk_dh_ifd)); + + const uint8_t oid[10] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02, 0x02}; + const emrtd_pacealg_t *alg = emrtd_pace_alg_by_oid(oid, sizeof(oid)); + + bool res = (alg != NULL); + res = res && (alg->cipher == EMRTD_PACE_CIPHER_AES128); + res = res && (alg->mapping == EMRTD_PACE_MAP_GM); + res = res && (alg->ka == EMRTD_PACE_KA_ECDH); + + // T_IFD is computed over the chip's key + res = res && (emrtd_pace_token(alg, ks_mac, pk_dh_ic, sizeof(pk_dh_ic), token) == PM3_SUCCESS); + res = res && hexeq(token, sizeof(token), "C2B0BD78D94BA866"); + + // T_IC is computed over our key + res = res && (emrtd_pace_token(alg, ks_mac, pk_dh_ifd, sizeof(pk_dh_ifd), token) == PM3_SUCCESS); + res = res && hexeq(token, sizeof(token), "3ABB9674BCE93C08"); + + PrintAndLogEx(SUCCESS, "Auth tokens...... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_ssc(void) { + emrtd_session_t ssn; + uint8_t ks[32] = { 0x00 }; + + emrtd_sm_clear(&ssn); + bool res = (emrtd_sm_setup(&ssn, EMRTD_PACE_CIPHER_AES128, ks, ks) == PM3_SUCCESS); + res = res && (ssn.ssclen == 16) && (emrtd_sm_blocksize(&ssn) == 16); + + emrtd_sm_bump_ssc(&ssn); + res = res && hexeq(ssn.ssc, ssn.ssclen, "00000000000000000000000000000001"); + + // carry across the whole SSC + memset(ssn.ssc, 0xFF, ssn.ssclen); + ssn.ssc[ssn.ssclen - 1] = 0xFF; + emrtd_sm_bump_ssc(&ssn); + res = res && hexeq(ssn.ssc, ssn.ssclen, "00000000000000000000000000000000"); + + memset(ssn.ssc, 0x00, ssn.ssclen); + ssn.ssc[ssn.ssclen - 1] = 0xFF; + emrtd_sm_bump_ssc(&ssn); + res = res && hexeq(ssn.ssc, ssn.ssclen, "00000000000000000000000000000100"); + + // 3DES sessions carry an 8 byte SSC + emrtd_sm_clear(&ssn); + res = res && (emrtd_sm_setup(&ssn, EMRTD_PACE_CIPHER_3DES, ks, ks) == PM3_SUCCESS); + res = res && (ssn.ssclen == 8) && (emrtd_sm_blocksize(&ssn) == 8); + unhex("887022120C06C2FF", ssn.ssc, sizeof(ssn.ssc)); + emrtd_sm_bump_ssc(&ssn); + res = res && hexeq(ssn.ssc, ssn.ssclen, "887022120C06C300"); + + PrintAndLogEx(SUCCESS, "SSC increment.... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_padding(void) { + uint8_t out[32] = { 0x00 }; + + bool res = (emrtd_pad_block((const uint8_t *)"\x01\x1E", 2, 8, out) == 8); + res = res && hexeq(out, 8, "011E800000000000"); + + res = res && (emrtd_pad_block((const uint8_t *)"\x01\x1E", 2, 16, out) == 16); + res = res && hexeq(out, 16, "011E8000000000000000000000000000"); + + // a full block always gets a whole block of padding added + res = res && (emrtd_pad_block((const uint8_t *)"\x0C\xA4\x02\x0C", 4, 8, out) == 8); + res = res && hexeq(out, 8, "0CA4020C80000000"); + + uint8_t full[8] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}; + res = res && (emrtd_pad_block(full, 8, 8, out) == 16); + res = res && hexeq(out, 16, "11223344556677888000000000000000"); + + PrintAndLogEx(SUCCESS, "ISO 9797-1 pad... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +// ICAO 9303-11 Appendix D.4, the BAC secure messaging worked example. +// This is the regression test for the 3DES path, it has to keep passing +// byte for byte after any refactor of the session handling. +static bool test_sm_3des(void) { + emrtd_session_t ssn; + uint8_t ks_enc[16], ks_mac[16]; + + unhex("979EC13B1CBFE9DCD01AB0FED307EAE5", ks_enc, sizeof(ks_enc)); + unhex("F1CB1F1FB5ADF208806B89DC579DC1F8", ks_mac, sizeof(ks_mac)); + + emrtd_sm_clear(&ssn); + bool res = (emrtd_sm_setup(&ssn, EMRTD_PACE_CIPHER_3DES, ks_enc, ks_mac) == PM3_SUCCESS); + unhex("887022120C06C226", ssn.ssc, sizeof(ssn.ssc)); + + // SELECT EF.COM, protected + emrtd_sm_bump_ssc(&ssn); + res = res && hexeq(ssn.ssc, ssn.ssclen, "887022120C06C227"); + + uint8_t pt[16] = { 0x00 }; + uint8_t ct[16] = { 0x00 }; + size_t ptlen = emrtd_pad_block((const uint8_t *)"\x01\x1E", 2, 8, pt); + res = res && (emrtd_sm_encrypt(&ssn, pt, ptlen, ct) == PM3_SUCCESS); + res = res && hexeq(ct, ptlen, "6375432908C044F6"); + + uint8_t n[64] = { 0x00 }; + size_t nlen = 0; + memcpy(n, ssn.ssc, ssn.ssclen); + nlen += ssn.ssclen; + nlen += emrtd_pad_block((const uint8_t *)"\x0C\xA4\x02\x0C", 4, 8, n + nlen); + memcpy(n + nlen, "\x87\x09\x01", 3); + nlen += 3; + memcpy(n + nlen, ct, ptlen); + nlen += ptlen; + + uint8_t cc[8] = { 0x00 }; + res = res && (emrtd_sm_mac(&ssn, n, nlen, cc) == PM3_SUCCESS); + res = res && hexeq(cc, sizeof(cc), "BF8B92D635FF24F8"); + + // Response 99 02 90 00 8E 08 FA855A5D4C50A8ED + emrtd_sm_bump_ssc(&ssn); + res = res && hexeq(ssn.ssc, ssn.ssclen, "887022120C06C228"); + + nlen = 0; + memcpy(n, ssn.ssc, ssn.ssclen); + nlen += ssn.ssclen; + memcpy(n + nlen, "\x99\x02\x90\x00", 4); + nlen += 4; + res = res && (emrtd_sm_mac(&ssn, n, nlen, cc) == PM3_SUCCESS); + res = res && hexeq(cc, sizeof(cc), "FA855A5D4C50A8ED"); + + PrintAndLogEx(SUCCESS, "3DES SM.......... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +// AES secure messaging, ICAO 9303-11 9.8.6. +// The session keys are the ones the PACE example above produces. ICAO publishes +// no AES secure messaging trace, so the protected APDUs below were computed +// independently (OpenSSL / PyCryptodome) from those keys. The one judgement +// call they encode is that step e.2, "concatenate SSC and M and add padding", +// applies to AES as well as to 3DES; that was confirmed on a document doing +// PACE with AES-CMAC-256, which answers 6988 to an unpadded MAC input. +static bool test_sm_aes(void) { + emrtd_session_t ssn; + uint8_t ks_enc[16], ks_mac[16]; + + unhex(ICAO_KSENC, ks_enc, sizeof(ks_enc)); + unhex(ICAO_KSMAC, ks_mac, sizeof(ks_mac)); + + emrtd_sm_clear(&ssn); + bool res = (emrtd_sm_setup(&ssn, EMRTD_PACE_CIPHER_AES128, ks_enc, ks_mac) == PM3_SUCCESS); + // SSC starts at zero after PACE + res = res && hexeq(ssn.ssc, ssn.ssclen, "00000000000000000000000000000000"); + + //--------------------------------------------------------------------- + // SELECT EF.COM -> 0CA4020C1D 871101 8E08 00 + //--------------------------------------------------------------------- + emrtd_sm_bump_ssc(&ssn); + + uint8_t pt[32] = { 0x00 }; + uint8_t ct[32] = { 0x00 }; + size_t ptlen = emrtd_pad_block((const uint8_t *)"\x01\x1E", 2, 16, pt); + res = res && (emrtd_sm_encrypt(&ssn, pt, ptlen, ct) == PM3_SUCCESS); + res = res && hexeq(ct, ptlen, "EE0E4724F4465C1BE9C2F73ABDD73A3D"); + + uint8_t n[128] = { 0x00 }; + size_t nlen = 0; + memcpy(n, ssn.ssc, ssn.ssclen); + nlen += ssn.ssclen; + nlen += emrtd_pad_block((const uint8_t *)"\x0C\xA4\x02\x0C", 4, 16, n + nlen); + memcpy(n + nlen, "\x87\x11\x01", 3); + nlen += 3; + memcpy(n + nlen, ct, ptlen); + nlen += ptlen; + + uint8_t cc[8] = { 0x00 }; + res = res && (emrtd_sm_mac(&ssn, n, nlen, cc) == PM3_SUCCESS); + res = res && hexeq(cc, sizeof(cc), "835D1B54575C955F"); + + // response 99 02 90 00 8E 08 + emrtd_sm_bump_ssc(&ssn); + nlen = 0; + memcpy(n, ssn.ssc, ssn.ssclen); + nlen += ssn.ssclen; + memcpy(n + nlen, "\x99\x02\x90\x00", 4); + nlen += 4; + res = res && (emrtd_sm_mac(&ssn, n, nlen, cc) == PM3_SUCCESS); + res = res && hexeq(cc, sizeof(cc), "BEA7B381C494A079"); + + //--------------------------------------------------------------------- + // READ BINARY offset 0, 4 bytes -> 0CB000000D 970104 8E08 00 + //--------------------------------------------------------------------- + emrtd_sm_bump_ssc(&ssn); + nlen = 0; + memcpy(n, ssn.ssc, ssn.ssclen); + nlen += ssn.ssclen; + nlen += emrtd_pad_block((const uint8_t *)"\x0C\xB0\x00\x00", 4, 16, n + nlen); + memcpy(n + nlen, "\x97\x01\x04", 3); + nlen += 3; + res = res && (emrtd_sm_mac(&ssn, n, nlen, cc) == PM3_SUCCESS); + res = res && hexeq(cc, sizeof(cc), "AA6BA54F44DF8364"); + + // response 87 11 01 99 02 90 00 8E 08 + emrtd_sm_bump_ssc(&ssn); + + uint8_t rct[16] = { 0x00 }; + unhex("645C0B1F998A088278D07942BBE94B60", rct, sizeof(rct)); + + nlen = 0; + memcpy(n, ssn.ssc, ssn.ssclen); + nlen += ssn.ssclen; + memcpy(n + nlen, "\x87\x11\x01", 3); + nlen += 3; + memcpy(n + nlen, rct, sizeof(rct)); + nlen += sizeof(rct); + memcpy(n + nlen, "\x99\x02\x90\x00", 4); + nlen += 4; + res = res && (emrtd_sm_mac(&ssn, n, nlen, cc) == PM3_SUCCESS); + res = res && hexeq(cc, sizeof(cc), "94A33C6AA2D8CCC8"); + + // and the response data has to decrypt back to the start of EF_COM + uint8_t plain[16] = { 0x00 }; + res = res && (emrtd_sm_decrypt(&ssn, rct, sizeof(rct), plain) == PM3_SUCCESS); + res = res && hexeq(plain, sizeof(plain), "60145F01800000000000000000000000"); + res = res && hexeq(plain, 4, "60145F01"); + + PrintAndLogEx(SUCCESS, "AES SM........... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_cardaccess(void) { + // A SET of four PACEInfos: + // ECDH-GM-AES-CMAC-128 / BrainpoolP256r1 (supported) + // ECDH-GM-AES-CMAC-256 / BrainpoolP384r1 (supported) + // DH-GM-AES-CMAC-128 / 1024-bit MODP (not supported, no DHM) + // ECDH-CAM-AES-CMAC-256 / BrainpoolP384r1 (supported, but ranked below + // GM while its proof cannot + // be checked) + const char *blob = + "3150" + "3012" "060A04007F0007020204020202010202010D" + "3012" "060A04007F00070202040204020102020110" + "3012" "060A04007F00070202040101020102020100" + "3012" "060A04007F00070202040604020102020110"; + + uint8_t data[128] = { 0x00 }; + size_t datalen = unhex(blob, data, sizeof(data)); + + emrtd_cardaccess_t ca; + bool res = (datalen > 0); + res = res && (emrtd_pace_parse_cardaccess(data, datalen, &ca) == PM3_SUCCESS); + res = res && (ca.count == 4); + // GM wins ties over CAM for now, see emrtd_pace_rank() + res = res && (ca.best == 1); + res = res && (ca.infos[3].supported); + res = res && (ca.infos[3].alg != NULL) && (ca.infos[3].alg->mapping == EMRTD_PACE_MAP_CAM); + res = res && (emrtd_pace_rank(&ca.infos[3]) < emrtd_pace_rank(&ca.infos[1])); + // but CAM still has to be usable when it is all a document offers + res = res && (emrtd_pace_rank(&ca.infos[3]) > 0); + + res = res && (ca.infos[0].supported) && (ca.infos[0].version == 2); + res = res && (ca.infos[0].alg != NULL) && (ca.infos[0].alg->cipher == EMRTD_PACE_CIPHER_AES128); + res = res && (ca.infos[0].sdp != NULL) && (ca.infos[0].sdp->curve == MBEDTLS_ECP_DP_BP256R1); + + res = res && (ca.infos[1].supported); + res = res && (ca.infos[1].alg != NULL) && (ca.infos[1].alg->cipher == EMRTD_PACE_CIPHER_AES256); + res = res && (ca.infos[1].sdp != NULL) && (ca.infos[1].sdp->curve == MBEDTLS_ECP_DP_BP384R1); + + res = res && (ca.infos[2].supported == false) && (ca.infos[2].reason != NULL); + + // curves that this tree's mbedtls does not carry must never resolve + const emrtd_pacesdp_t *sdp = emrtd_pace_sdp_by_id(14); // BrainpoolP320r1 + res = res && (sdp != NULL) && (sdp->curve == MBEDTLS_ECP_DP_NONE); + sdp = emrtd_pace_sdp_by_id(9); // BrainpoolP192r1 + res = res && (sdp != NULL) && (sdp->curve == MBEDTLS_ECP_DP_NONE); + sdp = emrtd_pace_sdp_by_id(12); // NIST P-256 + res = res && (sdp != NULL) && (sdp->curve == MBEDTLS_ECP_DP_SECP256R1); + + // truncated input must be rejected, not walked off the end of the buffer + emrtd_cardaccess_t bad; + for (size_t cut = 1; cut < datalen; cut++) { + if (emrtd_pace_parse_cardaccess(data, cut, &bad) == PM3_SUCCESS) { + // a shorter but still well formed prefix is only possible if it + // parses to fewer entries than the full blob + if (bad.count >= ca.count) { + res = false; + break; + } + } + } + + PrintAndLogEx(SUCCESS, "EF_CardAccess.... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +// Chip Authentication Mapping. +// +// The chip sends t = SK.Map.IC * SK.CA.IC^-1 mod n encrypted with KSenc, so +// that t * PK.CA.IC reproduces the ephemeral PACE key it used. Only a chip +// holding the static Chip Authentication private key can produce such a t. +// See US 9215230 (Kuegler / Bender) and TR-03110 part 3. +// +// No published vector exists, so this one is constructed the way a genuine +// chip would: t is derived from a chosen static key and mapping key, padded +// and encrypted. t is 32 bytes here and DO'8A' is 48, mirroring a real +// BrainpoolP384r1 document where a 48 byte t arrives as 64 bytes. +#define CAM_PK_ICC "048DF71464547FC82DCF1650BBC5B72DCD2CC3D9A71283F6E374C0958F316026DB0E1F619B0FBBD54B130E9D04B5201A0522D4CC199888B6D76C9A22BDD79F2D45" +#define CAM_PK_MAP_IC "041D840F08CE75DDA65326277A850039892B9A399614221865EDC0DCD27DE1B4EEA5E8B3CB9560F08D09DDB3B4DE4D936FF1311A9F6D20047E94B3E458BCA5778B" +#define CAM_KSENC "0102030405060708090A0B0C0D0E0F10" +#define CAM_DO8A "25887095A78FA691E074800EF9B097F96EBFA89ED8350BCAEDFD309DE91878ADCE249F1253D13483C441B1A08DFD74DE" + +static bool test_cam(void) { + uint8_t pk_icc[65], ks[16]; + + size_t pk_icclen = unhex(CAM_PK_ICC, pk_icc, sizeof(pk_icc)); + unhex(CAM_KSENC, ks, sizeof(ks)); + + emrtd_session_t ssn; + emrtd_sm_clear(&ssn); + bool res = (emrtd_sm_setup(&ssn, EMRTD_PACE_CIPHER_AES128, ks, ks) == PM3_SUCCESS); + + ssn.cam.negotiated = true; + ssn.cam.curve = MBEDTLS_ECP_DP_BP256R1; + ssn.cam.pk_map_iclen = unhex(CAM_PK_MAP_IC, ssn.cam.pk_map_ic, sizeof(ssn.cam.pk_map_ic)); + ssn.cam.enc_datalen = unhex(CAM_DO8A, ssn.cam.enc_data, sizeof(ssn.cam.enc_data)); + res = res && (ssn.cam.enc_datalen == 48); + + const char *mode = NULL; + res = res && (emrtd_pace_cam_verify(&ssn, pk_icc, pk_icclen, &mode) == PM3_SUCCESS); + res = res && (mode != NULL) && (strstr(mode, "PK.Map.IC") != NULL); + + // a chip that returns the wrong blob must not verify under any encoding + ssn.cam.enc_data[0] ^= 0x01; + res = res && (emrtd_pace_cam_verify(&ssn, pk_icc, pk_icclen, &mode) != PM3_SUCCESS); + ssn.cam.enc_data[0] ^= 0x01; + + // nor may a different, perfectly valid, chip authentication key pass + uint8_t other[65] = { 0x00 }; + size_t otherlen = unhex(CAM_PK_MAP_IC, other, sizeof(other)); + res = res && (emrtd_pace_cam_verify(&ssn, other, otherlen, &mode) != PM3_SUCCESS); + + // and the chip's own public key has to come out of EF_DG14 + const char *dg14 = + "6E5E315C305A060904007F000702020102304D300706052B8104002203420004" + "8DF71464547FC82DCF1650BBC5B72DCD2CC3D9A71283F6E374C0958F316026DB" + "0E1F619B0FBBD54B130E9D04B5201A0522D4CC199888B6D76C9A22BDD79F2D45"; + + uint8_t dg14bin[128] = { 0x00 }; + size_t dg14len = unhex(dg14, dg14bin, sizeof(dg14bin)); + + uint8_t found[EMRTD_EC_POINT_MAXLEN] = { 0x00 }; + size_t foundlen = 0; + res = res && (emrtd_pace_find_ca_pubkey(dg14bin, dg14len, 0, found, &foundlen) == PM3_SUCCESS); + res = res && (foundlen == pk_icclen) && hexeq(found, foundlen, CAM_PK_ICC); + + // truncated EF_DG14 must be refused, not walked off the end + for (size_t cut = 1; cut < dg14len; cut++) { + if (emrtd_pace_find_ca_pubkey(dg14bin, cut, 0, found, &foundlen) == PM3_SUCCESS) { + res = false; + break; + } + } + + PrintAndLogEx(SUCCESS, "CA mapping....... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +static bool test_tlv(void) { + const uint8_t data[] = {0x7F, 0x49, 0x04, 0x06, 0x02, 0xAA, 0xBB}; + const uint8_t *cur = data; + const uint8_t *end = data + sizeof(data); + uint32_t tag = 0; + const uint8_t *val = NULL; + size_t vlen = 0; + + bool res = emrtd_tlv_next(&cur, end, &tag, &val, &vlen); + res = res && (tag == 0x7F49) && (vlen == 4); + + const uint8_t *icur = val; + const uint8_t *iend = val + vlen; + res = res && emrtd_tlv_next(&icur, iend, &tag, &val, &vlen); + res = res && (tag == 0x06) && (vlen == 2) && (val[0] == 0xAA) && (val[1] == 0xBB); + res = res && (emrtd_tlv_next(&icur, iend, &tag, &val, &vlen) == false); + + // a length that runs past the buffer must be rejected + const uint8_t bad[] = {0x30, 0x10, 0x01}; + cur = bad; + res = res && (emrtd_tlv_next(&cur, bad + sizeof(bad), &tag, &val, &vlen) == false); + + uint8_t out[8] = { 0x00 }; + res = res && (emrtd_tlv_write_header(out, sizeof(out), 0x7F49, 0x4F) == 3); + res = res && hexeq(out, 3, "7F494F"); + res = res && (emrtd_tlv_write_header(out, sizeof(out), 0x86, 0x41) == 2); + res = res && hexeq(out, 2, "8641"); + res = res && (emrtd_tlv_write_header(out, sizeof(out), 0x87, 0x81) == 3); + res = res && hexeq(out, 3, "878181"); + res = res && (emrtd_tlv_write_header(out, 1, 0x87, 0x81) == 0); + + PrintAndLogEx(SUCCESS, "BER-TLV.......... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + +bool emrtd_test(bool verbose) { + (void)verbose; + bool res = true; + + PrintAndLogEx(INFO, "------ " _CYAN_("eMRTD PACE tests") " ------"); + + res = test_padding() && res; + res = test_tlv() && res; + res = test_mrz_password() && res; + res = test_can_password() && res; + res = test_kdf() && res; + res = test_nonce() && res; + res = test_cardaccess() && res; + res = test_gm() && res; + res = test_ec_keygen() && res; + res = test_token() && res; + res = test_cam() && res; + res = test_ssc() && res; + res = test_sm_3des() && res; + res = test_sm_aes() && res; + + PrintAndLogEx(INFO, "---------------------------"); + PrintAndLogEx(SUCCESS, "Tests ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(NORMAL, ""); + return res; +} diff --git a/client/src/emrtd/emrtd_pacetest.h b/client/src/emrtd/emrtd_pacetest.h new file mode 100644 index 000000000..1e7eb00be --- /dev/null +++ b/client/src/emrtd/emrtd_pacetest.h @@ -0,0 +1,26 @@ +//----------------------------------------------------------------------------- +// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// See LICENSE.txt for the text of the license. +//----------------------------------------------------------------------------- +// Offline regression tests for the eMRTD PACE / secure messaging primitives +//----------------------------------------------------------------------------- + +#ifndef EMRTD_PACETEST_H__ +#define EMRTD_PACETEST_H__ + +#include "common.h" + +bool emrtd_test(bool verbose); + +#endif /* emrtd_pacetest.h */ diff --git a/client/src/nfc/ndef.c b/client/src/nfc/ndef.c index 1fab72018..357effcfb 100644 --- a/client/src/nfc/ndef.c +++ b/client/src/nfc/ndef.c @@ -998,6 +998,17 @@ static int ndefDecodeExternal_record(NDEFHeader_t *ndef) { return PM3_SUCCESS; } + // Android Application Record + if ((ndef->TypeLen == strlen(NDEF_ANDROID_AAR)) && + (strncmp((char *)ndef->Type, NDEF_ANDROID_AAR, ndef->TypeLen) == 0)) { + PrintAndLogEx(INFO + , " Android app... " _GREEN_("%.*s") + , (int)ndef->PayloadLen + , ndef->Payload + ); + return PM3_SUCCESS; + } + PrintAndLogEx(INFO , " URN... " _GREEN_("urn:nfc:ext:%.*s") , (int)ndef->TypeLen @@ -1393,3 +1404,257 @@ int NDEFGetTotalLength(uint8_t *ndef, size_t ndeflen, size_t *outlen) { *outlen = idx; return PM3_SUCCESS; } + +//----------------------------------------------------------------------------- +// NDEF encoding +//----------------------------------------------------------------------------- + +// Find the longest matching abbreviation from URI_s[]. +// Returns the prefix code and sets prefixLen to how many bytes of uri it covers. +// Code 0x00 means "no abbreviation", the whole string gets stored verbatim. +static uint8_t ndefEncodeURIPrefix(const char *uri, size_t *prefixLen) { + + uint8_t code = 0; + size_t best = 0; + + for (uint8_t i = 1; i < ARRAYLEN(URI_s); i++) { + size_t n = strlen(URI_s[i]); + if ((n > best) && (strncmp(uri, URI_s[i], n) == 0)) { + best = n; + code = i; + } + } + + *prefixLen = best; + return code; +} + +int NDEFEncodePayloadURI(const char *uri, uint8_t *buf, size_t bufLen, size_t *outLen) { + + if ((uri == NULL) || (buf == NULL) || (outLen == NULL)) { + return PM3_EINVARG; + } + + size_t uri_len = strlen(uri); + if (uri_len == 0) { + return PM3_EINVARG; + } + + size_t prefix_len = 0; + uint8_t code = ndefEncodeURIPrefix(uri, &prefix_len); + + size_t n = 1 + (uri_len - prefix_len); + if (n > bufLen) { + return PM3_EOVFLOW; + } + + buf[0] = code; + memcpy(buf + 1, uri + prefix_len, uri_len - prefix_len); + + *outLen = n; + return PM3_SUCCESS; +} + +int NDEFEncodePayloadText(const char *text, const char *lang, uint8_t *buf, size_t bufLen, size_t *outLen) { + + if ((text == NULL) || (buf == NULL) || (outLen == NULL)) { + return PM3_EINVARG; + } + + if ((lang == NULL) || (strlen(lang) == 0)) { + lang = "en"; + } + + size_t lang_len = strlen(lang); + size_t text_len = strlen(text); + + // the status byte carries the language code length in its lower 6 bits + if (lang_len > 0x3F) { + return PM3_EINVARG; + } + + size_t n = 1 + lang_len + text_len; + if (n > bufLen) { + return PM3_EOVFLOW; + } + + // bit 7 clear == UTF-8 + buf[0] = (uint8_t)(lang_len & 0x3F); + memcpy(buf + 1, lang, lang_len); + memcpy(buf + 1 + lang_len, text, text_len); + + *outLen = n; + return PM3_SUCCESS; +} + +int NDEFEncodePayloadAAR(const char *pkg, uint8_t *buf, size_t bufLen, size_t *outLen) { + + if ((pkg == NULL) || (buf == NULL) || (outLen == NULL)) { + return PM3_EINVARG; + } + + size_t n = strlen(pkg); + if (n == 0) { + return PM3_EINVARG; + } + + if (n > bufLen) { + return PM3_EOVFLOW; + } + + memcpy(buf, pkg, n); + + *outLen = n; + return PM3_SUCCESS; +} + +int NDEFEncodeRecord(const NDEFRecordDesc_t *rec, bool mb, bool me, uint8_t *buf, size_t bufLen, size_t *outLen) { + + if ((rec == NULL) || (buf == NULL) || (outLen == NULL)) { + return PM3_EINVARG; + } + + if ((rec->typeLen > 255) || (rec->idLen > 255)) { + return PM3_EINVARG; + } + +#if SIZE_MAX > 0xFFFFFFFF + // the long form payload length field is only four bytes wide, a larger payload + // cannot be expressed. unreachable where size_t is no wider than the field. + if (rec->payloadLen > 0xFFFFFFFF) { + return PM3_EINVARG; + } +#endif + + if ((rec->typeLen && (rec->type == NULL)) || + (rec->idLen && (rec->id == NULL)) || + (rec->payloadLen && (rec->payload == NULL))) { + return PM3_EINVARG; + } + + bool sr = (rec->payloadLen < 256); + bool il = (rec->idLen > 0); + + size_t head = 1 + 1 + (sr ? 1 : 4) + (il ? 1 : 0) + rec->typeLen + rec->idLen; + + // keep the total from wrapping before it reaches the bufLen check below + if (rec->payloadLen > SIZE_MAX - head) { + return PM3_EINVARG; + } + + size_t n = head + rec->payloadLen; + if (n > bufLen) { + return PM3_EOVFLOW; + } + + size_t idx = 0; + + // MB | ME | CF | SR | IL | TNF. chunked records are never emitted + buf[idx] = (uint8_t)(rec->tnf & 0x07); + if (mb) { + buf[idx] |= 0x80; + } + if (me) { + buf[idx] |= 0x40; + } + if (sr) { + buf[idx] |= 0x10; + } + if (il) { + buf[idx] |= 0x08; + } + idx++; + + buf[idx++] = (uint8_t)rec->typeLen; + + if (sr) { + buf[idx++] = (uint8_t)rec->payloadLen; + } else { + buf[idx++] = (uint8_t)(rec->payloadLen >> 24); + buf[idx++] = (uint8_t)(rec->payloadLen >> 16); + buf[idx++] = (uint8_t)(rec->payloadLen >> 8); + buf[idx++] = (uint8_t)(rec->payloadLen); + } + + if (il) { + buf[idx++] = (uint8_t)rec->idLen; + } + + if (rec->typeLen) { + memcpy(buf + idx, rec->type, rec->typeLen); + idx += rec->typeLen; + } + + if (rec->idLen) { + memcpy(buf + idx, rec->id, rec->idLen); + idx += rec->idLen; + } + + if (rec->payloadLen) { + memcpy(buf + idx, rec->payload, rec->payloadLen); + idx += rec->payloadLen; + } + + *outLen = idx; + return PM3_SUCCESS; +} + +int NDEFEncodeMessage(const NDEFRecordDesc_t *recs, size_t count, uint8_t *buf, size_t bufLen, size_t *outLen) { + + if ((recs == NULL) || (buf == NULL) || (outLen == NULL) || (count == 0)) { + return PM3_EINVARG; + } + + size_t idx = 0; + for (size_t i = 0; i < count; i++) { + + size_t n = 0; + int res = NDEFEncodeRecord(&recs[i], (i == 0), (i == (count - 1)), buf + idx, bufLen - idx, &n); + if (res != PM3_SUCCESS) { + return res; + } + idx += n; + } + + *outLen = idx; + return PM3_SUCCESS; +} + +int NDEFEncodeTLV(const uint8_t *msg, size_t msgLen, uint8_t *buf, size_t bufLen, size_t *outLen) { + + if ((msg == NULL) || (buf == NULL) || (outLen == NULL) || (msgLen == 0)) { + return PM3_EINVARG; + } + + // 0xFFFF is reserved, and the terminator has to fit as well + if (msgLen > 0xFFFE) { + return PM3_EINVARG; + } + + // one byte length form up to 254, three byte form above that + size_t hdr = (msgLen < 0xFF) ? 2 : 4; + + size_t n = hdr + msgLen + 1; + if (n > bufLen) { + return PM3_EOVFLOW; + } + + size_t idx = 0; + buf[idx++] = 0x03; + + if (msgLen < 0xFF) { + buf[idx++] = (uint8_t)msgLen; + } else { + buf[idx++] = 0xFF; + buf[idx++] = (uint8_t)(msgLen >> 8); + buf[idx++] = (uint8_t)(msgLen); + } + + memcpy(buf + idx, msg, msgLen); + idx += msgLen; + + buf[idx++] = 0xFE; + + *outLen = idx; + return PM3_SUCCESS; +} diff --git a/client/src/nfc/ndef.h b/client/src/nfc/ndef.h index 31967c61a..ddc78dc9f 100644 --- a/client/src/nfc/ndef.h +++ b/client/src/nfc/ndef.h @@ -77,4 +77,35 @@ typedef struct { int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose); int NDEFRecordsDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen, bool verbose); int NDEFGetTotalLength(uint8_t *ndef, size_t ndeflen, size_t *outlen); + +// NFC Forum well known types +#define NDEF_TYPE_URI "U" +#define NDEF_TYPE_TEXT "T" + +// Android Application Record, TNF external +#define NDEF_ANDROID_AAR "android.com:pkg" + +// Describes one record to be encoded. +// Field order intentionally matches gst_ndef_record_t in cmdhfgst.c so the two +// can eventually be folded together. +typedef struct { + TypeNameFormat_t tnf; + const uint8_t *type; + size_t typeLen; + const uint8_t *id; + size_t idLen; + const uint8_t *payload; + size_t payloadLen; +} NDEFRecordDesc_t; + +// payload builders +int NDEFEncodePayloadURI(const char *uri, uint8_t *buf, size_t bufLen, size_t *outLen); +int NDEFEncodePayloadText(const char *text, const char *lang, uint8_t *buf, size_t bufLen, size_t *outLen); +int NDEFEncodePayloadAAR(const char *pkg, uint8_t *buf, size_t bufLen, size_t *outLen); + +// record / message / TLV assembly +int NDEFEncodeRecord(const NDEFRecordDesc_t *rec, bool mb, bool me, uint8_t *buf, size_t bufLen, size_t *outLen); +int NDEFEncodeMessage(const NDEFRecordDesc_t *recs, size_t count, uint8_t *buf, size_t bufLen, size_t *outLen); +int NDEFEncodeTLV(const uint8_t *msg, size_t msgLen, uint8_t *buf, size_t bufLen, size_t *outLen); + #endif // _NDEF_H_ diff --git a/client/src/pm3line_vocabulary.h b/client/src/pm3line_vocabulary.h index cdec39eed..e474d0070 100644 --- a/client/src/pm3line_vocabulary.h +++ b/client/src/pm3line_vocabulary.h @@ -255,6 +255,7 @@ const static vocabulary_t vocabulary[] = { { 0, "hf emrtd dump" }, { 1, "hf emrtd info" }, { 1, "hf emrtd list" }, + { 1, "hf emrtd test" }, { 1, "hf felica help" }, { 1, "hf felica list" }, { 0, "hf felica info" }, diff --git a/client/src/proxguiqt.cpp b/client/src/proxguiqt.cpp index df810aef9..11cadfdca 100644 --- a/client/src/proxguiqt.cpp +++ b/client/src/proxguiqt.cpp @@ -270,6 +270,40 @@ const PictureItem *PictureWidget::pictureAt(int i) const { return &m_images.at(i); } +ScaledPictureLabel::ScaledPictureLabel(const QImage &img, QWidget *parent) + : QLabel(parent), m_image(img) { + + setAlignment(Qt::AlignCenter); + setMinimumSize(1, 1); + // let the layout hand us whatever is going, we adapt to it + setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + rescale(); +} + +QSize ScaledPictureLabel::sizeHint(void) const { + return m_image.size(); +} + +void ScaledPictureLabel::resizeEvent(QResizeEvent *event) { + QLabel::resizeEvent(event); + rescale(); +} + +void ScaledPictureLabel::rescale(void) { + + if (m_image.isNull()) + return; + + QSize room = size(); + if (room.width() < 1 || room.height() < 1) + return; + + // Qt::KeepAspectRatio fits the image inside the box without distorting it. + // Scaling up is wanted here, a 240x320 portrait in a 400x400 window should + // fill the window rather than sit in the middle of it. + setPixmap(QPixmap::fromImage(m_image.scaled(room, Qt::KeepAspectRatio, Qt::SmoothTransformation))); +} + // Append one image to the array and give it its own tab void PictureWidget::addPicture(const QString &title, const QImage &img) { @@ -281,17 +315,8 @@ void PictureWidget::addPicture(const QString &title, const QImage &img) { QWidget *page = new QWidget(); QVBoxLayout *layout = new QVBoxLayout(page); - QLabel *lbl_pm = new QLabel(); - lbl_pm->setPixmap(QPixmap::fromImage(img)); - lbl_pm->setScaledContents(false); - lbl_pm->setAlignment(Qt::AlignCenter); - - // large images (fingerprints, high res portraits) shouldn't blow up the window - QScrollArea *scroll = new QScrollArea(page); - scroll->setWidget(lbl_pm); - scroll->setWidgetResizable(true); - scroll->setAlignment(Qt::AlignCenter); - layout->addWidget(scroll); + ScaledPictureLabel *lbl_pm = new ScaledPictureLabel(img, page); + layout->addWidget(lbl_pm, 1); QLabel *lbl_sz = new QLabel(page); lbl_sz->setText(QString("w: %1 h: %2") diff --git a/client/src/proxguiqt.h b/client/src/proxguiqt.h index 6da86e1ca..060ed9a73 100644 --- a/client/src/proxguiqt.h +++ b/client/src/proxguiqt.h @@ -27,6 +27,7 @@ #include #include #include +#include #include #include "proxgui.h" @@ -101,6 +102,27 @@ class PictureItem { QImage image; }; +/** + * @brief A label that keeps its image scaled to whatever room it is given + * + * Portraits in EF_DG2 are small (often 240x320) and signatures in EF_DG7 are + * wide and short. Painting either one at native size in a fixed window leaves + * it stranded in a corner, so the pixmap is rebuilt from the original image on + * every resize, fitted to the widget and keeping the aspect ratio. + */ +class ScaledPictureLabel : public QLabel { + public: + explicit ScaledPictureLabel(const QImage &img, QWidget *parent = nullptr); + QSize sizeHint(void) const override; + + protected: + void resizeEvent(QResizeEvent *event) override; + + private: + void rescale(void); + QImage m_image; +}; + // Picture viewer window. Holds an array of images, one tab per image, so that // several pictures of the same document (portrait, signature, other biometrics) // can be shown side by side diff --git a/common_arm/sys/sys_hw_at32.c b/common_arm/sys/sys_hw_at32.c index d09bbfed7..316913395 100644 --- a/common_arm/sys/sys_hw_at32.c +++ b/common_arm/sys/sys_hw_at32.c @@ -68,7 +68,8 @@ static void at32_bpr_write_dt1(uint32_t data) { // Select and enable an ERTC clock so the write-protection register is // writable at the full APB frequency. - crm_ertc_clock_select(CRM_ERTC_CLOCK_HEXT_DIV_20); + CRM->cfg_bit.ertcdiv = ((CRM_ERTC_CLOCK_HEXT_DIV_20 & 0x1F0) >> 4); + CRM->bpdc_bit.ertcsel = (CRM_ERTC_CLOCK_HEXT_DIV_20 & 0xF); CRM->bpdc_bit.ertcen = TRUE; ERTC->wp = SYS_SIMPLE_RESET_BPR_UNLOCK_KEY1; diff --git a/doc/commands.json b/doc/commands.json index 5c1cf6a2a..adf033844 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -2851,11 +2851,14 @@ }, "hf emrtd help": { "command": "hf emrtd help", - "description": "help This help info Tag information list List ISO 14443A/7816 history --------------------------------------------------------------------------------------- hf emrtd dump available offline: no Dump all files on an eMRTD", + "description": "help This help info Tag information list List ISO 14443A/7816 history test Regression tests --------------------------------------------------------------------------------------- hf emrtd dump available offline: no Dump all files on an eMRTD", "notes": [ "hf emrtd dump", "hf emrtd dump --dir ../dump", - "hf emrtd dump -n 123456789 -d 890101 -e 250401" + "hf emrtd dump -n 123456789 -d 890101 -e 250401", + "hf emrtd dump --can 123456 -> PACE with the Card Access Number", + "hf emrtd dump --can 123456 --pace -> PACE only, no BAC fallback", + "hf emrtd dump -n 123456789 -d 890101 -e 250401 --bac -> force BAC" ], "offline": true, "options": [ @@ -2864,9 +2867,12 @@ "-d, --date date of birth in YYMMDD format", "-e, --expiry expiry in YYMMDD format", "-m, --mrz <[0-9A-Z<]> 2nd line of MRZ, 44 chars", + "--can Card Access Number, PACE password instead of the MRZ", + "--pace force PACE, fail instead of falling back to BAC", + "--bac force BAC, skip PACE", "--dir save dump to the given dirpath" ], - "usage": "hf emrtd dump [-h] [-n ] [-d ] [-e ] [-m <[0-9A-Z<]>] [--dir ]" + "usage": "hf emrtd dump [-h] [-n ] [-d ] [-e ] [-m <[0-9A-Z<]>] [--can ] [--pace] [--bac] [--dir ]" }, "hf emrtd info": { "command": "hf emrtd info", @@ -2875,7 +2881,9 @@ "hf emrtd info", "hf emrtd info --dir ../dumps", "hf emrtd info -n 123456789 -d 890101 -e 250401", - "hf emrtd info -n 123456789 -d 890101 -e 250401 -i" + "hf emrtd info -n 123456789 -d 890101 -e 250401 -i", + "hf emrtd info --can 123456 -> PACE with the Card Access Number", + "hf emrtd info --can 123456 --pace -> PACE only, no BAC fallback" ], "offline": true, "options": [ @@ -2884,10 +2892,13 @@ "-d, --date date of birth in YYMMDD format", "-e, --expiry expiry in YYMMDD format", "-m, --mrz <[0-9A-Z<]> 2nd line of MRZ, 44 chars (passports only)", + "--can Card Access Number, PACE password instead of the MRZ", + "--pace force PACE, fail instead of falling back to BAC", + "--bac force BAC, skip PACE", "--dir display info from offline dump stored in dirpath", "-i, --images show images" ], - "usage": "hf emrtd info [-hi] [-n ] [-d ] [-e ] [-m <[0-9A-Z<]>] [--dir ]" + "usage": "hf emrtd info [-hi] [-n ] [-d ] [-e ] [-m <[0-9A-Z<]>] [--can ] [--pace] [--bac] [--dir ]" }, "hf emrtd list": { "command": "hf emrtd list", @@ -2910,6 +2921,18 @@ ], "usage": "hf emrtd list [-h1crux] [--frame] [-f ]" }, + "hf emrtd test": { + "command": "hf emrtd test", + "description": "Regression tests for the PACE and secure messaging primitives", + "notes": [ + "hf emrtd test" + ], + "offline": true, + "options": [ + "-h, --help This help" + ], + "usage": "hf emrtd test [-h]" + }, "hf epa help": { "command": "hf epa help", "description": "help This help --------------------------------------------------------------------------------------- hf epa cnonces available offline: no Tries to collect nonces when doing part of PACE protocol.", @@ -16116,8 +16139,14 @@ } }, "metadata": { +<<<<<<< HEAD "commands_extracted": 901, "extracted_by": "PM3Help2JSON v1.00", "extracted_on": "2026-08-22T14:19:35+00:00" +======= + "commands_extracted": 902, + "extracted_by": "PM3Help2JSON v1.00", + "extracted_on": "2026-08-21T18:43:14+00:00" +>>>>>>> b4c4edd7c94a989108cacaaaf73805a28a6c217c } } diff --git a/doc/commands.md b/doc/commands.md index 612340856..6b42e6bcc 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -354,6 +354,7 @@ Check column "offline" for their availability. |`hf emrtd dump `|N |`Dump eMRTD files to binary files` |`hf emrtd info `|Y |`Tag information` |`hf emrtd list `|Y |`List ISO 14443A/7816 history` +|`hf emrtd test `|Y |`Regression tests` ### hf felica