textual
[RRG-proxmark3.git] / client / src / emv / cmdemv.c
blob11111c53075114ce007cba2b3f29491e8f24d232
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2017 Merlok
3 // modified 2017 iceman
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 // EMV commands
9 //-----------------------------------------------------------------------------
11 #include "cmdemv.h"
13 #include <string.h>
15 #include "comms.h" // DropField
16 #include "cmdsmartcard.h" // smart_select
17 #include "cmdtrace.h"
18 #include "emvjson.h"
19 #include "test/cryptotest.h"
20 #include "cliparser.h"
21 #include "cmdparser.h"
22 #include "proxmark3.h"
23 #include "emv_roca.h"
24 #include "emvcore.h"
25 #include "cmdhf14a.h"
26 #include "dol.h"
27 #include "ui.h"
28 #include "emv_tags.h"
29 #include "fileutils.h"
31 static int CmdHelp(const char *Cmd);
33 #define TLV_ADD(tag, value)( tlvdb_change_or_add_node(tlvRoot, tag, sizeof(value) - 1, (const unsigned char *)value) )
34 static void ParamLoadDefaults(struct tlvdb *tlvRoot) {
35 //9F02:(Amount, authorized (Numeric)) len:6
36 TLV_ADD(0x9F02, "\x00\x00\x00\x00\x01\x00");
37 //9F1A:(Terminal Country Code) len:2
38 TLV_ADD(0x9F1A, "ru");
39 //5F2A:(Transaction Currency Code) len:2
40 // USD 840, EUR 978, RUR 810, RUB 643, RUR 810(old), UAH 980, AZN 031, n/a 999
41 TLV_ADD(0x5F2A, "\x09\x80");
42 //9A:(Transaction Date) len:3
43 TLV_ADD(0x9A, "\x00\x00\x00");
44 //9C:(Transaction Type) len:1 | 00 => Goods and service #01 => Cash
45 TLV_ADD(0x9C, "\x00");
46 // 9F37 Unpredictable Number len:4
47 TLV_ADD(0x9F37, "\x01\x02\x03\x04");
48 // 9F6A Unpredictable Number (MSD for UDOL) len:4
49 TLV_ADD(0x9F6A, "\x01\x02\x03\x04");
50 //9F66:(Terminal Transaction Qualifiers (TTQ)) len:4
51 TLV_ADD(0x9F66, "\x26\x00\x00\x00"); // qVSDC
52 //95:(Terminal Verification Results) len:5
53 // all OK TVR
54 TLV_ADD(0x95, "\x00\x00\x00\x00\x00");
55 // 9F4E Merchant Name and Location len:x
56 TLV_ADD(0x9F4E, "proxmrk3rdv\x00");
59 static void PrintChannel(Iso7816CommandChannel channel) {
60 switch (channel) {
61 case CC_CONTACTLESS:
62 PrintAndLogEx(INFO, "Selected channel... " _GREEN_("CONTACTLESS (T=CL)"));
63 break;
64 case CC_CONTACT:
65 PrintAndLogEx(INFO, "Selected channel... " _GREEN_("CONTACT"));
66 break;
70 static int CmdEMVSelect(const char *Cmd) {
71 uint8_t data[APDU_AID_LEN] = {0};
72 int datalen = 0;
74 CLIParserContext *ctx;
75 CLIParserInit(&ctx, "emv select",
76 "Executes select applet command",
77 "emv select -s a00000000101 -> select card, select applet\n"
78 "emv select -st a00000000101 -> select card, select applet, show result in TLV\n");
80 void *argtable[] = {
81 arg_param_begin,
82 arg_lit0("sS", "select", "activate field and select card"),
83 arg_lit0("kK", "keep", "keep field for next command"),
84 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
85 arg_lit0("tT", "tlv", "TLV decode results"),
86 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
87 arg_strx0(NULL, NULL, "<HEX applet AID>", NULL),
88 arg_param_end
90 CLIExecWithReturn(ctx, Cmd, argtable, true);
92 bool activateField = arg_get_lit(ctx, 1);
93 bool leaveSignalON = arg_get_lit(ctx, 2);
94 bool APDULogging = arg_get_lit(ctx, 3);
95 bool decodeTLV = arg_get_lit(ctx, 4);
96 Iso7816CommandChannel channel = CC_CONTACTLESS;
97 if (arg_get_lit(ctx, 5))
98 channel = CC_CONTACT;
99 PrintChannel(channel);
100 CLIGetHexWithReturn(ctx, 6, data, &datalen);
101 CLIParserFree(ctx);
103 SetAPDULogging(APDULogging);
105 // exec
106 uint8_t buf[APDU_RES_LEN] = {0};
107 size_t len = 0;
108 uint16_t sw = 0;
109 int res = EMVSelect(channel, activateField, leaveSignalON, data, datalen, buf, sizeof(buf), &len, &sw, NULL);
111 if (sw)
112 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
114 if (res)
115 return res;
117 if (decodeTLV)
118 TLVPrintFromBuffer(buf, len);
120 return PM3_SUCCESS;
123 static int CmdEMVSearch(const char *Cmd) {
125 CLIParserContext *ctx;
126 CLIParserInit(&ctx, "emv search",
127 "Tries to select all applets from applet list\n",
128 "emv search -s -> select card and search\n"
129 "emv search -st -> select card, search and show result in TLV\n");
131 void *argtable[] = {
132 arg_param_begin,
133 arg_lit0("sS", "select", "activate field and select card"),
134 arg_lit0("kK", "keep", "keep field ON for next command"),
135 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
136 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
137 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
138 arg_param_end
140 CLIExecWithReturn(ctx, Cmd, argtable, true);
142 bool activateField = arg_get_lit(ctx, 1);
143 bool leaveSignalON = arg_get_lit(ctx, 2);
144 bool APDULogging = arg_get_lit(ctx, 3);
145 bool decodeTLV = arg_get_lit(ctx, 4);
146 Iso7816CommandChannel channel = CC_CONTACTLESS;
147 if (arg_get_lit(ctx, 5))
148 channel = CC_CONTACT;
149 PrintChannel(channel);
150 CLIParserFree(ctx);
152 SetAPDULogging(APDULogging);
154 const char *al = "Applets list";
155 struct tlvdb *t = tlvdb_fixed(1, strlen(al), (const unsigned char *)al);
157 if (EMVSearch(channel, activateField, leaveSignalON, decodeTLV, t)) {
158 tlvdb_free(t);
159 return PM3_ERFTRANS;
162 PrintAndLogEx(SUCCESS, "Search completed.");
164 // print list here
165 if (!decodeTLV) {
166 TLVPrintAIDlistFromSelectTLV(t);
169 tlvdb_free(t);
171 return PM3_SUCCESS;
174 static int CmdEMVPPSE(const char *Cmd) {
176 CLIParserContext *ctx;
177 CLIParserInit(&ctx, "emv pse",
178 "Executes PSE/PPSE select command. It returns list of applet on the card:\n",
179 "emv pse -s1 -> select, get pse\n"
180 "emv pse -st2 -> select, get ppse, show result in TLV\n");
182 void *argtable[] = {
183 arg_param_begin,
184 arg_lit0("sS", "select", "activate field and select card"),
185 arg_lit0("kK", "keep", "keep field ON for next command"),
186 arg_lit0("1", "pse", "pse (1PAY.SYS.DDF01) mode"),
187 arg_lit0("2", "ppse", "ppse (2PAY.SYS.DDF01) mode (default mode)"),
188 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
189 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
190 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
191 arg_param_end
193 CLIExecWithReturn(ctx, Cmd, argtable, true);
195 bool activateField = arg_get_lit(ctx, 1);
196 bool leaveSignalON = arg_get_lit(ctx, 2);
197 uint8_t PSENum = 2;
198 if (arg_get_lit(ctx, 3))
199 PSENum = 1;
200 if (arg_get_lit(ctx, 4))
201 PSENum = 2;
202 bool APDULogging = arg_get_lit(ctx, 5);
203 bool decodeTLV = arg_get_lit(ctx, 6);
204 Iso7816CommandChannel channel = CC_CONTACTLESS;
205 if (arg_get_lit(ctx, 7))
206 channel = CC_CONTACT;
207 PrintChannel(channel);
208 CLIParserFree(ctx);
210 SetAPDULogging(APDULogging);
212 // exec
213 uint8_t buf[APDU_RES_LEN] = {0};
214 size_t len = 0;
215 uint16_t sw = 0;
216 int res = EMVSelectPSE(channel, activateField, leaveSignalON, PSENum, buf, sizeof(buf), &len, &sw);
218 if (sw)
219 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
221 if (res)
222 return res;
224 if (decodeTLV)
225 TLVPrintFromBuffer(buf, len);
227 return PM3_SUCCESS;
230 static int CmdEMVGPO(const char *Cmd) {
231 uint8_t data[APDU_RES_LEN] = {0};
232 int datalen = 0;
234 CLIParserContext *ctx;
235 CLIParserInit(&ctx, "emv gpo",
236 "Executes Get Processing Options command. It returns data in TLV format (0x77 - format2)\n"
237 "or plain format (0x80 - format1). Needs a EMV applet to be selected.",
238 "emv gpo -k -> execute GPO\n"
239 "emv gpo -t 01020304 -> execute GPO with 4-byte PDOL data, show result in TLV\n"
240 "emv gpo -pmt 9F 37 04 -> load params from file, make PDOL data from PDOL, execute GPO with PDOL, show result in TLV\n");
242 void *argtable[] = {
243 arg_param_begin,
244 arg_lit0("kK", "keep", "keep field ON for next command"),
245 arg_lit0("pP", "params", "load parameters from `emv_defparams.json` file for PDOLdata making from PDOL and parameters"),
246 arg_lit0("mM", "make", "make PDOLdata from PDOL (tag 9F38) and parameters (by default uses default parameters)"),
247 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
248 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
249 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
250 arg_strx0(NULL, NULL, "<HEX PDOLdata/PDOL>", NULL),
251 arg_param_end
253 CLIExecWithReturn(ctx, Cmd, argtable, true);
255 bool leaveSignalON = arg_get_lit(ctx, 1);
256 bool paramsLoadFromFile = arg_get_lit(ctx, 2);
257 bool dataMakeFromPDOL = arg_get_lit(ctx, 3);
258 bool APDULogging = arg_get_lit(ctx, 4);
259 bool decodeTLV = arg_get_lit(ctx, 5);
260 Iso7816CommandChannel channel = CC_CONTACTLESS;
261 if (arg_get_lit(ctx, 6))
262 channel = CC_CONTACT;
263 PrintChannel(channel);
264 CLIGetHexWithReturn(ctx, 7, data, &datalen);
265 CLIParserFree(ctx);
267 SetAPDULogging(APDULogging);
269 // Init TLV tree
270 const char *alr = "Root terminal TLV tree";
271 struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
273 // calc PDOL
274 struct tlv *pdol_data_tlv = NULL;
275 struct tlvdb *tmp_ext = NULL;
276 struct tlv data_tlv = {
277 .tag = 0x83,
278 .len = datalen,
279 .value = (uint8_t *)data,
281 if (dataMakeFromPDOL) {
282 ParamLoadDefaults(tlvRoot);
284 if (paramsLoadFromFile) {
285 PrintAndLogEx(INFO, "Params loading from file...");
286 ParamLoadFromJson(tlvRoot);
289 tmp_ext = tlvdb_external(0x9f38, datalen, data);
290 pdol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x83);
291 if (!pdol_data_tlv) {
292 PrintAndLogEx(ERR, "Can't create PDOL TLV.");
293 tlvdb_free(tmp_ext);
294 tlvdb_free(tlvRoot);
295 return PM3_ESOFT;
297 } else {
298 if (paramsLoadFromFile) {
299 PrintAndLogEx(WARNING, "Don't need to load parameters. Sending plain PDOL data...");
301 pdol_data_tlv = &data_tlv;
304 size_t pdol_data_tlv_data_len = 0;
305 unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len);
306 if (!pdol_data_tlv_data) {
307 PrintAndLogEx(ERR, "Can't create PDOL data.");
308 tlvdb_free(tmp_ext);
309 tlvdb_free(tlvRoot);
310 if (pdol_data_tlv != &data_tlv)
311 free(pdol_data_tlv);
312 return PM3_ESOFT;
314 PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
316 // exec
317 uint8_t buf[APDU_RES_LEN] = {0};
318 size_t len = 0;
319 uint16_t sw = 0;
320 int res = EMVGPO(channel, leaveSignalON, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
322 if (pdol_data_tlv != &data_tlv)
323 free(pdol_data_tlv);
325 tlvdb_free(tmp_ext);
326 tlvdb_free(tlvRoot);
328 if (sw)
329 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
331 if (res)
332 return res;
334 if (decodeTLV)
335 TLVPrintFromBuffer(buf, len);
337 return PM3_SUCCESS;
340 static int CmdEMVReadRecord(const char *Cmd) {
341 uint8_t data[APDU_RES_LEN] = {0};
342 int datalen = 0;
344 CLIParserContext *ctx;
345 CLIParserInit(&ctx, "emv readrec",
346 "Executes Read Record command. It returns data in TLV format.\n"
347 "Needs a bank applet to be selected and sometimes needs GPO to be executed.",
348 "emv readrec -k 0101 -> read file SFI=01, SFIrec=01\n"
349 "emv readrec -kt 0201 -> read file 0201 and show result in TLV\n");
351 void *argtable[] = {
352 arg_param_begin,
353 arg_lit0("kK", "keep", "keep field ON for next command"),
354 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
355 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
356 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
357 arg_strx1(NULL, NULL, "<SFI 1byte HEX><SFIrecord 1byte HEX>", NULL),
358 arg_param_end
360 CLIExecWithReturn(ctx, Cmd, argtable, true);
362 bool leaveSignalON = arg_get_lit(ctx, 1);
363 bool APDULogging = arg_get_lit(ctx, 2);
364 bool decodeTLV = arg_get_lit(ctx, 3);
365 Iso7816CommandChannel channel = CC_CONTACTLESS;
366 if (arg_get_lit(ctx, 4))
367 channel = CC_CONTACT;
368 PrintChannel(channel);
369 CLIGetHexWithReturn(ctx, 5, data, &datalen);
370 CLIParserFree(ctx);
372 if (datalen != 2) {
373 PrintAndLogEx(ERR, "Command needs to have 2 bytes of data");
374 return PM3_EINVARG;
377 SetAPDULogging(APDULogging);
379 // exec
380 uint8_t buf[APDU_RES_LEN] = {0};
381 size_t len = 0;
382 uint16_t sw = 0;
383 int res = EMVReadRecord(channel, leaveSignalON, data[0], data[1], buf, sizeof(buf), &len, &sw, NULL);
385 if (sw)
386 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
388 if (res)
389 return res;
392 if (decodeTLV)
393 TLVPrintFromBuffer(buf, len);
395 return PM3_SUCCESS;
398 static int CmdEMVAC(const char *Cmd) {
399 uint8_t data[APDU_RES_LEN] = {0};
400 int datalen = 0;
402 CLIParserContext *ctx;
403 CLIParserInit(&ctx, "emv genac",
404 "Generate Application Cryptogram command. It returns data in TLV format.\n"
405 "Needs a EMV applet to be selected and GPO to be executed.",
406 "emv genac -k 0102 -> generate AC with 2-byte CDOLdata and keep field ON after command\n"
407 "emv genac -t 01020304 -> generate AC with 4-byte CDOL data, show result in TLV\n"
408 "emv genac -Daac 01020304 -> generate AC with 4-byte CDOL data and terminal decision 'declined'\n"
409 "emv genac -pmt 9F 37 04 -> load params from file, make CDOL data from CDOL, generate AC with CDOL, show result in TLV");
411 void *argtable[] = {
412 arg_param_begin,
413 arg_lit0("kK", "keep", "keep field ON for next command"),
414 arg_lit0("cC", "cda", "executes CDA transaction. Needs to get SDAD in results."),
415 arg_str0("dD", "decision", "<aac|tc|arqc>", "Terminal decision. aac - declined, tc - approved, arqc - online authorisation requested"),
416 arg_lit0("pP", "params", "load parameters from `emv_defparams.json` file for CDOLdata making from CDOL and parameters"),
417 arg_lit0("mM", "make", "make CDOLdata from CDOL (tag 8C and 8D) and parameters (by default uses default parameters)"),
418 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
419 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
420 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
421 arg_strx1(NULL, NULL, "<HEX CDOLdata/CDOL>", NULL),
422 arg_param_end
424 CLIExecWithReturn(ctx, Cmd, argtable, false);
426 bool leaveSignalON = arg_get_lit(ctx, 1);
427 bool trTypeCDA = arg_get_lit(ctx, 2);
428 uint8_t termDecision = 0xff;
429 if (arg_get_str_len(ctx, 3)) {
430 if (!strncmp(arg_get_str(ctx, 3)->sval[0], "aac", 4))
431 termDecision = EMVAC_AAC;
432 if (!strncmp(arg_get_str(ctx, 3)->sval[0], "tc", 4))
433 termDecision = EMVAC_TC;
434 if (!strncmp(arg_get_str(ctx, 3)->sval[0], "arqc", 4))
435 termDecision = EMVAC_ARQC;
437 if (termDecision == 0xff) {
438 PrintAndLogEx(ERR, "ERROR: can't find terminal decision '%s'", arg_get_str(ctx, 3)->sval[0]);
439 CLIParserFree(ctx);
440 return PM3_EINVARG;
442 } else {
443 termDecision = EMVAC_TC;
445 if (trTypeCDA)
446 termDecision = termDecision | EMVAC_CDAREQ;
447 bool paramsLoadFromFile = arg_get_lit(ctx, 4);
448 bool dataMakeFromCDOL = arg_get_lit(ctx, 5);
449 bool APDULogging = arg_get_lit(ctx, 6);
450 bool decodeTLV = arg_get_lit(ctx, 7);
452 Iso7816CommandChannel channel = CC_CONTACTLESS;
453 if (arg_get_lit(ctx, 8))
454 channel = CC_CONTACT;
456 PrintChannel(channel);
457 CLIGetHexWithReturn(ctx, 9, data, &datalen);
458 CLIParserFree(ctx);
460 SetAPDULogging(APDULogging);
462 // Init TLV tree
463 const char *alr = "Root terminal TLV tree";
464 struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
466 // calc CDOL
467 struct tlv *cdol_data_tlv = NULL;
468 struct tlvdb *tmp_ext = NULL;
469 struct tlv data_tlv = {
470 .tag = 0x01,
471 .len = datalen,
472 .value = (uint8_t *)data,
475 if (dataMakeFromCDOL) {
476 ParamLoadDefaults(tlvRoot);
478 if (paramsLoadFromFile) {
479 PrintAndLogEx(INFO, "Params loading from file...");
480 ParamLoadFromJson(tlvRoot);
483 tmp_ext = tlvdb_external(0x8c, datalen, data);
484 cdol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x01); // 0x01 - dummy tag
485 if (!cdol_data_tlv) {
486 PrintAndLogEx(ERR, "Can't create CDOL TLV.");
487 tlvdb_free(tmp_ext);
488 tlvdb_free(tlvRoot);
489 return PM3_ESOFT;
491 } else {
492 if (paramsLoadFromFile) {
493 PrintAndLogEx(WARNING, "Don't need to load parameters. Sending plain CDOL data...");
495 cdol_data_tlv = &data_tlv;
498 PrintAndLogEx(INFO, "CDOL data[%zu]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len));
500 // exec
501 uint8_t buf[APDU_RES_LEN] = {0};
502 size_t len = 0;
503 uint16_t sw = 0;
504 int res = EMVAC(channel, leaveSignalON, termDecision, (uint8_t *)cdol_data_tlv->value, cdol_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot);
506 if (cdol_data_tlv != &data_tlv)
507 free(cdol_data_tlv);
509 tlvdb_free(tmp_ext);
510 tlvdb_free(tlvRoot);
512 if (sw)
513 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
515 if (res)
516 return res;
518 if (decodeTLV)
519 TLVPrintFromBuffer(buf, len);
521 return PM3_SUCCESS;
524 static int CmdEMVGenerateChallenge(const char *Cmd) {
526 CLIParserContext *ctx;
527 CLIParserInit(&ctx, "emv challenge",
528 "Executes Generate Challenge command. It returns 4 or 8-byte random number from card.\n"
529 "Needs a EMV applet to be selected and GPO to be executed.",
530 "emv challenge -> get challenge\n"
531 "emv challenge -k -> get challenge, keep fileld ON\n");
533 void *argtable[] = {
534 arg_param_begin,
535 arg_lit0("kK", "keep", "keep field ON for next command"),
536 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
537 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
538 arg_param_end
540 CLIExecWithReturn(ctx, Cmd, argtable, true);
542 bool leaveSignalON = arg_get_lit(ctx, 1);
543 bool APDULogging = arg_get_lit(ctx, 2);
544 Iso7816CommandChannel channel = CC_CONTACTLESS;
545 if (arg_get_lit(ctx, 3))
546 channel = CC_CONTACT;
547 PrintChannel(channel);
548 CLIParserFree(ctx);
550 SetAPDULogging(APDULogging);
552 // exec
553 uint8_t buf[APDU_RES_LEN] = {0};
554 size_t len = 0;
555 uint16_t sw = 0;
556 int res = EMVGenerateChallenge(channel, leaveSignalON, buf, sizeof(buf), &len, &sw, NULL);
558 if (sw)
559 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
561 if (res)
562 return res;
564 PrintAndLogEx(SUCCESS, "Challenge: %s", sprint_hex(buf, len));
566 if (len != 4 && len != 8)
567 PrintAndLogEx(WARNING, "Length of challenge must be 4 or 8, but it %zu", len);
569 return PM3_SUCCESS;
572 static int CmdEMVInternalAuthenticate(const char *Cmd) {
573 uint8_t data[APDU_RES_LEN] = {0};
574 int datalen = 0;
576 CLIParserContext *ctx;
577 CLIParserInit(&ctx, "emv intauth",
578 "Generate Internal Authenticate command. Usually needs 4-byte random number. It returns data in TLV format .\n"
579 "Needs a EMV applet to be selected and GPO to be executed.",
581 "emv intauth -k 01020304 -> execute Internal Authenticate with 4-byte DDOLdata and keep field ON after command\n"
582 "emv intauth -t 01020304 -> execute Internal Authenticate with 4-byte DDOL data, show result in TLV\n"
583 "emv intauth -pmt 9F 37 04 -> load params from file, make DDOL data from DDOL, Internal Authenticate with DDOL, show result in TLV");
585 void *argtable[] = {
586 arg_param_begin,
587 arg_lit0("kK", "keep", "keep field ON for next command"),
588 arg_lit0("pP", "params", "load parameters from `emv_defparams.json` file for DDOLdata making from DDOL and parameters"),
589 arg_lit0("mM", "make", "make DDOLdata from DDOL (tag 9F49) and parameters (by default uses default parameters)"),
590 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
591 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
592 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
593 arg_strx1(NULL, NULL, "<HEX DDOLdata/DDOL>", NULL),
594 arg_param_end
596 CLIExecWithReturn(ctx, Cmd, argtable, false);
598 bool leaveSignalON = arg_get_lit(ctx, 1);
599 bool paramsLoadFromFile = arg_get_lit(ctx, 2);
600 bool dataMakeFromDDOL = arg_get_lit(ctx, 3);
601 bool APDULogging = arg_get_lit(ctx, 4);
602 bool decodeTLV = arg_get_lit(ctx, 5);
603 Iso7816CommandChannel channel = CC_CONTACTLESS;
604 if (arg_get_lit(ctx, 6))
605 channel = CC_CONTACT;
606 PrintChannel(channel);
607 CLIGetHexWithReturn(ctx, 7, data, &datalen);
608 CLIParserFree(ctx);
610 SetAPDULogging(APDULogging);
612 // Init TLV tree
613 const char *alr = "Root terminal TLV tree";
614 struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
616 // calc DDOL
617 struct tlv *ddol_data_tlv = NULL;
618 struct tlvdb *tmp_ext = NULL;
619 struct tlv data_tlv = {
620 .tag = 0x01,
621 .len = datalen,
622 .value = (uint8_t *)data,
625 if (dataMakeFromDDOL) {
626 ParamLoadDefaults(tlvRoot);
628 if (paramsLoadFromFile) {
629 PrintAndLogEx(INFO, "Params loading from file...");
630 ParamLoadFromJson(tlvRoot);
633 tmp_ext = tlvdb_external(0x9f49, datalen, data);
634 ddol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x01); // 0x01 - dummy tag
635 if (!ddol_data_tlv) {
636 PrintAndLogEx(ERR, "Can't create DDOL TLV.");
637 tlvdb_free(tmp_ext);
638 tlvdb_free(tlvRoot);
639 return PM3_ESOFT;
641 } else {
642 if (paramsLoadFromFile) {
643 PrintAndLogEx(WARNING, "Don't need to load parameters. Sending plain DDOL data...");
645 ddol_data_tlv = &data_tlv;
648 PrintAndLogEx(INFO, "DDOL data[%zu]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len));
650 // exec
651 uint8_t buf[APDU_RES_LEN] = {0};
652 size_t len = 0;
653 uint16_t sw = 0;
654 int res = EMVInternalAuthenticate(channel, leaveSignalON, data, datalen, buf, sizeof(buf), &len, &sw, NULL);
656 if (ddol_data_tlv != &data_tlv)
657 free(ddol_data_tlv);
659 tlvdb_free(tmp_ext);
660 tlvdb_free(tlvRoot);
662 if (sw)
663 PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
665 if (res)
666 return res;
668 if (decodeTLV)
669 TLVPrintFromBuffer(buf, len);
671 return PM3_SUCCESS;
674 #define dreturn(n) {free(pdol_data_tlv); tlvdb_free(tlvSelect); tlvdb_free(tlvRoot); DropFieldEx( channel ); return n;}
676 static void InitTransactionParameters(struct tlvdb *tlvRoot, bool paramLoadJSON, enum TransactionType TrType, bool GenACGPO) {
678 ParamLoadDefaults(tlvRoot);
680 if (paramLoadJSON) {
681 PrintAndLogEx(INFO, "* * Transaction parameters loading from JSON...");
682 ParamLoadFromJson(tlvRoot);
685 //9F66:(Terminal Transaction Qualifiers (TTQ)) len:4
687 switch (TrType) {
688 case TT_MSD:
689 TLV_ADD(0x9F66, "\x86\x00\x00\x00"); // MSD
690 break;
691 // not standard for contactless. just for test.
692 case TT_VSDC:
693 TLV_ADD(0x9F66, "\x46\x00\x00\x00"); // VSDC
694 break;
695 case TT_QVSDCMCHIP:
696 // qVSDC
697 if (GenACGPO) {
698 TLV_ADD(0x9F66, "\x26\x80\x00\x00");
699 } else {
700 TLV_ADD(0x9F66, "\x26\x00\x00\x00");
702 break;
703 case TT_CDA:
704 // qVSDC (VISA CDA not enabled)
705 if (GenACGPO) {
706 TLV_ADD(0x9F66, "\x26\x80\x00\x00");
707 } else {
708 TLV_ADD(0x9F66, "\x26\x00\x00\x00");
710 break;
711 default:
712 break;
716 static void ProcessGPOResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t len, bool decodeTLV) {
717 if (buf[0] == 0x80) {
718 if (decodeTLV) {
719 PrintAndLogEx(SUCCESS, "GPO response format1:");
720 TLVPrintFromBuffer(buf, len);
723 if (len < 4 || (len - 4) % 4) {
724 PrintAndLogEx(ERR, "GPO response format 1 parsing error. length = %zu", len);
725 } else {
726 // AIP
727 struct tlvdb *f1AIP = tlvdb_fixed(0x82, 2, buf + 2);
728 tlvdb_add(tlvRoot, f1AIP);
729 if (decodeTLV) {
730 PrintAndLogEx(INFO, "\n* * Decode response format 1 (0x80) AIP and AFL:");
731 TLVPrintFromTLV(f1AIP);
734 // AFL
735 struct tlvdb *f1AFL = tlvdb_fixed(0x94, len - 4, buf + 2 + 2);
736 tlvdb_add(tlvRoot, f1AFL);
737 if (decodeTLV)
738 TLVPrintFromTLV(f1AFL);
740 } else {
741 if (decodeTLV)
742 TLVPrintFromBuffer(buf, len);
746 static void ProcessACResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t len, bool decodeTLV) {
747 if (buf[0] == 0x80) {
748 if (decodeTLV) {
749 PrintAndLogEx(SUCCESS, "GPO response format 1:");
750 TLVPrintFromBuffer(buf, len);
753 uint8_t elmlen = len - 2; // wo 0x80XX
755 if (len < 4 + 2 || (elmlen - 2) % 4 || elmlen != buf[1]) {
756 PrintAndLogEx(ERR, "GPO response format1 parsing error. length=%zu", len);
757 } else {
758 struct tlvdb *tlvElm = NULL;
759 if (decodeTLV)
760 PrintAndLogEx(NORMAL, "\n------------ Format1 decoded ------------");
762 // CID (Cryptogram Information Data)
763 tlvdb_change_or_add_node_ex(tlvRoot, 0x9f27, 1, &buf[2], &tlvElm);
764 if (decodeTLV)
765 TLVPrintFromTLV(tlvElm);
767 // ATC (Application Transaction Counter)
768 tlvdb_change_or_add_node_ex(tlvRoot, 0x9f36, 2, &buf[3], &tlvElm);
769 if (decodeTLV)
770 TLVPrintFromTLV(tlvElm);
772 // AC (Application Cryptogram)
773 tlvdb_change_or_add_node_ex(tlvRoot, 0x9f26, MIN(8, elmlen - 3), &buf[5], &tlvElm);
774 if (decodeTLV)
775 TLVPrintFromTLV(tlvElm);
777 // IAD (Issuer Application Data) - optional
778 if (len > 11 + 2) {
779 tlvdb_change_or_add_node_ex(tlvRoot, 0x9f10, elmlen - 11, &buf[13], &tlvElm);
780 if (decodeTLV)
781 TLVPrintFromTLV(tlvElm);
783 tlvdb_free(tlvElm);
785 } else {
786 if (decodeTLV)
787 TLVPrintFromBuffer(buf, len);
791 static int CmdEMVExec(const char *Cmd) {
792 uint8_t buf[APDU_RES_LEN] = {0};
793 size_t len = 0;
794 uint16_t sw = 0;
795 uint8_t AID[APDU_AID_LEN] = {0};
796 size_t AIDlen = 0;
797 uint8_t ODAiList[4096];
798 size_t ODAiListLen = 0;
800 int res;
802 struct tlvdb *tlvSelect = NULL;
803 struct tlvdb *tlvRoot = NULL;
804 struct tlv *pdol_data_tlv = NULL;
806 CLIParserContext *ctx;
807 CLIParserInit(&ctx, "emv exec",
808 "Executes EMV contactless transaction",
809 "emv exec -sat -> select card, execute MSD transaction, show APDU and TLV\n"
810 "emv exec -satc -> select card, execute CDA transaction, show APDU and TLV\n");
812 void *argtable[] = {
813 arg_param_begin,
814 arg_lit0("sS", "select", "activate field and select card."),
815 arg_lit0("aA", "apdu", "show APDU reqests and responses."),
816 arg_lit0("tT", "tlv", "TLV decode results."),
817 arg_lit0("jJ", "jload", "Load transaction parameters from `emv_defparams.json` file."),
818 arg_lit0("fF", "forceaid", "Force search AID. Search AID instead of execute PPSE."),
819 arg_rem("By default:", "Transaction type - MSD"),
820 arg_lit0("vV", "qvsdc", "Transaction type - qVSDC or M/Chip."),
821 arg_lit0("cC", "qvsdccda", "Transaction type - qVSDC or M/Chip plus CDA (SDAD generation)."),
822 arg_lit0("xX", "vsdc", "Transaction type - VSDC. For test only. Not a standard behavior."),
823 arg_lit0("gG", "acgpo", "VISA. generate AC from GPO."),
824 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
825 arg_param_end
827 CLIExecWithReturn(ctx, Cmd, argtable, true);
829 bool activateField = arg_get_lit(ctx, 1);
830 bool showAPDU = arg_get_lit(ctx, 2);
831 bool decodeTLV = arg_get_lit(ctx, 3);
832 bool paramLoadJSON = arg_get_lit(ctx, 4);
833 bool forceSearch = arg_get_lit(ctx, 5);
835 enum TransactionType TrType = TT_MSD;
836 if (arg_get_lit(ctx, 7))
837 TrType = TT_QVSDCMCHIP;
838 if (arg_get_lit(ctx, 8))
839 TrType = TT_CDA;
840 if (arg_get_lit(ctx, 9))
841 TrType = TT_VSDC;
843 bool GenACGPO = arg_get_lit(ctx, 10);
844 Iso7816CommandChannel channel = CC_CONTACTLESS;
845 if (arg_get_lit(ctx, 11))
846 channel = CC_CONTACT;
847 PrintChannel(channel);
848 uint8_t psenum = (channel == CC_CONTACT) ? 1 : 2;
849 CLIParserFree(ctx);
851 if (!IfPm3Smartcard()) {
852 if (channel == CC_CONTACT) {
853 PrintAndLogEx(WARNING, "PM3 does not have SMARTCARD support. Exiting.");
854 return PM3_EDEVNOTSUPP;
858 SetAPDULogging(showAPDU);
860 // init applets list tree
861 const char *al = "Applets list";
862 tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al);
864 // Application Selection
865 // https://www.openscdp.org/scripts/tutorial/emv/applicationselection.html
866 if (!forceSearch) {
867 // PPSE
868 PrintAndLogEx(NORMAL, "\n* PPSE.");
869 SetAPDULogging(showAPDU);
870 res = EMVSearchPSE(channel, activateField, true, psenum, decodeTLV, tlvSelect);
872 // check PPSE instead of PSE and vice versa
873 if (res) {
874 PrintAndLogEx(NORMAL, "Check PPSE instead of PSE and vice versa...");
875 res = EMVSearchPSE(channel, false, true, psenum == 1 ? 2 : 1, decodeTLV, tlvSelect);
878 // check PPSE and select application id
879 if (!res) {
880 TLVPrintAIDlistFromSelectTLV(tlvSelect);
881 EMVSelectApplication(tlvSelect, AID, &AIDlen);
885 // Search
886 if (!AIDlen) {
887 PrintAndLogEx(NORMAL, "\n* Search AID in list.");
888 SetAPDULogging(false);
889 if (EMVSearch(channel, activateField, true, decodeTLV, tlvSelect)) {
890 dreturn(PM3_ERFTRANS);
893 // check search and select application id
894 TLVPrintAIDlistFromSelectTLV(tlvSelect);
895 EMVSelectApplication(tlvSelect, AID, &AIDlen);
898 // Init TLV tree
899 const char *alr = "Root terminal TLV tree";
900 tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
902 // check if we found EMV application on card
903 if (!AIDlen) {
904 PrintAndLogEx(WARNING, "Can't select AID. EMV AID not found");
905 dreturn(PM3_ERFTRANS);
908 // Select
909 PrintAndLogEx(NORMAL, "\n* Selecting AID:%s", sprint_hex_inrow(AID, AIDlen));
910 SetAPDULogging(showAPDU);
911 res = EMVSelect(channel, false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot);
913 if (res) {
914 PrintAndLogEx(WARNING, "Can't select AID (%d). Exit...", res);
915 dreturn(PM3_ERFTRANS);
918 if (decodeTLV)
919 TLVPrintFromBuffer(buf, len);
920 PrintAndLogEx(NORMAL, "* Selected.");
922 PrintAndLogEx(NORMAL, "\n* Init transaction parameters.");
923 InitTransactionParameters(tlvRoot, paramLoadJSON, TrType, GenACGPO);
924 TLVPrintFromTLV(tlvRoot); // TODO delete!!!
926 PrintAndLogEx(NORMAL, "\n* Calc PDOL.");
927 pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83);
928 if (!pdol_data_tlv) {
929 PrintAndLogEx(ERR, "Error: can't create PDOL TLV.");
930 dreturn(PM3_ESOFT);
933 size_t pdol_data_tlv_data_len;
934 unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len);
935 if (!pdol_data_tlv_data) {
936 PrintAndLogEx(ERR, "Error: can't create PDOL data.");
937 dreturn(PM3_ESOFT);
939 PrintAndLogEx(NORMAL, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
941 PrintAndLogEx(NORMAL, "\n* GPO.");
942 res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
944 free(pdol_data_tlv_data);
945 //free(pdol_data_tlv); --- free on exit.
947 if (res) {
948 PrintAndLogEx(ERR, "GPO error(%d): %4x. Exit...", res, sw);
949 dreturn(PM3_ERFTRANS);
952 // process response template format 1 [id:80 2b AIP + x4b AFL] and format 2 [id:77 TLV]
953 ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV);
955 // extract PAN from track2
957 const struct tlv *track2 = tlvdb_get(tlvRoot, 0x57, NULL);
958 if (!tlvdb_get(tlvRoot, 0x5a, NULL) && track2 && track2->len >= 8) {
959 struct tlvdb *pan = GetPANFromTrack2(track2);
960 if (pan) {
961 tlvdb_add(tlvRoot, pan);
963 const struct tlv *pantlv = tlvdb_get(tlvRoot, 0x5a, NULL);
964 PrintAndLogEx(NORMAL, "\n* * Extracted PAN from track2: %s", sprint_hex(pantlv->value, pantlv->len));
965 } else {
966 PrintAndLogEx(WARNING, "\n* * WARNING: Can't extract PAN from track2.");
971 PrintAndLogEx(NORMAL, "\n* Read records from AFL.");
972 const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL);
974 if (!AFL || !AFL->len)
975 PrintAndLogEx(WARNING, "WARNING: AFL not found.");
977 while (AFL && AFL->len) {
978 if (AFL->len % 4) {
979 PrintAndLogEx(WARNING, "Warning: Wrong AFL length: %zu", AFL->len);
980 break;
983 for (int i = 0; i < AFL->len / 4; i++) {
984 uint8_t SFI = AFL->value[i * 4 + 0] >> 3;
985 uint8_t SFIstart = AFL->value[i * 4 + 1];
986 uint8_t SFIend = AFL->value[i * 4 + 2];
987 uint8_t SFIoffline = AFL->value[i * 4 + 3];
989 PrintAndLogEx(NORMAL, "* * SFI[%02x] start:%02x end:%02x offline count:%02x", SFI, SFIstart, SFIend, SFIoffline);
990 if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) {
991 PrintAndLogEx(NORMAL, "SFI ERROR! Skipped...");
992 continue;
995 for (int n = SFIstart; n <= SFIend; n++) {
996 PrintAndLogEx(NORMAL, "* * * SFI[%02x] %d", SFI, n);
998 res = EMVReadRecord(channel, true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot);
999 if (res) {
1000 PrintAndLogEx(WARNING, "Error SFI[%02x]. APDU error %4x", SFI, sw);
1001 continue;
1004 if (decodeTLV) {
1005 TLVPrintFromBuffer(buf, len);
1006 PrintAndLogEx(NORMAL, "");
1009 // Build Input list for Offline Data Authentication
1010 // EMV 4.3 book3 10.3, page 96
1011 if (SFIoffline > 0) {
1012 if (SFI < 11) {
1013 const unsigned char *abuf = buf;
1014 size_t elmlen = len;
1015 struct tlv e;
1016 if (tlv_parse_tl(&abuf, &elmlen, &e)) {
1017 memcpy(&ODAiList[ODAiListLen], &buf[len - elmlen], elmlen);
1018 ODAiListLen += elmlen;
1019 } else {
1020 PrintAndLogEx(WARNING, "Error SFI[%02x]. Creating input list for Offline Data Authentication error.", SFI);
1022 } else {
1023 memcpy(&ODAiList[ODAiListLen], buf, len);
1024 ODAiListLen += len;
1027 SFIoffline--;
1032 break;
1035 // copy Input list for Offline Data Authentication
1036 if (ODAiListLen) {
1037 struct tlvdb *oda = tlvdb_fixed(0x21, ODAiListLen, ODAiList); // not a standard tag
1038 tlvdb_add(tlvRoot, oda);
1039 PrintAndLogEx(NORMAL, "* Input list for Offline Data Authentication added to TLV. len=%zu \n", ODAiListLen);
1042 // get AIP
1043 uint16_t AIP = 0;
1044 const struct tlv *AIPtlv = tlvdb_get(tlvRoot, 0x82, NULL);
1045 if (AIPtlv) {
1046 AIP = AIPtlv->value[0] + AIPtlv->value[1] * 0x100;
1047 PrintAndLogEx(NORMAL, "* * AIP=%04x", AIP);
1048 } else {
1049 PrintAndLogEx(ERR, "Can't find AIP.");
1052 // SDA
1053 if (AIP & 0x0040) {
1054 PrintAndLogEx(NORMAL, "\n* SDA");
1055 trSDA(tlvRoot);
1058 // DDA
1059 if (AIP & 0x0020) {
1060 PrintAndLogEx(NORMAL, "\n* DDA");
1061 trDDA(channel, decodeTLV, tlvRoot);
1064 // transaction check
1066 // qVSDC
1067 if (TrType == TT_QVSDCMCHIP || TrType == TT_CDA) {
1068 // 9F26: Application Cryptogram
1069 const struct tlv *AC = tlvdb_get(tlvRoot, 0x9F26, NULL);
1070 if (AC) {
1071 PrintAndLogEx(NORMAL, "\n--> qVSDC transaction.");
1072 PrintAndLogEx(NORMAL, "* AC path");
1074 // 9F36: Application Transaction Counter (ATC)
1075 const struct tlv *ATC = tlvdb_get(tlvRoot, 0x9F36, NULL);
1076 if (ATC) {
1078 // 9F10: Issuer Application Data - optional
1079 const struct tlv *IAD = tlvdb_get(tlvRoot, 0x9F10, NULL);
1081 // print AC data
1082 PrintAndLogEx(NORMAL, "ATC: %s", sprint_hex(ATC->value, ATC->len));
1083 PrintAndLogEx(NORMAL, "AC: %s", sprint_hex(AC->value, AC->len));
1084 if (IAD) {
1085 PrintAndLogEx(NORMAL, "IAD: %s", sprint_hex(IAD->value, IAD->len));
1087 // https://mst-company.ru/blog/ekvajring-emv-tranzaktsiya-emv-transaction-flow-chast-4-pdol-i-beskontaktnye-karty-osobennosti-qvsdc-i-quics
1088 if (IAD->value[0] == 0x1f) {
1089 PrintAndLogEx(NORMAL, " Key index: 0x%02x", IAD->value[2]);
1090 PrintAndLogEx(NORMAL, " Crypto ver: 0x%02x(%03d)", IAD->value[1], IAD->value[1]);
1091 PrintAndLogEx(NORMAL, " CVR: %s", sprint_hex(&IAD->value[3], 5));
1092 struct tlvdb *cvr = tlvdb_fixed(0x20, 5, &IAD->value[3]);
1093 TLVPrintFromTLVLev(cvr, 1);
1094 PrintAndLogEx(NORMAL, " IDD option id: 0x%02x", IAD->value[8]);
1095 PrintAndLogEx(NORMAL, " IDD: %s", sprint_hex(&IAD->value[9], 23));
1096 } else if (IAD->len >= IAD->value[0] + 1) {
1097 PrintAndLogEx(NORMAL, " Key index: 0x%02x", IAD->value[1]);
1098 PrintAndLogEx(NORMAL, " Crypto ver: 0x%02x(%03d)", IAD->value[2], IAD->value[2]);
1099 PrintAndLogEx(NORMAL, " CVR: %s", sprint_hex(&IAD->value[3], IAD->value[0] - 2));
1100 struct tlvdb *cvr = tlvdb_fixed(0x20, IAD->value[0] - 2, &IAD->value[3]);
1101 TLVPrintFromTLVLev(cvr, 1);
1102 if (IAD->len >= 8) {
1103 int iddLen = IAD->value[7];
1104 PrintAndLogEx(NORMAL, " IDD length: %d", iddLen);
1105 if (iddLen >= 1)
1106 PrintAndLogEx(NORMAL, " IDD option id: 0x%02x", IAD->value[8]);
1107 if (iddLen >= 2)
1108 PrintAndLogEx(NORMAL, " IDD: %s", sprint_hex(&IAD->value[9], iddLen - 1));
1111 } else {
1112 PrintAndLogEx(WARNING, "WARNING: IAD not found.");
1115 } else {
1116 PrintAndLogEx(WARNING, "Warning AC: Application Transaction Counter (ATC) not found.");
1121 // Mastercard M/CHIP
1122 if (GetCardPSVendor(AID, AIDlen) == CV_MASTERCARD && (TrType == TT_QVSDCMCHIP || TrType == TT_CDA)) {
1123 const struct tlv *CDOL1 = tlvdb_get(tlvRoot, 0x8c, NULL);
1124 if (CDOL1 && GetCardPSVendor(AID, AIDlen) == CV_MASTERCARD) { // and m/chip transaction flag
1125 PrintAndLogEx(NORMAL, "\n--> Mastercard M/Chip transaction.");
1127 PrintAndLogEx(NORMAL, "* * Generate challenge");
1128 res = EMVGenerateChallenge(channel, true, buf, sizeof(buf), &len, &sw, tlvRoot);
1129 if (res) {
1130 PrintAndLogEx(ERR, "Error GetChallenge. APDU error %4x", sw);
1131 dreturn(PM3_ERFTRANS);
1133 if (len < 4) {
1134 PrintAndLogEx(ERR, "Error GetChallenge. Wrong challenge length %zu", len);
1135 dreturn(PM3_ESOFT);
1138 // ICC Dynamic Number
1139 struct tlvdb *ICCDynN = tlvdb_fixed(0x9f4c, len, buf);
1140 tlvdb_add(tlvRoot, ICCDynN);
1141 if (decodeTLV) {
1142 PrintAndLogEx(NORMAL, "\n* * ICC Dynamic Number:");
1143 TLVPrintFromTLV(ICCDynN);
1146 PrintAndLogEx(NORMAL, "* * Calc CDOL1");
1147 struct tlv *cdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x8c, NULL), tlvRoot, 0x01); // 0x01 - dummy tag
1148 if (!cdol_data_tlv) {
1149 PrintAndLogEx(ERR, "Error: can't create CDOL1 TLV.");
1150 dreturn(PM3_ESOFT);
1153 PrintAndLogEx(NORMAL, "CDOL1 data[%zu]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len));
1155 PrintAndLogEx(NORMAL, "* * AC1");
1156 // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD
1157 res = EMVAC(channel, true, (TrType == TT_CDA) ? EMVAC_TC + EMVAC_CDAREQ : EMVAC_TC, (uint8_t *)cdol_data_tlv->value, cdol_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot);
1159 if (res) {
1160 PrintAndLogEx(ERR, "AC1 error(%d): %4x. Exit...", res, sw);
1161 dreturn(PM3_ERFTRANS);
1164 if (decodeTLV)
1165 TLVPrintFromBuffer(buf, len);
1167 // CDA
1168 PrintAndLogEx(NORMAL, "\n* CDA:");
1169 struct tlvdb *ac_tlv = tlvdb_parse_multi(buf, len);
1170 if (tlvdb_get(ac_tlv, 0x9f4b, NULL)) {
1171 res = trCDA(tlvRoot, ac_tlv, pdol_data_tlv, cdol_data_tlv);
1172 if (res) {
1173 PrintAndLogEx(NORMAL, "CDA error (%d)", res);
1175 } else {
1176 PrintAndLogEx(NORMAL, "\n* Signed Dynamic Application Data (0x9f4b) not present");
1179 free(ac_tlv);
1180 free(cdol_data_tlv);
1182 PrintAndLogEx(NORMAL, "\n* M/Chip transaction result:");
1183 // 9F27: Cryptogram Information Data (CID)
1184 const struct tlv *CID = tlvdb_get(tlvRoot, 0x9F27, NULL);
1185 if (CID) {
1186 emv_tag_dump(CID, 1);
1187 PrintAndLogEx(NORMAL, "------------------------------");
1188 if (CID->len > 0) {
1189 switch (CID->value[0] & EMVAC_AC_MASK) {
1190 case EMVAC_AAC:
1191 PrintAndLogEx(NORMAL, "Transaction DECLINED.");
1192 break;
1193 case EMVAC_TC:
1194 PrintAndLogEx(NORMAL, "Transaction approved OFFLINE.");
1195 break;
1196 case EMVAC_ARQC:
1197 PrintAndLogEx(NORMAL, "Transaction approved ONLINE.");
1198 break;
1199 default:
1200 PrintAndLogEx(WARNING, "Warning: CID transaction code error %2x", CID->value[0] & EMVAC_AC_MASK);
1201 break;
1203 } else {
1204 PrintAndLogEx(WARNING, "Warning: Wrong CID length %zu", CID->len);
1206 } else {
1207 PrintAndLogEx(WARNING, "Warning: CID(9F27) not found.");
1213 // MSD
1214 if (AIP & 0x8000 && TrType == TT_MSD) {
1215 PrintAndLogEx(NORMAL, "\n--> MSD transaction.");
1217 PrintAndLogEx(NORMAL, "* MSD dCVV path. Check dCVV");
1219 const struct tlv *track2 = tlvdb_get(tlvRoot, 0x57, NULL);
1220 if (track2) {
1221 PrintAndLogEx(NORMAL, "Track2: %s", sprint_hex(track2->value, track2->len));
1223 struct tlvdb *dCVV = GetdCVVRawFromTrack2(track2);
1224 PrintAndLogEx(NORMAL, "dCVV raw data:");
1225 TLVPrintFromTLV(dCVV);
1227 if (GetCardPSVendor(AID, AIDlen) == CV_MASTERCARD) {
1228 PrintAndLogEx(NORMAL, "\n* Mastercard calculate UDOL");
1230 // UDOL (9F69)
1231 const struct tlv *UDOL = tlvdb_get(tlvRoot, 0x9F69, NULL);
1232 // UDOL(9F69) default: 9F6A (Unpredictable number) 4 bytes
1233 const struct tlv defUDOL = {
1234 .tag = 0x01,
1235 .len = 3,
1236 .value = (uint8_t *)"\x9f\x6a\x04",
1238 if (!UDOL)
1239 PrintAndLogEx(NORMAL, "Use default UDOL.");
1241 struct tlv *udol_data_tlv = dol_process(UDOL ? UDOL : &defUDOL, tlvRoot, 0x01); // 0x01 - dummy tag
1242 if (!udol_data_tlv) {
1243 PrintAndLogEx(ERR, "Error: can't create UDOL TLV.");
1244 dreturn(PM3_ESOFT);
1247 PrintAndLogEx(NORMAL, "UDOL data[%zu]: %s", udol_data_tlv->len, sprint_hex(udol_data_tlv->value, udol_data_tlv->len));
1249 PrintAndLogEx(NORMAL, "\n* Mastercard compute cryptographic checksum(UDOL)");
1251 res = MSCComputeCryptoChecksum(channel, true, (uint8_t *)udol_data_tlv->value, udol_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot);
1252 if (res) {
1253 PrintAndLogEx(ERR, "Error Compute Crypto Checksum. APDU error %4x", sw);
1254 free(udol_data_tlv);
1255 dreturn(PM3_ESOFT);
1258 // Mastercard compute cryptographic checksum result
1259 TLVPrintFromBuffer(buf, len);
1260 PrintAndLogEx(NORMAL, "");
1262 free(udol_data_tlv);
1265 } else {
1266 PrintAndLogEx(ERR, "Error MSD: Track2 data not found.");
1270 // VSDC
1271 if (GetCardPSVendor(AID, AIDlen) == CV_VISA && (TrType == TT_VSDC || TrType == TT_CDA)) {
1272 PrintAndLogEx(NORMAL, "\n--> VSDC transaction.");
1274 PrintAndLogEx(NORMAL, "* * Calc CDOL1");
1275 struct tlv *cdol1_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x8c, NULL), tlvRoot, 0x01); // 0x01 - dummy tag
1276 if (!cdol1_data_tlv) {
1277 PrintAndLogEx(ERR, "Error: can't create CDOL1 TLV.");
1278 dreturn(PM3_ESOFT);
1281 PrintAndLogEx(NORMAL, "CDOL1 data[%zu]: %s", cdol1_data_tlv->len, sprint_hex(cdol1_data_tlv->value, cdol1_data_tlv->len));
1283 PrintAndLogEx(NORMAL, "* * AC1");
1284 // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD
1285 res = EMVAC(channel, true, (TrType == TT_CDA) ? EMVAC_TC + EMVAC_CDAREQ : EMVAC_TC, (uint8_t *)cdol1_data_tlv->value, cdol1_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot);
1286 if (res) {
1287 PrintAndLogEx(ERR, "AC1 error(%d): %4x. Exit...", res, sw);
1288 free(cdol1_data_tlv);
1289 dreturn(PM3_ERFTRANS);
1292 // process Format1 (0x80) and print Format2 (0x77)
1293 ProcessACResponseFormat1(tlvRoot, buf, len, decodeTLV);
1295 uint8_t CID = 0;
1296 tlvdb_get_uint8(tlvRoot, 0x9f27, &CID);
1298 // AC1 print result
1299 PrintAndLogEx(NORMAL, "");
1300 if ((CID & EMVAC_AC_MASK) == EMVAC_AAC) PrintAndLogEx(INFO, "AC1 result: AAC (Transaction declined)");
1301 if ((CID & EMVAC_AC_MASK) == EMVAC_TC) PrintAndLogEx(INFO, "AC1 result: TC (Transaction approved)");
1302 if ((CID & EMVAC_AC_MASK) == EMVAC_ARQC) PrintAndLogEx(INFO, "AC1 result: ARQC (Online authorisation requested)");
1303 if ((CID & EMVAC_AC_MASK) == EMVAC_AC_MASK) PrintAndLogEx(INFO, "AC1 result: RFU");
1305 // decode Issuer Application Data (IAD)
1306 uint8_t CryptoVersion = 0;
1307 const struct tlv *IAD = tlvdb_get(tlvRoot, 0x9f10, NULL);
1308 if (IAD && (IAD->len > 1)) {
1309 PrintAndLogEx(NORMAL, "\n* * Issuer Application Data (IAD):");
1310 uint8_t VDDlen = IAD->value[0]; // Visa discretionary data length
1311 uint8_t IDDlen = 0; // Issuer discretionary data length
1312 PrintAndLogEx(NORMAL, "IAD length: %zu", IAD->len);
1313 PrintAndLogEx(NORMAL, "VDDlen: %d", VDDlen);
1314 if (VDDlen < IAD->len - 1) {
1315 IDDlen = IAD->value[VDDlen + 1];
1317 PrintAndLogEx(NORMAL, "IDDlen: %d", IDDlen);
1319 uint8_t DerivKeyIndex = IAD->value[1];
1320 CryptoVersion = IAD->value[2];
1322 PrintAndLogEx(NORMAL, "CryptoVersion: %d", CryptoVersion);
1323 PrintAndLogEx(NORMAL, "DerivKeyIndex: %d", DerivKeyIndex);
1325 // Card Verification Results (CVR) decode
1326 if ((VDDlen - 2) > 0) {
1327 uint8_t CVRlen = IAD->value[3];
1328 if (CVRlen == (VDDlen - 2 - 1)) {
1329 PrintAndLogEx(NORMAL, "CVR length: %d", CVRlen);
1330 PrintAndLogEx(NORMAL, "CVR: %s", sprint_hex(&IAD->value[4], CVRlen));
1331 } else {
1332 PrintAndLogEx(WARNING, "Wrong CVR length! CVR: %s", sprint_hex(&IAD->value[3], VDDlen - 2));
1335 if (IDDlen) {
1336 PrintAndLogEx(NORMAL, "IDD: %s", sprint_hex(&IAD->value[VDDlen + 1], IDDlen));
1338 } else {
1339 PrintAndLogEx(WARNING, "Issuer Application Data (IAD) not found.");
1342 PrintAndLogEx(NORMAL, "\n* * Processing online request");
1344 // authorization response code from acquirer
1345 const char HostResponse[] = "00"; // 0x3030
1346 size_t HostResponseLen = sizeof(HostResponse) - 1;
1348 PrintAndLogEx(NORMAL, "Host Response: `%s`", HostResponse);
1350 tlvdb_change_or_add_node(tlvRoot, 0x8a, HostResponseLen, (const unsigned char *)HostResponse);
1352 if (CryptoVersion == 10) {
1353 PrintAndLogEx(NORMAL, "\n* * Generate ARPC");
1355 // Application Cryptogram (AC)
1356 const struct tlv *AC = tlvdb_get(tlvRoot, 0x9f26, NULL);
1357 if (AC && (AC->len > 0)) {
1358 PrintAndLogEx(NORMAL, "AC: %s", sprint_hex(AC->value, AC->len));
1360 size_t rawARPClen = AC->len;
1361 uint8_t rawARPC[rawARPClen];
1362 memcpy(rawARPC, AC->value, AC->len);
1363 for (int i = 0; (i < HostResponseLen) && (i < rawARPClen); i++) {
1364 rawARPC[i] ^= HostResponse[i];
1366 PrintAndLogEx(NORMAL, "raw ARPC: %s", sprint_hex(rawARPC, rawARPClen));
1368 // here must be calculation of ARPC, but we dont know a bank keys.
1369 PrintAndLogEx(NORMAL, "ARPC: n/a");
1371 } else {
1372 PrintAndLogEx(WARNING, "Application Cryptogram (AC) not found.");
1374 // here must be external authenticate, but we dont know ARPC
1377 // needs to send AC2 command (res == ARQC)
1378 if ((CID & EMVAC_AC_MASK) == EMVAC_ARQC) {
1379 PrintAndLogEx(NORMAL, "\n* * Calc CDOL2");
1380 struct tlv *cdol2_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x8d, NULL), tlvRoot, 0x01); // 0x01 - dummy tag
1381 if (!cdol2_data_tlv) {
1382 PrintAndLogEx(ERR, "Error: can't create CDOL2 TLV.");
1383 free(cdol1_data_tlv);
1384 dreturn(PM3_ESOFT);
1387 PrintAndLogEx(NORMAL, "CDOL2 data[%zu]: %s", cdol2_data_tlv->len, sprint_hex(cdol2_data_tlv->value, cdol2_data_tlv->len));
1388 //PrintAndLogEx(NORMAL, "* * AC2");
1389 // here must be AC2, but we dont make external authenticate (
1390 /* // AC2
1391 PRINT_INDENT(level);
1392 if ((CID & EMVAC_AC2_MASK) == EMVAC_AAC2) PrintAndLogEx(NORMAL, "\tAC2: AAC (Transaction declined)");
1393 if ((CID & EMVAC_AC2_MASK) == EMVAC_TC2) PrintAndLogEx(NORMAL, "\tAC2: TC (Transaction approved)");
1394 if ((CID & EMVAC_AC2_MASK) == EMVAC_ARQC2) PrintAndLogEx(NORMAL, "\tAC2: not requested (ARQC)");
1395 if ((CID & EMVAC_AC2_MASK) == EMVAC_AC2_MASK) PrintAndLogEx(NORMAL, "\tAC2: RFU");
1397 free(cdol2_data_tlv);
1399 free(cdol1_data_tlv);
1402 DropFieldEx(channel);
1404 // Destroy TLV's
1405 free(pdol_data_tlv);
1407 tlvdb_free(tlvSelect);
1408 tlvdb_free(tlvRoot);
1410 PrintAndLogEx(NORMAL, "\n* Transaction completed.");
1411 return PM3_SUCCESS;
1414 static int CmdEMVScan(const char *Cmd) {
1415 uint8_t AID[APDU_AID_LEN] = {0};
1416 size_t AIDlen = 0;
1417 uint8_t buf[APDU_RES_LEN] = {0};
1418 size_t len = 0;
1419 uint8_t ODAI_list[4096];
1420 size_t ODAI_listlen = 0;
1421 uint16_t sw = 0;
1422 int res;
1424 CLIParserContext *ctx;
1425 CLIParserInit(&ctx, "emv scan",
1426 "Scan EMV card and save it contents to a file.\n"
1427 "It executes EMV contactless transaction and saves result to a file which can be used for emulation\n",
1428 "emv scan -at -> scan MSD transaction mode and show APDU and TLV\n"
1429 "emv scan -c -> scan CDA transaction mode\n"
1432 void *argtable[] = {
1433 arg_param_begin,
1434 arg_lit0("aA", "apdu", "show APDU reqests and responses."),
1435 arg_lit0("tT", "tlv", "TLV decode results."),
1436 arg_lit0("eE", "extract", "Extract TLV elements and fill Application Data"),
1437 arg_lit0("jJ", "jload", "Load transaction parameters from `emv_defparams.json` file."),
1438 arg_rem("By default:", "Transaction type - MSD"),
1439 arg_lit0("vV", "qvsdc", "Transaction type - qVSDC or M/Chip."),
1440 arg_lit0("cC", "qvsdccda", "Transaction type - qVSDC or M/Chip plus CDA (SDAD generation)."),
1441 arg_lit0("xX", "vsdc", "Transaction type - VSDC. For test only. Not a standard behavior."),
1442 arg_lit0("gG", "acgpo", "VISA. generate AC from GPO."),
1443 arg_lit0("mM", "merge", "Merge output file with card's data. (warning: the file may be corrupted!)"),
1444 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default."),
1445 arg_str1(NULL, NULL, "output.json", "JSON output file name"),
1446 arg_param_end
1448 CLIExecWithReturn(ctx, Cmd, argtable, true);
1450 bool showAPDU = arg_get_lit(ctx, 1);
1451 bool decodeTLV = arg_get_lit(ctx, 2);
1452 bool extractTLVElements = arg_get_lit(ctx, 3);
1453 bool paramLoadJSON = arg_get_lit(ctx, 4);
1455 enum TransactionType TrType = TT_MSD;
1456 if (arg_get_lit(ctx, 6))
1457 TrType = TT_QVSDCMCHIP;
1458 if (arg_get_lit(ctx, 7))
1459 TrType = TT_CDA;
1460 if (arg_get_lit(ctx, 8))
1461 TrType = TT_VSDC;
1463 bool GenACGPO = arg_get_lit(ctx, 9);
1464 bool MergeJSON = arg_get_lit(ctx, 10);
1466 Iso7816CommandChannel channel = CC_CONTACTLESS;
1467 if (arg_get_lit(ctx, 11))
1468 channel = CC_CONTACT;
1470 PrintChannel(channel);
1472 uint8_t psenum = (channel == CC_CONTACT) ? 1 : 2;
1474 uint8_t filename[FILE_PATH_SIZE] = {0};
1475 int filenamelen = sizeof(filename);
1476 CLIGetStrWithReturn(ctx, 12, filename, &filenamelen);
1478 CLIParserFree(ctx);
1480 if (!IfPm3Smartcard()) {
1481 if (channel == CC_CONTACT) {
1482 PrintAndLogEx(WARNING, "PM3 does not have SMARTCARD support, exiting");
1483 return PM3_EDEVNOTSUPP;
1487 SetAPDULogging(showAPDU);
1489 json_t *root;
1490 json_error_t error;
1492 // current path + file name
1493 if (MergeJSON) {
1495 root = json_load_file((char *)filename, 0, &error);
1496 if (!root) {
1497 PrintAndLogEx(ERR, "Json error on line %d: %s", error.line, error.text);
1498 return PM3_EFILE;
1501 if (!json_is_object(root)) {
1502 PrintAndLogEx(ERR, "Invalid json format. root must be an object");
1503 return PM3_EFILE;
1505 } else {
1506 root = json_object();
1509 // drop field at start
1510 DropFieldEx(channel);
1512 JsonSaveStr(root, "$.File.Created", "proxmark3 `emv scan`");
1514 if (channel == CC_CONTACTLESS) {
1515 // iso 14443 select
1516 PrintAndLogEx(INFO, "GET UID, ATS");
1518 iso14a_card_select_t card;
1519 if (Hf14443_4aGetCardData(&card)) {
1520 return PM3_ERFTRANS;
1523 JsonSaveStr(root, "$.Card.Contactless.Communication", "iso14443-4a");
1524 JsonSaveBufAsHex(root, "$.Card.Contactless.UID", (uint8_t *)&card.uid, card.uidlen);
1525 JsonSaveHex(root, "$.Card.Contactless.ATQA", card.atqa[0] + (card.atqa[1] << 2), 2);
1526 JsonSaveHex(root, "$.Card.Contactless.SAK", card.sak, 0);
1527 JsonSaveBufAsHex(root, "$.Card.Contactless.ATS", (uint8_t *)card.ats, card.ats_len);
1528 } else {
1529 PrintAndLogEx(INFO, "GET ATR");
1531 smart_card_atr_t card;
1532 smart_select(true, &card);
1533 if (!card.atr_len) {
1534 PrintAndLogEx(ERR, "Can't get ATR from a smart card.");
1535 return PM3_ERFTRANS;
1538 JsonSaveStr(root, "$.Card.Contact.Communication", "iso7816");
1539 JsonSaveBufAsHex(root, "$.Card.Contact.ATR", (uint8_t *)card.atr, card.atr_len);
1542 // init applets list tree
1543 const char *al = "Applets list";
1544 struct tlvdb *tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al);
1546 // EMV PPSE
1547 PrintAndLogEx(INFO, "PPSE");
1548 res = EMVSelectPSE(channel, true, true, 2, buf, sizeof(buf), &len, &sw);
1550 if (!res && sw == 0x9000) {
1551 if (decodeTLV)
1552 TLVPrintFromBuffer(buf, len);
1554 JsonSaveBufAsHex(root, "$.PPSE.AID", (uint8_t *)"2PAY.SYS.DDF01", 14);
1556 struct tlvdb *fci = tlvdb_parse_multi(buf, len);
1557 if (extractTLVElements)
1558 JsonSaveTLVTree(root, root, "$.PPSE.FCITemplate", fci);
1559 else
1560 JsonSaveTLVTreeElm(root, "$.PPSE.FCITemplate", fci, true, true, false);
1561 JsonSaveTLVValue(root, "$.Application.KernelID", tlvdb_find_full(fci, 0x9f2a));
1562 tlvdb_free(fci);
1565 res = EMVSearchPSE(channel, false, true, psenum, decodeTLV, tlvSelect);
1567 // check PPSE and select application id
1568 if (!res) {
1569 TLVPrintAIDlistFromSelectTLV(tlvSelect);
1570 } else {
1571 // EMV SEARCH with AID list
1572 SetAPDULogging(false);
1573 PrintAndLogEx(INFO, "AID search.");
1574 if (EMVSearch(channel, false, true, decodeTLV, tlvSelect)) {
1575 PrintAndLogEx(ERR, "Can't found any of EMV AID, exiting...");
1576 tlvdb_free(tlvSelect);
1577 DropFieldEx(channel);
1578 return PM3_ERFTRANS;
1581 // check search and select application id
1582 TLVPrintAIDlistFromSelectTLV(tlvSelect);
1585 // EMV SELECT application
1586 SetAPDULogging(showAPDU);
1587 EMVSelectApplication(tlvSelect, AID, &AIDlen);
1589 tlvdb_free(tlvSelect);
1591 if (!AIDlen) {
1592 PrintAndLogEx(INFO, "Can't select AID. EMV AID not found, exiting...");
1593 DropFieldEx(channel);
1594 return PM3_ERFTRANS;
1597 JsonSaveBufAsHex(root, "$.Application.AID", AID, AIDlen);
1599 // Init TLV tree
1600 const char *alr = "Root terminal TLV tree";
1601 struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
1603 // EMV SELECT applet
1605 PrintAndLogEx(INFO, "Selecting AID: " _GREEN_("%s"), sprint_hex_inrow(AID, AIDlen));
1606 SetAPDULogging(showAPDU);
1607 res = EMVSelect(channel, false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot);
1609 if (res) {
1610 PrintAndLogEx(ERR, "Can't select AID (%d), exiting...", res);
1611 tlvdb_free(tlvRoot);
1612 DropFieldEx(channel);
1613 return PM3_ERFTRANS;
1616 if (decodeTLV)
1617 TLVPrintFromBuffer(buf, len);
1619 // save mode
1620 if (tlvdb_get(tlvRoot, 0x9f38, NULL)) {
1621 JsonSaveStr(root, "$.Application.Mode", TransactionTypeStr[TrType]);
1624 struct tlvdb *fci = tlvdb_parse_multi(buf, len);
1625 if (extractTLVElements)
1626 JsonSaveTLVTree(root, root, "$.Application.FCITemplate", fci);
1627 else
1628 JsonSaveTLVTreeElm(root, "$.Application.FCITemplate", fci, true, true, false);
1630 tlvdb_free(fci);
1632 // create transaction parameters
1633 PrintAndLogEx(INFO, "Init transaction parameters");
1634 InitTransactionParameters(tlvRoot, paramLoadJSON, TrType, GenACGPO);
1636 PrintAndLogEx(INFO, "Calc PDOL");
1637 struct tlv *pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83);
1638 if (!pdol_data_tlv) {
1639 PrintAndLogEx(ERR, "Can't create PDOL TLV");
1640 tlvdb_free(tlvRoot);
1641 DropFieldEx(channel);
1642 return PM3_ESOFT;
1645 size_t pdol_data_tlv_data_len;
1646 unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len);
1647 if (!pdol_data_tlv_data) {
1648 PrintAndLogEx(ERR, "Can't create PDOL data");
1649 tlvdb_free(tlvRoot);
1650 free(pdol_data_tlv);
1651 DropFieldEx(channel);
1652 return PM3_ESOFT;
1654 PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
1656 PrintAndLogEx(INFO, "GPO");
1657 res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
1659 free(pdol_data_tlv_data);
1660 free(pdol_data_tlv);
1662 if (res) {
1663 PrintAndLogEx(ERR, "GPO error(%d): %4x, exiting...", res, sw);
1664 tlvdb_free(tlvRoot);
1665 DropFieldEx(channel);
1666 return PM3_ERFTRANS;
1668 ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV);
1670 struct tlvdb *gpofci = tlvdb_parse_multi(buf, len);
1671 if (extractTLVElements)
1672 JsonSaveTLVTree(root, root, "$.Application.GPO", gpofci);
1673 else
1674 JsonSaveTLVTreeElm(root, "$.Application.GPO", gpofci, true, true, false);
1676 JsonSaveTLVValue(root, "$.ApplicationData.AIP", tlvdb_find_full(gpofci, 0x82));
1677 JsonSaveTLVValue(root, "$.ApplicationData.AFL", tlvdb_find_full(gpofci, 0x94));
1679 tlvdb_free(gpofci);
1681 PrintAndLogEx(INFO, "Read records from AFL");
1682 const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL);
1684 while (AFL && AFL->len) {
1685 if (AFL->len % 4) {
1686 PrintAndLogEx(ERR, "Wrong AFL length: %zu", AFL->len);
1687 break;
1690 json_t *sfijson = json_path_get(root, "$.Application.Records");
1691 if (!sfijson) {
1692 json_t *app = json_path_get(root, "$.Application");
1693 json_object_set_new(app, "Records", json_array());
1695 sfijson = json_path_get(root, "$.Application.Records");
1697 if (!json_is_array(sfijson)) {
1698 PrintAndLogEx(ERR, "Internal logic error. `$.Application.Records` is not an array.");
1699 break;
1701 for (int i = 0; i < AFL->len / 4; i++) {
1702 uint8_t SFI = AFL->value[i * 4 + 0] >> 3;
1703 uint8_t SFIstart = AFL->value[i * 4 + 1];
1704 uint8_t SFIend = AFL->value[i * 4 + 2];
1705 uint8_t SFIoffline = AFL->value[i * 4 + 3];
1706 bool first_time = SFIoffline;
1708 PrintAndLogEx(INFO, " SFI[%02x] start:%02x end:%02x offline:%02x", SFI, SFIstart, SFIend, SFIoffline);
1709 if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) {
1710 PrintAndLogEx(ERR, "SFI ERROR! Skipped...");
1711 continue;
1714 for (int n = SFIstart; n <= SFIend; n++) {
1715 PrintAndLogEx(INFO, " SFI[%02x] %d", SFI, n);
1717 res = EMVReadRecord(channel, true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot);
1718 if (res) {
1719 PrintAndLogEx(ERR, "SFI[%02x]. APDU error %4x", SFI, sw);
1720 continue;
1723 // Build Input list for Offline Data Authentication
1724 // EMV 4.3 book3 10.3, page 96
1725 if (first_time && SFIoffline) {
1726 if (SFI < 11) {
1727 const unsigned char *abuf = buf;
1728 size_t elmlen = len;
1729 struct tlv e;
1730 if (tlv_parse_tl(&abuf, &elmlen, &e)) {
1731 memcpy(ODAI_list + ODAI_listlen, &buf[len - elmlen], elmlen);
1732 ODAI_listlen += elmlen;
1733 } else {
1734 PrintAndLogEx(WARNING, "Error SFI[%02x]. Creating input list for Offline Data Authentication error", SFI);
1736 } else {
1737 memcpy(ODAI_list + ODAI_listlen, buf, len);
1738 ODAI_listlen += len;
1740 first_time = false;
1743 if (decodeTLV) {
1744 TLVPrintFromBuffer(buf, len);
1745 PrintAndLogEx(NORMAL, "");
1748 json_t *jsonelm = json_object();
1749 json_array_append_new(sfijson, jsonelm);
1751 JsonSaveHex(jsonelm, "SFI", SFI, 1);
1752 JsonSaveHex(jsonelm, "RecordNum", n, 1);
1753 JsonSaveHex(jsonelm, "Offline", SFIoffline, 1);
1755 struct tlvdb *rsfi = tlvdb_parse_multi(buf, len);
1756 if (extractTLVElements)
1757 JsonSaveTLVTree(root, jsonelm, "$.Data", rsfi);
1758 else
1759 JsonSaveTLVTreeElm(jsonelm, "$.Data", rsfi, true, true, false);
1761 tlvdb_free(rsfi);
1764 break;
1767 // copy Input list for Offline Data Authentication
1768 if (ODAI_listlen) {
1769 struct tlvdb *oda = tlvdb_fixed(0x21, ODAI_listlen, ODAI_list); // not a standard tag
1770 tlvdb_add(tlvRoot, oda);
1771 PrintAndLogEx(INFO, "Input list for Offline Data Authentication added to TLV [%zu bytes]", ODAI_listlen);
1774 // getting certificates
1775 if (tlvdb_get(tlvRoot, 0x90, NULL)) {
1776 PrintAndLogEx(INFO, "Recovering certificates");
1777 PKISetStrictExecution(false);
1778 RecoveryCertificates(tlvRoot, root);
1779 PKISetStrictExecution(true);
1782 // free tlv object
1783 tlvdb_free(tlvRoot);
1785 DropFieldEx(channel);
1788 if (MergeJSON == false) {
1789 // create unique new name
1790 char *fname = newfilenamemcopy((char *)filename, ".json");
1791 if (fname == NULL) {
1792 return PM3_EMALLOC;
1794 strcpy((char *)filename, fname);
1795 free(fname);
1798 res = json_dump_file(root, (char *)filename, JSON_INDENT(2));
1799 if (res) {
1800 PrintAndLogEx(ERR, "Can't save the file: %s", filename);
1801 return PM3_EFILE;
1804 PrintAndLogEx(SUCCESS, "File " _YELLOW_("`%s`") " saved.", filename);
1806 // free json object
1807 json_decref(root);
1808 return PM3_SUCCESS;
1811 static int CmdEMVList(const char *Cmd) {
1812 return CmdTraceListAlias(Cmd, "emv", "7816");
1815 static int CmdEMVTest(const char *Cmd) {
1816 CLIParserContext *ctx;
1817 CLIParserInit(&ctx, "emv test",
1818 "Executes tests\n",
1819 "emv test -i\n"
1820 "emv test --long"
1823 void *argtable[] = {
1824 arg_param_begin,
1825 arg_lit0("i", "ignore", "ignore timing tests for VM"),
1826 arg_lit0("l", "long", "run long tests too"),
1827 arg_param_end
1829 CLIExecWithReturn(ctx, Cmd, argtable, true);
1831 bool ignoreTimeTest = arg_get_lit(ctx, 1);
1832 bool runSlowTests = arg_get_lit(ctx, 2);
1833 CLIParserFree(ctx);
1835 return ExecuteCryptoTests(true, ignoreTimeTest, runSlowTests);
1838 static int CmdEMVRoca(const char *Cmd) {
1839 uint8_t AID[APDU_AID_LEN] = {0};
1840 size_t AIDlen = 0;
1841 uint8_t buf[APDU_RES_LEN] = {0};
1842 size_t len = 0;
1843 uint16_t sw = 0;
1844 uint8_t ODAI_list[4096];
1845 size_t ODAI_listlen = 0;
1846 int res;
1848 CLIParserContext *ctx;
1849 CLIParserInit(&ctx, "emv roca",
1850 "Tries to extract public keys and run the ROCA test against them.\n",
1851 "emv roca -w -> select --CONTACT-- card and run test\n"
1852 "emv roca -> select --CONTACTLESS-- card and run test\n"
1855 void *argtable[] = {
1856 arg_param_begin,
1857 arg_lit0("tT", "selftest", "self test"),
1858 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
1859 arg_lit0("wW", "wired", "Send data via contact (iso7816) interface. Contactless interface set by default"),
1860 arg_param_end
1862 CLIExecWithReturn(ctx, Cmd, argtable, true);
1864 if (arg_get_lit(ctx, 1)) {
1865 CLIParserFree(ctx);
1866 return roca_self_test();
1869 bool show_apdu = arg_get_lit(ctx, 2);
1871 Iso7816CommandChannel channel = CC_CONTACTLESS;
1872 if (arg_get_lit(ctx, 3))
1873 channel = CC_CONTACT;
1875 CLIParserFree(ctx);
1876 PrintChannel(channel);
1878 if (!IfPm3Smartcard()) {
1879 if (channel == CC_CONTACT) {
1880 PrintAndLogEx(WARNING, "PM3 does not have SMARTCARD support, exiting");
1881 return PM3_EDEVNOTSUPP;
1885 // select card
1886 uint8_t psenum = (channel == CC_CONTACT) ? 1 : 2;
1888 SetAPDULogging(show_apdu);
1890 // init applets list tree
1891 const char *al = "Applets list";
1892 struct tlvdb *tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al);
1894 // EMV PPSE
1895 PrintAndLogEx(INFO, "PPSE");
1896 res = EMVSearchPSE(channel, false, true, psenum, false, tlvSelect);
1898 // check PPSE and select application id
1899 if (!res) {
1900 TLVPrintAIDlistFromSelectTLV(tlvSelect);
1901 } else {
1902 // EMV SEARCH with AID list
1903 PrintAndLogEx(INFO, "starting AID search");
1904 if (EMVSearch(channel, false, true, false, tlvSelect)) {
1905 PrintAndLogEx(ERR, "Can't found any of EMV AID, exiting");
1906 tlvdb_free(tlvSelect);
1907 DropFieldEx(channel);
1908 return PM3_ERFTRANS;
1911 // check search and select application id
1912 TLVPrintAIDlistFromSelectTLV(tlvSelect);
1915 // EMV SELECT application
1916 SetAPDULogging(false);
1917 EMVSelectApplication(tlvSelect, AID, &AIDlen);
1919 tlvdb_free(tlvSelect);
1921 if (!AIDlen) {
1922 PrintAndLogEx(INFO, "Can't select AID or EMV AID not found, exiting");
1923 DropFieldEx(channel);
1924 return PM3_ERFTRANS;
1927 // Init TLV tree
1928 const char *alr = "Root terminal TLV tree";
1929 struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
1931 // EMV SELECT applet
1932 PrintAndLogEx(INFO, "Selecting AID: " _YELLOW_("%s"), sprint_hex_inrow(AID, AIDlen));
1933 res = EMVSelect(channel, false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot);
1935 if (res) {
1936 PrintAndLogEx(ERR, "Can't select AID (%d), exiting", res);
1937 tlvdb_free(tlvRoot);
1938 DropFieldEx(channel);
1939 return PM3_ERFTRANS;
1942 PrintAndLogEx(INFO, "Init transaction parameters");
1943 InitTransactionParameters(tlvRoot, true, TT_QVSDCMCHIP, false);
1945 PrintAndLogEx(INFO, "Calc PDOL");
1946 struct tlv *pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83);
1947 if (!pdol_data_tlv) {
1948 PrintAndLogEx(ERR, "Can't create PDOL TLV");
1949 tlvdb_free(tlvRoot);
1950 DropFieldEx(channel);
1951 return PM3_ESOFT;
1954 size_t pdol_data_tlv_data_len;
1955 unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len);
1956 if (!pdol_data_tlv_data) {
1957 PrintAndLogEx(ERR, "Can't create PDOL data, exiting");
1958 tlvdb_free(tlvRoot);
1959 DropFieldEx(channel);
1960 free(pdol_data_tlv);
1961 return PM3_ESOFT;
1963 PrintAndLogEx(INFO, "PDOL data[%zu]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
1965 PrintAndLogEx(INFO, "GPO");
1966 res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
1968 free(pdol_data_tlv_data);
1969 free(pdol_data_tlv);
1971 if (res) {
1972 PrintAndLogEx(ERR, "GPO error(%d): %4x, exiting", res, sw);
1973 tlvdb_free(tlvRoot);
1974 DropFieldEx(channel);
1975 return PM3_ERFTRANS;
1977 ProcessGPOResponseFormat1(tlvRoot, buf, len, false);
1979 PrintAndLogEx(INFO, "Read records from AFL");
1980 const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL);
1982 while (AFL && AFL->len) {
1983 if (AFL->len % 4) {
1984 PrintAndLogEx(ERR, "Wrong AFL length: %zu", AFL->len);
1985 break;
1988 for (int i = 0; i < AFL->len / 4; i++) {
1989 uint8_t SFI = AFL->value[i * 4 + 0] >> 3;
1990 uint8_t SFIstart = AFL->value[i * 4 + 1];
1991 uint8_t SFIend = AFL->value[i * 4 + 2];
1992 uint8_t SFIoffline = AFL->value[i * 4 + 3];
1994 PrintAndLogEx(INFO, " SFI[%02x] start :%02x end :%02x offline :%02x", SFI, SFIstart, SFIend, SFIoffline);
1995 if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) {
1996 PrintAndLogEx(ERR, "SFI ERROR, skipping");
1997 continue;
2000 for (int n = SFIstart; n <= SFIend; n++) {
2001 PrintAndLogEx(INFO, " SFI[%02x] %d", SFI, n);
2003 res = EMVReadRecord(channel, true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot);
2004 if (res) {
2005 PrintAndLogEx(ERR, "SFI[%02x]. APDU error %4x", SFI, sw);
2006 continue;
2009 // Build Input list for Offline Data Authentication
2010 // EMV 4.3 book3 10.3, page 96
2011 if (SFIoffline > 0) {
2012 if (SFI < 11) {
2013 const unsigned char *abuf = buf;
2014 size_t elmlen = len;
2015 struct tlv e;
2016 if (tlv_parse_tl(&abuf, &elmlen, &e)) {
2017 memcpy(ODAI_list + ODAI_listlen, &buf[len - elmlen], elmlen);
2018 ODAI_listlen += elmlen;
2019 } else {
2020 PrintAndLogEx(WARNING, "Error SFI[%02x]. Creating input list for Offline Data Authentication error", SFI);
2022 } else {
2023 memcpy(ODAI_list + ODAI_listlen, buf, len);
2024 ODAI_listlen += len;
2026 SFIoffline--;
2030 break;
2033 // getting certificates
2034 int ret = PM3_SUCCESS;
2036 // copy Input list for Offline Data Authentication
2037 if (ODAI_listlen) {
2038 struct tlvdb *oda = tlvdb_fixed(0x21, ODAI_listlen, ODAI_list); // not a standard tag
2039 tlvdb_add(tlvRoot, oda);
2040 PrintAndLogEx(INFO, "Input list for Offline Data Authentication added to TLV [%zu bytes]", ODAI_listlen);
2043 if (tlvdb_get(tlvRoot, 0x90, NULL)) {
2044 PrintAndLogEx(INFO, "Recovering certificates");
2045 PKISetStrictExecution(false);
2047 struct emv_pk *pk = get_ca_pk(tlvRoot);
2048 if (!pk) {
2049 PrintAndLogEx(ERR, "ERROR: Key not found, exiting");
2050 ret = PM3_ESOFT;
2051 goto out;
2054 struct emv_pk *issuer_pk = emv_pki_recover_issuer_cert(pk, tlvRoot);
2055 if (!issuer_pk) {
2056 emv_pk_free(pk);
2057 PrintAndLogEx(WARNING, "WARNING: Issuer certificate not found, exiting");
2058 ret = PM3_ESOFT;
2059 goto out;
2062 PrintAndLogEx(SUCCESS, "Issuer Public key recovered RID " _YELLOW_("%s") " IDX " _YELLOW_("%02hhx") " CSN " _YELLOW_("%s"),
2063 sprint_hex(issuer_pk->rid, 5),
2064 issuer_pk->index,
2065 sprint_hex(issuer_pk->serial, 3)
2069 const struct tlv *sda_tlv = tlvdb_get(tlvRoot, 0x21, NULL);
2070 struct emv_pk *icc_pk = emv_pki_recover_icc_cert(issuer_pk, tlvRoot, sda_tlv);
2071 if (!icc_pk) {
2072 emv_pk_free(pk);
2073 emv_pk_free(issuer_pk);
2074 PrintAndLogEx(WARNING, "WARNING: ICC certificate not found, exiting");
2075 ret = PM3_ESOFT;
2076 goto out;
2079 PrintAndLogEx(SUCCESS, "ICC Public key recovered RID " _YELLOW_("%s") " IDX " _YELLOW_("%02hhx") " CSN " _YELLOW_("%s"),
2080 sprint_hex(icc_pk->rid, 5),
2081 icc_pk->index,
2082 sprint_hex(icc_pk->serial, 3)
2085 PrintAndLogEx(INFO, "ICC Public key modulus:");
2086 print_hex_break(icc_pk->modulus, icc_pk->mlen, 16);
2088 // icc_pk->exp, icc_pk->elen
2089 // icc_pk->modulus, icc_pk->mlen
2090 if (icc_pk->elen > 0 && icc_pk->mlen > 0) {
2091 PrintAndLogEx(NORMAL, "");
2092 if (emv_rocacheck(icc_pk->modulus, icc_pk->mlen, false)) {
2093 PrintAndLogEx(SUCCESS, "ICC Public key is " _RED_("subject") " to ROCA vulnerability, it is considered insecure");
2094 } else {
2095 PrintAndLogEx(INFO, "ICC Public key is " _GREEN_("not subject") " to ROCA vulnerability, it is secure");
2099 PKISetStrictExecution(true);
2102 out:
2103 tlvdb_free(tlvRoot);
2104 DropFieldEx(channel);
2105 return ret;
2108 static command_t CommandTable[] = {
2109 {"help", CmdHelp, AlwaysAvailable, "This help"},
2110 {"exec", CmdEMVExec, IfPm3Iso14443, "Executes EMV contactless transaction."},
2111 {"pse", CmdEMVPPSE, IfPm3Iso14443, "Execute PPSE. It selects 2PAY.SYS.DDF01 or 1PAY.SYS.DDF01 directory."},
2112 {"search", CmdEMVSearch, IfPm3Iso14443, "Try to select all applets from applets list and print installed applets."},
2113 {"select", CmdEMVSelect, IfPm3Iso14443, "Select applet."},
2114 {"gpo", CmdEMVGPO, IfPm3Iso14443, "Execute GetProcessingOptions."},
2115 {"readrec", CmdEMVReadRecord, IfPm3Iso14443, "Read files from card."},
2116 {"genac", CmdEMVAC, IfPm3Iso14443, "Generate ApplicationCryptogram."},
2117 {"challenge", CmdEMVGenerateChallenge, IfPm3Iso14443, "Generate challenge."},
2118 {"intauth", CmdEMVInternalAuthenticate, IfPm3Iso14443, "Internal authentication."},
2119 {"scan", CmdEMVScan, IfPm3Iso14443, "Scan EMV card and save it contents to json file for emulator."},
2120 {"test", CmdEMVTest, AlwaysAvailable, "Crypto logic test."},
2122 {"getrng", CmdEMVGetrng, IfPm3Iso14443, "get random number from terminal"},
2123 {"eload", CmdEmvELoad, IfPm3Iso14443, "load EMV tag into device"},
2124 {"dump", CmdEmvDump, IfPm3Iso14443, "dump EMV tag values"},
2125 {"sim", CmdEmvSim, IfPm3Iso14443, "simulate EMV tag"},
2126 {"clone", CmdEmvClone, IfPm3Iso14443, "clone an EMV tag"},
2128 {"list", CmdEMVList, AlwaysAvailable, "List ISO7816 history"},
2129 {"roca", CmdEMVRoca, IfPm3Iso14443, "Extract public keys and run ROCA test"},
2130 {NULL, NULL, NULL, NULL}
2133 static int CmdHelp(const char *Cmd) {
2134 (void)Cmd; // Cmd is not used so far
2135 CmdsHelp(CommandTable);
2136 return PM3_SUCCESS;
2139 int CmdEMV(const char *Cmd) {
2140 clearCommandBuffer();
2141 return CmdsParse(CommandTable, Cmd);