textual
[RRG-proxmark3.git] / client / src / cmdsmartcard.c
blobfcd52abf824860c6e00bb5019c2d09de9745ee73
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2018 iceman
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // Proxmark3 RDV40 Smartcard module commands
9 //-----------------------------------------------------------------------------
10 #include "cmdsmartcard.h"
11 #include <ctype.h>
12 #include <string.h>
13 #include "cmdparser.h" // command_t
14 #include "commonutil.h" // ARRAYLEN
15 #include "protocols.h"
16 #include "cmdtrace.h"
17 #include "proxmark3.h"
18 #include "comms.h" // getfromdevice
19 #include "emv/emvcore.h" // decodeTVL
20 #include "crypto/libpcrypto.h" // sha512hash
21 #include "ui.h"
22 #include "util.h"
23 #include "fileutils.h"
24 #include "crc16.h" // crc
25 #include "cliparser.h" // cliparsing
27 static int CmdHelp(const char *Cmd);
29 static int smart_loadjson(const char *preferredName, json_t **root) {
31 json_error_t error;
33 if (preferredName == NULL) return 1;
35 char *path;
36 int res = searchFile(&path, RESOURCES_SUBDIR, preferredName, ".json", false);
37 if (res != PM3_SUCCESS) {
38 return PM3_EFILE;
41 int retval = PM3_SUCCESS;
42 *root = json_load_file(path, 0, &error);
43 if (!*root) {
44 PrintAndLogEx(ERR, "json (%s) error on line %d: %s", path, error.line, error.text);
45 retval = PM3_ESOFT;
46 goto out;
49 if (!json_is_array(*root)) {
50 PrintAndLogEx(ERR, "Invalid json (%s) format. root must be an array.", path);
51 retval = PM3_ESOFT;
52 goto out;
55 PrintAndLogEx(SUCCESS, "Loaded file (%s) OK.", path);
56 out:
57 free(path);
58 return retval;
61 static uint8_t GetATRTA1(uint8_t *atr, size_t atrlen) {
62 if (atrlen > 2) {
63 uint8_t T0 = atr[1];
64 if (T0 & 0x10)
65 return atr[2];
68 return 0x11; // default value is 0x11, corresponding to fmax=5 MHz, Fi=372, Di=1.
71 int DiArray[] = {
72 0, // b0000 RFU
73 1, // b0001
77 16,
78 32, // b0110
79 64, // b0111. This was RFU in ISO/IEC 7816-3:1997 and former. Some card readers or drivers may erroneously reject cards using this value
80 12,
81 20,
82 0, // b1010 RFU
84 0, // ...
87 0 // b1111 RFU
90 int FiArray[] = {
91 372, // b0000 Historical note: in ISO/IEC 7816-3:1989, this was assigned to cards with internal clock
92 372, // b0001
93 558, // b0010
94 744, // b0011
95 1116, // b0100
96 1488, // b0101
97 1860, // b0110
98 0, // b0111 RFU
99 0, // b1000 RFU
100 512, // b1001
101 768, // b1010
102 1024, // b1011
103 1536, // b1100
104 2048, // b1101
105 0, // b1110 RFU
106 0 // b1111 RFU
109 float FArray[] = {
110 4, // b0000 Historical note: in ISO/IEC 7816-3:1989, this was assigned to cards with internal clock
111 5, // b0001
112 6, // b0010
113 8, // b0011
114 12, // b0100
115 16, // b0101
116 20, // b0110
117 0, // b0111 RFU
118 0, // b1000 RFU
119 5, // b1001
120 7.5, // b1010
121 10, // b1011
122 15, // b1100
123 20, // b1101
124 0, // b1110 RFU
125 0 // b1111 RFU
128 static int GetATRDi(uint8_t *atr, size_t atrlen) {
129 uint8_t TA1 = GetATRTA1(atr, atrlen);
130 return DiArray[TA1 & 0x0F]; // The 4 low-order bits of TA1 (4th MSbit to 1st LSbit) encode Di
133 static int GetATRFi(uint8_t *atr, size_t atrlen) {
134 uint8_t TA1 = GetATRTA1(atr, atrlen);
135 return FiArray[TA1 >> 4]; // The 4 high-order bits of TA1 (8th MSbit to 5th LSbit) encode fmax and Fi
138 static float GetATRF(uint8_t *atr, size_t atrlen) {
139 uint8_t TA1 = GetATRTA1(atr, atrlen);
140 return FArray[TA1 >> 4]; // The 4 high-order bits of TA1 (8th MSbit to 5th LSbit) encode fmax and Fi
143 static void PrintATR(uint8_t *atr, size_t atrlen) {
145 uint8_t T0 = atr[1];
146 uint8_t K = T0 & 0x0F;
147 uint8_t T1len = 0, TD1len = 0, TDilen = 0;
148 bool protocol_T0_present = true;
149 bool protocol_T15_present = false;
151 if (T0 & 0x10) {
152 PrintAndLogEx(INFO, "\t- TA1 (Maximum clock frequency, proposed bit duration) [ 0x%02x ]", atr[2 + T1len]);
153 T1len++;
156 if (T0 & 0x20) {
157 PrintAndLogEx(INFO, "\t- TB1 (Deprecated: VPP requirements) [ 0x%02x ]", atr[2 + T1len]);
158 T1len++;
161 if (T0 & 0x40) {
162 PrintAndLogEx(INFO, "\t- TC1 (Extra delay between bytes required by card) [ 0x%02x ]", atr[2 + T1len]);
163 T1len++;
166 if (T0 & 0x80) {
167 uint8_t TD1 = atr[2 + T1len];
168 PrintAndLogEx(INFO, "\t- TD1 (First offered transmission protocol, presence of TA2..TD2) [ 0x%02x ] Protocol T%d", TD1, TD1 & 0x0f);
169 protocol_T0_present = false;
170 if ((TD1 & 0x0f) == 0) {
171 protocol_T0_present = true;
173 if ((TD1 & 0x0f) == 15) {
174 protocol_T15_present = true;
177 T1len++;
179 if (TD1 & 0x10) {
180 PrintAndLogEx(INFO, "\t- TA2 (Specific protocol and parameters to be used after the ATR) [ 0x%02x ]", atr[2 + T1len + TD1len]);
181 TD1len++;
183 if (TD1 & 0x20) {
184 PrintAndLogEx(INFO, "\t- TB2 (Deprecated: VPP precise voltage requirement) [ 0x%02x ]", atr[2 + T1len + TD1len]);
185 TD1len++;
187 if (TD1 & 0x40) {
188 PrintAndLogEx(INFO, "\t- TC2 (Maximum waiting time for protocol T=0) [ 0x%02x ]", atr[2 + T1len + TD1len]);
189 TD1len++;
191 if (TD1 & 0x80) {
192 uint8_t TDi = atr[2 + T1len + TD1len];
193 PrintAndLogEx(INFO, "\t- TD2 (A supported protocol or more global parameters, presence of TA3..TD3) [ 0x%02x ] Protocol T%d", TDi, TDi & 0x0f);
194 if ((TDi & 0x0f) == 0) {
195 protocol_T0_present = true;
197 if ((TDi & 0x0f) == 15) {
198 protocol_T15_present = true;
200 TD1len++;
202 bool nextCycle = true;
203 uint8_t vi = 3;
204 while (nextCycle) {
205 nextCycle = false;
206 if (TDi & 0x10) {
207 PrintAndLogEx(INFO, "\t- TA%d: 0x%02x", vi, atr[2 + T1len + TD1len + TDilen]);
208 TDilen++;
210 if (TDi & 0x20) {
211 PrintAndLogEx(INFO, "\t- TB%d: 0x%02x", vi, atr[2 + T1len + TD1len + TDilen]);
212 TDilen++;
214 if (TDi & 0x40) {
215 PrintAndLogEx(INFO, "\t- TC%d: 0x%02x", vi, atr[2 + T1len + TD1len + TDilen]);
216 TDilen++;
218 if (TDi & 0x80) {
219 TDi = atr[2 + T1len + TD1len + TDilen];
220 PrintAndLogEx(INFO, "\t- TD%d [ 0x%02x ] Protocol T%d", vi, TDi, TDi & 0x0f);
221 TDilen++;
223 nextCycle = true;
224 vi++;
230 if (!protocol_T0_present || protocol_T15_present) { // there is CRC Check Byte TCK
231 uint8_t vxor = 0;
232 for (int i = 1; i < atrlen; i++)
233 vxor ^= atr[i];
235 if (vxor)
236 PrintAndLogEx(WARNING, "Invalid check sum. Must be 0 got 0x%02X", vxor);
237 else
238 PrintAndLogEx(INFO, "Check sum OK.");
241 if (atr[0] != 0x3b)
242 PrintAndLogEx(WARNING, "Not a direct convention [ 0x%02x ]", atr[0]);
244 uint8_t calen = 2 + T1len + TD1len + TDilen + K;
246 if (atrlen != calen && atrlen != calen + 1) // may be CRC
247 PrintAndLogEx(WARNING, "Invalid ATR length. len: %zu, T1len: %d, TD1len: %d, TDilen: %d, K: %d", atrlen, T1len, TD1len, TDilen, K);
249 if (K > 0)
250 PrintAndLogEx(INFO, "Historical bytes | len %02d | format %02x", K, atr[2 + T1len + TD1len + TDilen]);
252 if (K > 1) {
253 PrintAndLogEx(INFO, "\tHistorical bytes");
254 print_buffer(&atr[2 + T1len + TD1len + TDilen], K, 1);
258 static int smart_wait(uint8_t *out, int maxoutlen, bool verbose) {
259 int i = 4;
260 uint32_t len = 0;
261 do {
262 clearCommandBuffer();
263 PacketResponseNG resp;
264 if (WaitForResponseTimeout(CMD_SMART_RAW, &resp, 1000)) {
266 if (resp.status != PM3_SUCCESS) {
267 if (verbose) PrintAndLogEx(WARNING, "smart card response status failed");
268 return -3;
271 len = resp.length;
272 if (len == 0) {
273 if (verbose) PrintAndLogEx(WARNING, "smart card response failed");
274 return -2;
277 if (len > maxoutlen) {
278 if (verbose) PrintAndLogEx(ERR, "Response too large. Got %u, expected %d", len, maxoutlen);
279 return -4;
282 memcpy(out, resp.data.asBytes, len);
283 if (len >= 2) {
284 if (verbose) {
287 if (out[len - 2] == 0x90 && out[len - 1] == 0x00) {
288 PrintAndLogEx(SUCCESS, _GREEN_("%02X%02X") " | %s", out[len - 2], out[len - 1], GetAPDUCodeDescription(out[len - 2], out[len - 1]));
289 } else {
290 PrintAndLogEx(SUCCESS, "%02X%02X | %s", out[len - 2], out[len - 1], GetAPDUCodeDescription(out[len - 2], out[len - 1]));
293 } else {
294 if (verbose) {
295 PrintAndLogEx(SUCCESS, " %d | %s", len, sprint_hex_inrow_ex(out, len, 8));
298 return len;
300 } while (i--);
302 if (verbose) {
303 PrintAndLogEx(WARNING, "smart card response timeout");
305 return -1;
308 static int smart_responseEx(uint8_t *out, int maxoutlen, bool verbose) {
310 int datalen = smart_wait(out, maxoutlen, verbose);
311 bool needGetData = false;
313 if (datalen < 2) {
314 goto out;
317 if (out[datalen - 2] == 0x61 || out[datalen - 2] == 0x9F) {
318 needGetData = true;
321 if (needGetData) {
322 int len = out[datalen - 1];
324 if (verbose) PrintAndLogEx(INFO, "Requesting " _YELLOW_("0x%02X") " bytes response", len);
326 uint8_t cmd_getresp[] = {0x00, ISO7816_GET_RESPONSE, 0x00, 0x00, len};
327 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
328 payload->flags = SC_RAW | SC_LOG;
329 payload->len = sizeof(cmd_getresp);
330 memcpy(payload->data, cmd_getresp, sizeof(cmd_getresp));
332 clearCommandBuffer();
333 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
334 free(payload);
336 datalen = smart_wait(out, maxoutlen, verbose);
338 if (datalen < 2) {
339 goto out;
342 // data wo ACK
343 if (datalen != len + 2) {
344 // data with ACK
345 if (datalen == len + 2 + 1) { // 2 - response, 1 - ACK
346 if (out[0] != ISO7816_GET_RESPONSE) {
347 if (verbose) {
348 PrintAndLogEx(ERR, "GetResponse ACK error. len 0x%x | data[0] %02X", len, out[0]);
350 datalen = 0;
351 goto out;
354 datalen--;
355 memmove(out, &out[1], datalen);
356 } else {
357 // wrong length
358 if (verbose) {
359 PrintAndLogEx(WARNING, "GetResponse wrong length. Must be 0x%02X got 0x%02X", len, datalen - 3);
365 out:
366 return datalen;
369 static int smart_response(uint8_t *out, int maxoutlen) {
370 return smart_responseEx(out, maxoutlen, true);
373 static int CmdSmartRaw(const char *Cmd) {
374 CLIParserContext *ctx;
375 CLIParserInit(&ctx, "smart raw",
376 "Sends raw bytes to card",
377 "smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR\n"
378 "smart raw -0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory\n"
379 "smart raw -0 -t -d 00a4040007a0000000041010 -> Mastercard\n"
380 "smart raw -0 -t -d 00a4040007a0000000031010 -> Visa"
383 void *argtable[] = {
384 arg_param_begin,
385 arg_lit0("r", NULL, "do not read response"),
386 arg_lit0("a", NULL, "active smartcard without select (reset sc module)"),
387 arg_lit0("s", NULL, "active smartcard with select (get ATR)"),
388 arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
389 arg_lit0("0", NULL, "use protocol T=0"),
390 arg_str1("d", "data", "<hex>", "bytes to send"),
391 arg_param_end
393 CLIExecWithReturn(ctx, Cmd, argtable, true);
395 bool reply = (arg_get_lit(ctx, 1) == false);
396 bool active = arg_get_lit(ctx, 2);
397 bool active_select = arg_get_lit(ctx, 3);
398 bool decode_tlv = arg_get_lit(ctx, 4);
399 bool use_t0 = arg_get_lit(ctx, 5);
401 int dlen = 0;
402 uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
403 int res = CLIParamHexToBuf(arg_get_str(ctx, 6), data, sizeof(data), &dlen);
404 CLIParserFree(ctx);
406 if (res) {
407 PrintAndLogEx(FAILED, "Error parsing bytes");
408 return PM3_EINVARG;
411 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + dlen);
412 if (payload == NULL) {
413 PrintAndLogEx(FAILED, "failed to allocate memory");
414 return PM3_EMALLOC;
416 payload->len = dlen;
417 memcpy(payload->data, data, dlen);
419 payload->flags = SC_LOG;
420 if (active || active_select) {
422 payload->flags |= (SC_CONNECT | SC_CLEARLOG);
423 if (active_select)
424 payload->flags |= SC_SELECT;
427 if (dlen > 0) {
428 if (use_t0)
429 payload->flags |= SC_RAW_T0;
430 else
431 payload->flags |= SC_RAW;
434 uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
435 if (buf == NULL) {
436 PrintAndLogEx(DEBUG, "failed to allocate memory");
437 free(payload);
438 return PM3_EMALLOC;
441 clearCommandBuffer();
442 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + dlen);
444 if (reply == false) {
445 goto out;
448 // reading response from smart card
449 int len = smart_response(buf, PM3_CMD_DATA_SIZE);
450 if (len < 0) {
451 free(payload);
452 free(buf);
453 return PM3_ESOFT;
456 if (buf[0] == 0x6C) {
458 // request more bytes to download
459 data[4] = buf[1];
460 memcpy(payload->data, data, dlen);
461 clearCommandBuffer();
462 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + dlen);
464 len = smart_response(buf, PM3_CMD_DATA_SIZE);
466 data[4] = 0;
469 if (decode_tlv && len > 4)
470 TLVPrintFromBuffer(buf, len - 2);
471 else {
472 if (len > 2) {
473 PrintAndLogEx(INFO, "Response data:");
474 PrintAndLogEx(INFO, " # | bytes | ascii");
475 PrintAndLogEx(INFO, "---+-------------------------------------------------+-----------------");
476 print_hex_break(buf, len, 16);
479 PrintAndLogEx(NORMAL, "");
480 out:
481 free(payload);
482 free(buf);
483 return PM3_SUCCESS;
486 static int CmdSmartUpgrade(const char *Cmd) {
487 PrintAndLogEx(INFO, "-------------------------------------------------------------------");
488 PrintAndLogEx(WARNING, _RED_("WARNING") " - sim module firmware upgrade");
489 PrintAndLogEx(WARNING, _RED_("A dangerous command, do wrong and you could brick the sim module"));
490 PrintAndLogEx(INFO, "-------------------------------------------------------------------");
491 PrintAndLogEx(NORMAL, "");
493 CLIParserContext *ctx;
494 CLIParserInit(&ctx, "smart upgrade",
495 "Upgrade RDV4.0 sim module firmware",
496 "smart upgrade -f sim011.bin"
499 void *argtable[] = {
500 arg_param_begin,
501 arg_str1("f", "file", "<filename>", "firmware file name"),
502 arg_param_end
504 CLIExecWithReturn(ctx, Cmd, argtable, true);
505 int fnlen = 0;
506 char filename[FILE_PATH_SIZE] = {0};
507 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, sizeof(filename), &fnlen);
508 CLIParserFree(ctx);
510 char *bin_extension = filename;
511 char *dot_position = NULL;
512 while ((dot_position = strchr(bin_extension, '.')) != NULL) {
513 bin_extension = dot_position + 1;
516 // generate filename for the related SHA512 hash file
517 char sha512filename[FILE_PATH_SIZE] = {'\0'};
518 if (!strcmp(bin_extension, "BIN") || !strcmp(bin_extension, "bin")) {
519 memcpy(sha512filename, filename, strlen(filename) - strlen("bin"));
520 strcat(sha512filename, "sha512.txt");
521 } else {
522 PrintAndLogEx(FAILED, "Filename extension of firmware upgrade file must be .BIN");
523 return PM3_ESOFT;
526 PrintAndLogEx(INFO, "firmware file " _YELLOW_("%s"), filename);
527 PrintAndLogEx(INFO, "Checking integrity " _YELLOW_("%s"), sha512filename);
529 // load firmware file
530 size_t firmware_size = 0;
531 uint8_t *firmware = NULL;
532 if (loadFile_safe(filename, "", (void **)&firmware, &firmware_size) != PM3_SUCCESS) {
533 PrintAndLogEx(FAILED, "Firmware file " _YELLOW_("%s") " not found or locked.", filename);
534 return PM3_EFILE;
537 // load sha512 file
538 size_t sha512_size = 0;
539 char *hashstring = NULL;
540 if (loadFile_safe(sha512filename, "", (void **)&hashstring, &sha512_size) != PM3_SUCCESS) {
541 PrintAndLogEx(FAILED, "SHA-512 file not found or locked.");
542 free(firmware);
543 return PM3_EFILE;
546 if (sha512_size < 128) {
547 PrintAndLogEx(FAILED, "SHA-512 file wrong size");
548 free(hashstring);
549 free(firmware);
550 return PM3_ESOFT;
552 hashstring[128] = '\0';
554 uint8_t hash_1[64];
555 if (param_gethex(hashstring, 0, hash_1, 128)) {
556 PrintAndLogEx(FAILED, "Couldn't read SHA-512 file");
557 free(hashstring);
558 free(firmware);
559 return PM3_ESOFT;
562 uint8_t hash_2[64];
563 if (sha512hash(firmware, firmware_size, hash_2)) {
564 PrintAndLogEx(FAILED, "Couldn't calculate SHA-512 of firmware");
565 free(hashstring);
566 free(firmware);
567 return PM3_ESOFT;
570 if (memcmp(hash_1, hash_2, 64)) {
571 PrintAndLogEx(FAILED, "Couldn't verify integrity of firmware file " _RED_("(wrong SHA-512 hash)"));
572 free(hashstring);
573 free(firmware);
574 return PM3_ESOFT;
576 free(hashstring);
578 PrintAndLogEx(INFO, _GREEN_("Don\'t turn off your PM3!"));
579 PrintAndLogEx(SUCCESS, "Sim module firmware uploading to PM3...");
581 PacketResponseNG resp;
583 //Send to device
584 uint32_t index = 0;
585 uint32_t bytes_sent = 0;
586 uint32_t bytes_remaining = firmware_size;
588 while (bytes_remaining > 0) {
590 struct {
591 uint32_t idx;
592 uint32_t bytes_in_packet;
593 uint16_t crc;
594 uint8_t data[400];
595 } PACKED upload;
597 uint32_t bytes_in_packet = MIN(sizeof(upload.data), bytes_remaining);
599 upload.idx = index + bytes_sent;
600 upload.bytes_in_packet = bytes_in_packet;
601 memcpy(upload.data, firmware + bytes_sent, bytes_in_packet);
603 uint8_t a = 0, b = 0;
604 compute_crc(CRC_14443_A, upload.data, bytes_in_packet, &a, &b);
605 upload.crc = (a << 8 | b);
607 clearCommandBuffer();
608 SendCommandNG(CMD_SMART_UPLOAD, (uint8_t *)&upload, sizeof(upload));
609 if (!WaitForResponseTimeout(CMD_SMART_UPLOAD, &resp, 2000)) {
610 PrintAndLogEx(WARNING, "timeout while waiting for reply.");
611 free(firmware);
612 return PM3_ETIMEOUT;
615 if (resp.status != PM3_SUCCESS) {
616 PrintAndLogEx(WARNING, "uploading to device failed");
617 free(firmware);
618 return resp.status;
620 bytes_remaining -= bytes_in_packet;
621 bytes_sent += bytes_in_packet;
622 PrintAndLogEx(INPLACE, "%d bytes sent", bytes_sent);
624 PrintAndLogEx(NORMAL, "");
625 PrintAndLogEx(SUCCESS, "Sim module firmware updating...");
627 // trigger the firmware upgrade
628 clearCommandBuffer();
629 struct {
630 uint16_t fw_size;
631 uint16_t crc;
632 } PACKED payload;
633 payload.fw_size = firmware_size;
635 uint8_t a = 0, b = 0;
636 compute_crc(CRC_14443_A, firmware, firmware_size, &a, &b);
637 payload.crc = (a << 8 | b);
639 free(firmware);
640 SendCommandNG(CMD_SMART_UPGRADE, (uint8_t *)&payload, sizeof(payload));
641 if (!WaitForResponseTimeout(CMD_SMART_UPGRADE, &resp, 2500)) {
642 PrintAndLogEx(WARNING, "timeout while waiting for reply.");
643 return PM3_ETIMEOUT;
646 if (resp.status == PM3_SUCCESS) {
647 PrintAndLogEx(SUCCESS, "Sim module firmware upgrade " _GREEN_("successful"));
648 PrintAndLogEx(HINT, "run " _YELLOW_("`hw status`") " to validate the fw version ");
649 } else {
650 PrintAndLogEx(FAILED, "Sim module firmware upgrade " _RED_("failed"));
652 return PM3_SUCCESS;
655 static int CmdSmartInfo(const char *Cmd) {
656 CLIParserContext *ctx;
657 CLIParserInit(&ctx, "smart info",
658 "Extract more detailed information from smart card.",
659 "smart info -v"
662 void *argtable[] = {
663 arg_param_begin,
664 arg_lit0("v", "verbose", "verbose"),
665 arg_param_end
667 CLIExecWithReturn(ctx, Cmd, argtable, true);
668 bool verbose = arg_get_lit(ctx, 1);
669 CLIParserFree(ctx);
671 clearCommandBuffer();
672 SendCommandNG(CMD_SMART_ATR, NULL, 0);
673 PacketResponseNG resp;
674 if (WaitForResponseTimeout(CMD_SMART_ATR, &resp, 2500) == false) {
675 if (verbose) {
676 PrintAndLogEx(WARNING, "smart card timeout");
678 return PM3_ETIMEOUT;
681 if (resp.status != PM3_SUCCESS) {
682 if (verbose) {
683 PrintAndLogEx(WARNING, "smart card select failed");
685 return PM3_ESOFT;
688 smart_card_atr_t card;
689 memcpy(&card, (smart_card_atr_t *)resp.data.asBytes, sizeof(smart_card_atr_t));
691 // print header
692 PrintAndLogEx(INFO, "--- " _CYAN_("Smartcard Information") " ---------");
693 PrintAndLogEx(INFO, "ISO7618-3 ATR : %s", sprint_hex(card.atr, card.atr_len));
694 PrintAndLogEx(INFO, "http://smartcard-atr.apdu.fr/parse?ATR=%s", sprint_hex_inrow(card.atr, card.atr_len));
696 // print ATR
697 PrintAndLogEx(INFO, "ATR");
698 PrintATR(card.atr, card.atr_len);
700 // print D/F (brom byte TA1 or defaults)
701 PrintAndLogEx(NORMAL, "");
702 PrintAndLogEx(INFO, "D/F (TA1)");
703 int Di = GetATRDi(card.atr, card.atr_len);
704 int Fi = GetATRFi(card.atr, card.atr_len);
705 float F = GetATRF(card.atr, card.atr_len);
706 if (GetATRTA1(card.atr, card.atr_len) == 0x11)
707 PrintAndLogEx(INFO, "Using default values...");
709 PrintAndLogEx(INFO, "\t- Di %d", Di);
710 PrintAndLogEx(INFO, "\t- Fi %d", Fi);
711 PrintAndLogEx(INFO, "\t- F %.1f MHz", F);
713 if (Di && Fi) {
714 PrintAndLogEx(INFO, "\t- Cycles/ETU %d", Fi / Di);
715 PrintAndLogEx(INFO, "\t- %.1f bits/sec at 4 MHz", (float)4000000 / (Fi / Di));
716 PrintAndLogEx(INFO, "\t- %.1f bits/sec at Fmax (%.1fMHz)", (F * 1000000) / (Fi / Di), F);
717 } else {
718 PrintAndLogEx(WARNING, "\t- Di or Fi is RFU.");
721 return PM3_SUCCESS;
724 static int CmdSmartReader(const char *Cmd) {
725 CLIParserContext *ctx;
726 CLIParserInit(&ctx, "smart reader",
727 "Act as a smart card reader.",
728 "smart reader"
731 void *argtable[] = {
732 arg_param_begin,
733 arg_lit0("v", "verbose", "verbose"),
734 arg_param_end
736 CLIExecWithReturn(ctx, Cmd, argtable, true);
737 bool verbose = arg_get_lit(ctx, 1);
738 CLIParserFree(ctx);
740 clearCommandBuffer();
741 SendCommandNG(CMD_SMART_ATR, NULL, 0);
742 PacketResponseNG resp;
743 if (WaitForResponseTimeout(CMD_SMART_ATR, &resp, 2500) == false) {
744 if (verbose) {
745 PrintAndLogEx(WARNING, "smart card select failed");
747 return PM3_ETIMEOUT;
750 if (resp.status != PM3_SUCCESS) {
751 if (verbose) {
752 PrintAndLogEx(WARNING, "smart card select failed");
754 return PM3_ESOFT;
756 smart_card_atr_t *card = (smart_card_atr_t *)resp.data.asBytes;
757 PrintAndLogEx(INFO, "ISO7816-3 ATR : %s", sprint_hex(card->atr, card->atr_len));
758 return PM3_SUCCESS;
761 static int CmdSmartSetClock(const char *Cmd) {
763 CLIParserContext *ctx;
764 CLIParserInit(&ctx, "smart setclock",
765 "Set clock speed for smart card interface.",
766 "smart setclock --4mhz\n"
767 "smart setclock --16mhz"
770 void *argtable[] = {
771 arg_param_begin,
772 arg_lit0(NULL, "16mhz", "16 MHz clock speed"),
773 arg_lit0(NULL, "8mhz", "8 MHz clock speed"),
774 arg_lit0(NULL, "4mhz", "4 MHz clock speed"),
775 arg_param_end
777 CLIExecWithReturn(ctx, Cmd, argtable, false);
778 bool c16 = arg_get_lit(ctx, 1);
779 bool c8 = arg_get_lit(ctx, 2);
780 bool c4 = arg_get_lit(ctx, 3);
781 CLIParserFree(ctx);
783 if ((c16 + c8 + c4) > 1) {
784 PrintAndLogEx(WARNING, "Only one clock speed can be used at a time");
785 return PM3_EINVARG;
788 struct {
789 uint32_t new_clk;
790 } PACKED payload;
792 if (c16)
793 payload.new_clk = 0;
794 else if (c8)
795 payload.new_clk = 1;
796 else if (c4)
797 payload.new_clk = 2;
799 clearCommandBuffer();
800 SendCommandNG(CMD_SMART_SETCLOCK, (uint8_t *)&payload, sizeof(payload));
801 PacketResponseNG resp;
802 if (!WaitForResponseTimeout(CMD_SMART_SETCLOCK, &resp, 2500)) {
803 PrintAndLogEx(WARNING, "smart card select failed");
804 return PM3_ETIMEOUT;
807 if (resp.status != PM3_SUCCESS) {
808 PrintAndLogEx(WARNING, "smart card set clock failed");
809 return PM3_ESOFT;
812 switch (payload.new_clk) {
813 case 0:
814 PrintAndLogEx(SUCCESS, "Clock changed to " _GREEN_("16") " MHz giving " _GREEN_("10800") " baudrate");
815 break;
816 case 1:
817 PrintAndLogEx(SUCCESS, "Clock changed to " _GREEN_("8") " MHz giving " _GREEN_("21600") " baudrate");
818 break;
819 case 2:
820 PrintAndLogEx(SUCCESS, "Clock changed to " _GREEN_("4") " MHz giving " _GREEN_("86400") " baudrate");
821 break;
822 default:
823 break;
825 return PM3_SUCCESS;
828 static int CmdSmartList(const char *Cmd) {
829 return CmdTraceListAlias(Cmd, "smart", "7816");
832 static void smart_brute_prim(void) {
834 uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
835 if (!buf)
836 return;
838 uint8_t get_card_data[] = {
839 0x80, 0xCA, 0x9F, 0x13, 0x00,
840 0x80, 0xCA, 0x9F, 0x17, 0x00,
841 0x80, 0xCA, 0x9F, 0x36, 0x00,
842 0x80, 0xCA, 0x9F, 0x4f, 0x00
845 PrintAndLogEx(INFO, "Reading primitives");
847 for (int i = 0; i < ARRAYLEN(get_card_data); i += 5) {
849 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + 5);
850 payload->flags = SC_RAW_T0;
851 payload->len = 5;
852 memcpy(payload->data, get_card_data + i, 5);
854 clearCommandBuffer();
855 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + 5);
856 free(payload);
858 int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
859 if (len > 2) {
860 PrintAndLogEx(SUCCESS, "\tHEX %d |: %s", len, sprint_hex(buf, len));
863 free(buf);
866 static int smart_brute_sfi(bool decodeTLV) {
868 uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
869 if (buf == NULL)
870 return 1;
872 int len;
873 // READ RECORD
874 uint8_t READ_RECORD[] = {0x00, 0xB2, 0x00, 0x00, 0x00};
875 PrintAndLogEx(INFO, "Start SFI brute forcing");
877 for (uint8_t sfi = 1; sfi <= 31; sfi++) {
879 PrintAndLogEx(NORMAL, "." NOLF);
881 for (uint16_t rec = 1; rec <= 255; rec++) {
883 if (kbd_enter_pressed()) {
884 PrintAndLogEx(WARNING, "\naborted via keyboard!\n");
885 free(buf);
886 return 1;
889 READ_RECORD[2] = rec;
890 READ_RECORD[3] = (sfi << 3) | 4;
892 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + sizeof(READ_RECORD));
893 payload->flags = SC_RAW_T0;
894 payload->len = sizeof(READ_RECORD);
895 memcpy(payload->data, READ_RECORD, sizeof(READ_RECORD));
897 clearCommandBuffer();
898 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(READ_RECORD));
900 len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
902 if (buf[0] == 0x6C) {
903 READ_RECORD[4] = buf[1];
905 memcpy(payload->data, READ_RECORD, sizeof(READ_RECORD));
906 clearCommandBuffer();
907 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(READ_RECORD));
908 len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
910 READ_RECORD[4] = 0;
913 free(payload);
915 if (len > 4) {
917 PrintAndLogEx(SUCCESS, "\n\t file %02d, record %02d found", sfi, rec);
919 uint8_t modifier = (buf[0] == 0xC0) ? 1 : 0;
921 if (decodeTLV) {
922 if (!TLVPrintFromBuffer(buf + modifier, len - 2 - modifier)) {
923 PrintAndLogEx(SUCCESS, "\tHEX: %s", sprint_hex(buf, len));
927 memset(buf, 0x00, PM3_CMD_DATA_SIZE);
930 free(buf);
931 return 0;
934 static void smart_brute_options(bool decodeTLV) {
936 uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
937 if (!buf)
938 return;
940 // Get processing options command
941 uint8_t GET_PROCESSING_OPTIONS[] = {0x80, 0xA8, 0x00, 0x00, 0x02, 0x83, 0x00, 0x00};
943 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + sizeof(GET_PROCESSING_OPTIONS));
944 payload->flags = SC_RAW_T0;
945 payload->len = sizeof(GET_PROCESSING_OPTIONS);
946 memcpy(payload->data, GET_PROCESSING_OPTIONS, sizeof(GET_PROCESSING_OPTIONS));
948 clearCommandBuffer();
949 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(GET_PROCESSING_OPTIONS));
950 free(payload);
952 int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
953 if (len > 4) {
954 PrintAndLogEx(SUCCESS, "Got processing options");
955 if (decodeTLV) {
956 TLVPrintFromBuffer(buf, len - 2);
958 } else {
959 PrintAndLogEx(FAILED, "Getting processing options failed");
962 free(buf);
965 static int CmdSmartBruteforceSFI(const char *Cmd) {
966 CLIParserContext *ctx;
967 CLIParserInit(&ctx, "smart brute",
968 "Tries to bruteforce SFI, using a known list of AID's",
969 "smart brute -t"
972 void *argtable[] = {
973 arg_param_begin,
974 arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
975 // arg_lit0("0", NULL, "use protocol T=0"),
976 arg_param_end
978 CLIExecWithReturn(ctx, Cmd, argtable, true);
979 bool decode_tlv = arg_get_lit(ctx, 1);
980 // bool use_t0 = arg_get_lit(ctx, 2);
981 CLIParserFree(ctx);
983 const char *SELECT = "00a40400%02zu%s";
985 // uint8_t GENERATE_AC[] = {0x80, 0xAE};
986 // uint8_t GET_CHALLENGE[] = {0x00, 0x84, 0x00};
987 // uint8_t GET_DATA[] = {0x80, 0xCA, 0x00, 0x00, 0x00};
988 // uint8_t SELECT[] = {0x00, 0xA4, 0x04, 0x00};
989 // uint8_t UNBLOCK_PIN[] = {0x84, 0x24, 0x00, 0x00, 0x00};
990 // uint8_t VERIFY[] = {0x00, 0x20, 0x00, 0x80};
992 PrintAndLogEx(INFO, "Importing AID list");
993 json_t *root = NULL;
994 smart_loadjson("aidlist", &root);
996 uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
997 if (!buf)
998 return PM3_EMALLOC;
1000 PrintAndLogEx(INFO, "Selecting card");
1001 if (!smart_select(false, NULL)) {
1002 free(buf);
1003 return PM3_ESOFT;
1006 char *caid = NULL;
1008 for (int i = 0; i < json_array_size(root); i++) {
1010 PrintAndLogEx(NORMAL, "+" NOLF);
1012 if (caid)
1013 free(caid);
1015 json_t *data, *jaid;
1017 data = json_array_get(root, i);
1018 if (json_is_object(data) == false) {
1019 PrintAndLogEx(ERR, "\ndata %d is not an object\n", i + 1);
1020 json_decref(root);
1021 return PM3_ESOFT;
1024 jaid = json_object_get(data, "AID");
1025 if (json_is_string(jaid) == false) {
1026 PrintAndLogEx(ERR, "\nAID data [%d] is not a string", i + 1);
1027 json_decref(root);
1028 return PM3_ESOFT;
1031 const char *aid = json_string_value(jaid);
1032 if (aid == false)
1033 continue;
1035 size_t aidlen = strlen(aid);
1036 caid = calloc(8 + 2 + aidlen + 1, sizeof(uint8_t));
1037 snprintf(caid, 8 + 2 + aidlen + 1, SELECT, aidlen >> 1, aid);
1039 int hexlen = 0;
1040 uint8_t cmddata[PM3_CMD_DATA_SIZE];
1041 int res = param_gethex_to_eol(caid, 0, cmddata, sizeof(cmddata), &hexlen);
1042 if (res)
1043 continue;
1045 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + hexlen);
1046 payload->flags = SC_RAW_T0;
1047 payload->len = hexlen;
1049 memcpy(payload->data, cmddata, hexlen);
1050 clearCommandBuffer();
1051 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + hexlen);
1052 free(payload);
1054 int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
1055 if (len < 3)
1056 continue;
1058 json_t *jvendor, *jname;
1059 jvendor = json_object_get(data, "Vendor");
1060 if (json_is_string(jvendor) == false) {
1061 PrintAndLogEx(ERR, "Vendor data [%d] is not a string", i + 1);
1062 continue;
1065 const char *vendor = json_string_value(jvendor);
1066 if (!vendor)
1067 continue;
1069 jname = json_object_get(data, "Name");
1070 if (json_is_string(jname) == false) {
1071 PrintAndLogEx(ERR, "Name data [%d] is not a string", i + 1);
1072 continue;
1074 const char *name = json_string_value(jname);
1075 if (!name)
1076 continue;
1078 PrintAndLogEx(SUCCESS, "\nAID %s | %s | %s", aid, vendor, name);
1080 smart_brute_options(decode_tlv);
1082 smart_brute_prim();
1084 smart_brute_sfi(decode_tlv);
1086 PrintAndLogEx(SUCCESS, "\nSFI brute force done\n");
1089 if (caid)
1090 free(caid);
1092 free(buf);
1093 json_decref(root);
1095 PrintAndLogEx(SUCCESS, "\nSearch completed.");
1096 return PM3_SUCCESS;
1099 static command_t CommandTable[] = {
1100 {"help", CmdHelp, AlwaysAvailable, "This help"},
1101 {"list", CmdSmartList, AlwaysAvailable, "List ISO 7816 history"},
1102 {"info", CmdSmartInfo, IfPm3Smartcard, "Tag information"},
1103 {"reader", CmdSmartReader, IfPm3Smartcard, "Act like an IS07816 reader"},
1104 {"raw", CmdSmartRaw, IfPm3Smartcard, "Send raw hex data to tag"},
1105 {"upgrade", CmdSmartUpgrade, AlwaysAvailable, "Upgrade sim module firmware"},
1106 {"setclock", CmdSmartSetClock, IfPm3Smartcard, "Set clock speed"},
1107 {"brute", CmdSmartBruteforceSFI, IfPm3Smartcard, "Bruteforce SFI"},
1108 {NULL, NULL, NULL, NULL}
1111 static int CmdHelp(const char *Cmd) {
1112 (void)Cmd; // Cmd is not used so far
1113 CmdsHelp(CommandTable);
1114 return PM3_SUCCESS;
1117 int CmdSmartcard(const char *Cmd) {
1118 clearCommandBuffer();
1119 return CmdsParse(CommandTable, Cmd);
1122 int ExchangeAPDUSC(bool verbose, uint8_t *datain, int datainlen, bool activateCard, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) {
1124 *dataoutlen = 0;
1126 smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + datainlen);
1127 payload->flags = (SC_RAW_T0 | SC_LOG);
1128 if (activateCard) {
1129 payload->flags |= (SC_SELECT | SC_CONNECT);
1131 payload->len = datainlen;
1132 memcpy(payload->data, datain, datainlen);
1134 clearCommandBuffer();
1135 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + datainlen);
1137 int len = smart_responseEx(dataout, maxdataoutlen, verbose);
1138 if (len < 0) {
1139 free(payload);
1140 return 1;
1143 // retry
1144 if (len > 1 && dataout[len - 2] == 0x6c && datainlen > 4) {
1146 payload->flags = SC_RAW_T0;
1147 payload->len = 5;
1148 // transfer length via T=0
1149 datain[4] = dataout[len - 1];
1150 memcpy(payload->data, datain, 5);
1151 clearCommandBuffer();
1152 SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + 5);
1153 datain[4] = 0;
1154 len = smart_responseEx(dataout, maxdataoutlen, verbose);
1157 free(payload);
1158 *dataoutlen = len;
1159 return 0;
1162 bool smart_select(bool verbose, smart_card_atr_t *atr) {
1163 if (atr)
1164 memset(atr, 0, sizeof(smart_card_atr_t));
1166 clearCommandBuffer();
1167 SendCommandNG(CMD_SMART_ATR, NULL, 0);
1168 PacketResponseNG resp;
1169 if (WaitForResponseTimeout(CMD_SMART_ATR, &resp, 2500) == false) {
1170 if (verbose) PrintAndLogEx(WARNING, "smart card select timeouted");
1171 return false;
1174 if (resp.status != PM3_SUCCESS) {
1175 if (verbose) PrintAndLogEx(WARNING, "smart card select failed");
1176 return false;
1179 smart_card_atr_t card;
1180 memcpy(&card, (smart_card_atr_t *)resp.data.asBytes, sizeof(smart_card_atr_t));
1182 if (atr)
1183 memcpy(atr, &card, sizeof(smart_card_atr_t));
1185 if (verbose)
1186 PrintAndLogEx(INFO, "ISO7816-3 ATR : %s", sprint_hex(card.atr, card.atr_len));
1188 return true;