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
7 //-----------------------------------------------------------------------------
9 //-----------------------------------------------------------------------------
15 #include "comms.h" // DropField
16 #include "cmdsmartcard.h" // smart_select
19 #include "test/cryptotest.h"
20 #include "cliparser.h"
21 #include "cmdparser.h"
22 #include "proxmark3.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
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
) {
62 PrintAndLogEx(INFO
, "Selected channel... " _GREEN_("CONTACTLESS (T=CL)"));
65 PrintAndLogEx(INFO
, "Selected channel... " _GREEN_("CONTACT"));
70 static int CmdEMVSelect(const char *Cmd
) {
71 uint8_t data
[APDU_AID_LEN
] = {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");
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
),
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))
99 PrintChannel(channel
);
100 CLIGetHexWithReturn(ctx
, 6, data
, &datalen
);
103 SetAPDULogging(APDULogging
);
106 uint8_t buf
[APDU_RES_LEN
] = {0};
109 int res
= EMVSelect(channel
, activateField
, leaveSignalON
, data
, datalen
, buf
, sizeof(buf
), &len
, &sw
, NULL
);
112 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
118 TLVPrintFromBuffer(buf
, len
);
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");
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."),
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
);
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
)) {
162 PrintAndLogEx(SUCCESS
, "Search completed.");
166 TLVPrintAIDlistFromSelectTLV(t
);
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");
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."),
193 CLIExecWithReturn(ctx
, Cmd
, argtable
, true);
195 bool activateField
= arg_get_lit(ctx
, 1);
196 bool leaveSignalON
= arg_get_lit(ctx
, 2);
198 if (arg_get_lit(ctx
, 3))
200 if (arg_get_lit(ctx
, 4))
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
);
210 SetAPDULogging(APDULogging
);
213 uint8_t buf
[APDU_RES_LEN
] = {0};
216 int res
= EMVSelectPSE(channel
, activateField
, leaveSignalON
, PSENum
, buf
, sizeof(buf
), &len
, &sw
);
219 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
225 TLVPrintFromBuffer(buf
, len
);
230 static int CmdEMVGPO(const char *Cmd
) {
231 uint8_t data
[APDU_RES_LEN
] = {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");
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
),
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
);
267 SetAPDULogging(APDULogging
);
270 const char *alr
= "Root terminal TLV tree";
271 struct tlvdb
*tlvRoot
= tlvdb_fixed(1, strlen(alr
), (const unsigned char *)alr
);
274 struct tlv
*pdol_data_tlv
= NULL
;
275 struct tlvdb
*tmp_ext
= NULL
;
276 struct tlv data_tlv
= {
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.");
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.");
310 if (pdol_data_tlv
!= &data_tlv
)
314 PrintAndLogEx(INFO
, "PDOL data[%zu]: %s", pdol_data_tlv_data_len
, sprint_hex(pdol_data_tlv_data
, pdol_data_tlv_data_len
));
317 uint8_t buf
[APDU_RES_LEN
] = {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
)
329 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
335 TLVPrintFromBuffer(buf
, len
);
340 static int CmdEMVReadRecord(const char *Cmd
) {
341 uint8_t data
[APDU_RES_LEN
] = {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");
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
),
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
);
373 PrintAndLogEx(ERR
, "Command needs to have 2 bytes of data");
377 SetAPDULogging(APDULogging
);
380 uint8_t buf
[APDU_RES_LEN
] = {0};
383 int res
= EMVReadRecord(channel
, leaveSignalON
, data
[0], data
[1], buf
, sizeof(buf
), &len
, &sw
, NULL
);
386 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
393 TLVPrintFromBuffer(buf
, len
);
398 static int CmdEMVAC(const char *Cmd
) {
399 uint8_t data
[APDU_RES_LEN
] = {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");
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
),
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]);
443 termDecision
= EMVAC_TC
;
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
);
460 SetAPDULogging(APDULogging
);
463 const char *alr
= "Root terminal TLV tree";
464 struct tlvdb
*tlvRoot
= tlvdb_fixed(1, strlen(alr
), (const unsigned char *)alr
);
467 struct tlv
*cdol_data_tlv
= NULL
;
468 struct tlvdb
*tmp_ext
= NULL
;
469 struct tlv data_tlv
= {
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.");
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
));
501 uint8_t buf
[APDU_RES_LEN
] = {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
)
513 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
519 TLVPrintFromBuffer(buf
, len
);
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");
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."),
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
);
550 SetAPDULogging(APDULogging
);
553 uint8_t buf
[APDU_RES_LEN
] = {0};
556 int res
= EMVGenerateChallenge(channel
, leaveSignalON
, buf
, sizeof(buf
), &len
, &sw
, NULL
);
559 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
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
);
572 static int CmdEMVInternalAuthenticate(const char *Cmd
) {
573 uint8_t data
[APDU_RES_LEN
] = {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");
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
),
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
);
610 SetAPDULogging(APDULogging
);
613 const char *alr
= "Root terminal TLV tree";
614 struct tlvdb
*tlvRoot
= tlvdb_fixed(1, strlen(alr
), (const unsigned char *)alr
);
617 struct tlv
*ddol_data_tlv
= NULL
;
618 struct tlvdb
*tmp_ext
= NULL
;
619 struct tlv data_tlv
= {
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.");
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
));
651 uint8_t buf
[APDU_RES_LEN
] = {0};
654 int res
= EMVInternalAuthenticate(channel
, leaveSignalON
, data
, datalen
, buf
, sizeof(buf
), &len
, &sw
, NULL
);
656 if (ddol_data_tlv
!= &data_tlv
)
663 PrintAndLogEx(INFO
, "APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
669 TLVPrintFromBuffer(buf
, len
);
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
);
681 PrintAndLogEx(INFO
, "* * Transaction parameters loading from JSON...");
682 ParamLoadFromJson(tlvRoot
);
685 //9F66:(Terminal Transaction Qualifiers (TTQ)) len:4
689 TLV_ADD(0x9F66, "\x86\x00\x00\x00"); // MSD
691 // not standard for contactless. just for test.
693 TLV_ADD(0x9F66, "\x46\x00\x00\x00"); // VSDC
698 TLV_ADD(0x9F66, "\x26\x80\x00\x00");
700 TLV_ADD(0x9F66, "\x26\x00\x00\x00");
704 // qVSDC (VISA CDA not enabled)
706 TLV_ADD(0x9F66, "\x26\x80\x00\x00");
708 TLV_ADD(0x9F66, "\x26\x00\x00\x00");
716 static void ProcessGPOResponseFormat1(struct tlvdb
*tlvRoot
, uint8_t *buf
, size_t len
, bool decodeTLV
) {
717 if (buf
[0] == 0x80) {
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
);
727 struct tlvdb
*f1AIP
= tlvdb_fixed(0x82, 2, buf
+ 2);
728 tlvdb_add(tlvRoot
, f1AIP
);
730 PrintAndLogEx(INFO
, "\n* * Decode response format 1 (0x80) AIP and AFL:");
731 TLVPrintFromTLV(f1AIP
);
735 struct tlvdb
*f1AFL
= tlvdb_fixed(0x94, len
- 4, buf
+ 2 + 2);
736 tlvdb_add(tlvRoot
, f1AFL
);
738 TLVPrintFromTLV(f1AFL
);
742 TLVPrintFromBuffer(buf
, len
);
746 static void ProcessACResponseFormat1(struct tlvdb
*tlvRoot
, uint8_t *buf
, size_t len
, bool decodeTLV
) {
747 if (buf
[0] == 0x80) {
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
);
758 struct tlvdb
*tlvElm
= NULL
;
760 PrintAndLogEx(NORMAL
, "\n------------ Format1 decoded ------------");
762 // CID (Cryptogram Information Data)
763 tlvdb_change_or_add_node_ex(tlvRoot
, 0x9f27, 1, &buf
[2], &tlvElm
);
765 TLVPrintFromTLV(tlvElm
);
767 // ATC (Application Transaction Counter)
768 tlvdb_change_or_add_node_ex(tlvRoot
, 0x9f36, 2, &buf
[3], &tlvElm
);
770 TLVPrintFromTLV(tlvElm
);
772 // AC (Application Cryptogram)
773 tlvdb_change_or_add_node_ex(tlvRoot
, 0x9f26, MIN(8, elmlen
- 3), &buf
[5], &tlvElm
);
775 TLVPrintFromTLV(tlvElm
);
777 // IAD (Issuer Application Data) - optional
779 tlvdb_change_or_add_node_ex(tlvRoot
, 0x9f10, elmlen
- 11, &buf
[13], &tlvElm
);
781 TLVPrintFromTLV(tlvElm
);
787 TLVPrintFromBuffer(buf
, len
);
791 static int CmdEMVExec(const char *Cmd
) {
792 uint8_t buf
[APDU_RES_LEN
] = {0};
795 uint8_t AID
[APDU_AID_LEN
] = {0};
797 uint8_t ODAiList
[4096];
798 size_t ODAiListLen
= 0;
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");
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."),
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))
840 if (arg_get_lit(ctx
, 9))
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;
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
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
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
880 TLVPrintAIDlistFromSelectTLV(tlvSelect
);
881 EMVSelectApplication(tlvSelect
, AID
, &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
);
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
904 PrintAndLogEx(WARNING
, "Can't select AID. EMV AID not found");
905 dreturn(PM3_ERFTRANS
);
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
);
914 PrintAndLogEx(WARNING
, "Can't select AID (%d). Exit...", res
);
915 dreturn(PM3_ERFTRANS
);
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.");
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.");
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.
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
);
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
));
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
) {
979 PrintAndLogEx(WARNING
, "Warning: Wrong AFL length: %zu", AFL
->len
);
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...");
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
);
1000 PrintAndLogEx(WARNING
, "Error SFI[%02x]. APDU error %4x", SFI
, sw
);
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) {
1013 const unsigned char *abuf
= buf
;
1014 size_t elmlen
= len
;
1016 if (tlv_parse_tl(&abuf
, &elmlen
, &e
)) {
1017 memcpy(&ODAiList
[ODAiListLen
], &buf
[len
- elmlen
], elmlen
);
1018 ODAiListLen
+= elmlen
;
1020 PrintAndLogEx(WARNING
, "Error SFI[%02x]. Creating input list for Offline Data Authentication error.", SFI
);
1023 memcpy(&ODAiList
[ODAiListLen
], buf
, len
);
1035 // copy Input list for Offline Data Authentication
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
);
1044 const struct tlv
*AIPtlv
= tlvdb_get(tlvRoot
, 0x82, NULL
);
1046 AIP
= AIPtlv
->value
[0] + AIPtlv
->value
[1] * 0x100;
1047 PrintAndLogEx(NORMAL
, "* * AIP=%04x", AIP
);
1049 PrintAndLogEx(ERR
, "Can't find AIP.");
1054 PrintAndLogEx(NORMAL
, "\n* SDA");
1060 PrintAndLogEx(NORMAL
, "\n* DDA");
1061 trDDA(channel
, decodeTLV
, tlvRoot
);
1064 // transaction check
1067 if (TrType
== TT_QVSDCMCHIP
|| TrType
== TT_CDA
) {
1068 // 9F26: Application Cryptogram
1069 const struct tlv
*AC
= tlvdb_get(tlvRoot
, 0x9F26, NULL
);
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
);
1078 // 9F10: Issuer Application Data - optional
1079 const struct tlv
*IAD
= tlvdb_get(tlvRoot
, 0x9F10, NULL
);
1082 PrintAndLogEx(NORMAL
, "ATC: %s", sprint_hex(ATC
->value
, ATC
->len
));
1083 PrintAndLogEx(NORMAL
, "AC: %s", sprint_hex(AC
->value
, AC
->len
));
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
);
1106 PrintAndLogEx(NORMAL
, " IDD option id: 0x%02x", IAD
->value
[8]);
1108 PrintAndLogEx(NORMAL
, " IDD: %s", sprint_hex(&IAD
->value
[9], iddLen
- 1));
1112 PrintAndLogEx(WARNING
, "WARNING: IAD not found.");
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
);
1130 PrintAndLogEx(ERR
, "Error GetChallenge. APDU error %4x", sw
);
1131 dreturn(PM3_ERFTRANS
);
1134 PrintAndLogEx(ERR
, "Error GetChallenge. Wrong challenge length %zu", len
);
1138 // ICC Dynamic Number
1139 struct tlvdb
*ICCDynN
= tlvdb_fixed(0x9f4c, len
, buf
);
1140 tlvdb_add(tlvRoot
, ICCDynN
);
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.");
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
);
1160 PrintAndLogEx(ERR
, "AC1 error(%d): %4x. Exit...", res
, sw
);
1161 dreturn(PM3_ERFTRANS
);
1165 TLVPrintFromBuffer(buf
, len
);
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
);
1173 PrintAndLogEx(NORMAL
, "CDA error (%d)", res
);
1176 PrintAndLogEx(NORMAL
, "\n* Signed Dynamic Application Data (0x9f4b) not present");
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
);
1186 emv_tag_dump(CID
, 1);
1187 PrintAndLogEx(NORMAL
, "------------------------------");
1189 switch (CID
->value
[0] & EMVAC_AC_MASK
) {
1191 PrintAndLogEx(NORMAL
, "Transaction DECLINED.");
1194 PrintAndLogEx(NORMAL
, "Transaction approved OFFLINE.");
1197 PrintAndLogEx(NORMAL
, "Transaction approved ONLINE.");
1200 PrintAndLogEx(WARNING
, "Warning: CID transaction code error %2x", CID
->value
[0] & EMVAC_AC_MASK
);
1204 PrintAndLogEx(WARNING
, "Warning: Wrong CID length %zu", CID
->len
);
1207 PrintAndLogEx(WARNING
, "Warning: CID(9F27) not found.");
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
);
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");
1231 const struct tlv
*UDOL
= tlvdb_get(tlvRoot
, 0x9F69, NULL
);
1232 // UDOL(9F69) default: 9F6A (Unpredictable number) 4 bytes
1233 const struct tlv defUDOL
= {
1236 .value
= (uint8_t *)"\x9f\x6a\x04",
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.");
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
);
1253 PrintAndLogEx(ERR
, "Error Compute Crypto Checksum. APDU error %4x", sw
);
1254 free(udol_data_tlv
);
1258 // Mastercard compute cryptographic checksum result
1259 TLVPrintFromBuffer(buf
, len
);
1260 PrintAndLogEx(NORMAL
, "");
1262 free(udol_data_tlv
);
1266 PrintAndLogEx(ERR
, "Error MSD: Track2 data not found.");
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.");
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
);
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
);
1296 tlvdb_get_uint8(tlvRoot
, 0x9f27, &CID
);
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
));
1332 PrintAndLogEx(WARNING
, "Wrong CVR length! CVR: %s", sprint_hex(&IAD
->value
[3], VDDlen
- 2));
1336 PrintAndLogEx(NORMAL
, "IDD: %s", sprint_hex(&IAD
->value
[VDDlen
+ 1], IDDlen
));
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");
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
);
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 (
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
);
1405 free(pdol_data_tlv
);
1407 tlvdb_free(tlvSelect
);
1408 tlvdb_free(tlvRoot
);
1410 PrintAndLogEx(NORMAL
, "\n* Transaction completed.");
1414 static int CmdEMVScan(const char *Cmd
) {
1415 uint8_t AID
[APDU_AID_LEN
] = {0};
1417 uint8_t buf
[APDU_RES_LEN
] = {0};
1419 uint8_t ODAI_list
[4096];
1420 size_t ODAI_listlen
= 0;
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
[] = {
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"),
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))
1460 if (arg_get_lit(ctx
, 8))
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
);
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
);
1492 // current path + file name
1495 root
= json_load_file((char *)filename
, 0, &error
);
1497 PrintAndLogEx(ERR
, "Json error on line %d: %s", error
.line
, error
.text
);
1501 if (!json_is_object(root
)) {
1502 PrintAndLogEx(ERR
, "Invalid json format. root must be an object");
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
) {
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
);
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
);
1547 PrintAndLogEx(INFO
, "PPSE");
1548 res
= EMVSelectPSE(channel
, true, true, 2, buf
, sizeof(buf
), &len
, &sw
);
1550 if (!res
&& sw
== 0x9000) {
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
);
1560 JsonSaveTLVTreeElm(root
, "$.PPSE.FCITemplate", fci
, true, true, false);
1561 JsonSaveTLVValue(root
, "$.Application.KernelID", tlvdb_find_full(fci
, 0x9f2a));
1565 res
= EMVSearchPSE(channel
, false, true, psenum
, decodeTLV
, tlvSelect
);
1567 // check PPSE and select application id
1569 TLVPrintAIDlistFromSelectTLV(tlvSelect
);
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
);
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
);
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
);
1610 PrintAndLogEx(ERR
, "Can't select AID (%d), exiting...", res
);
1611 tlvdb_free(tlvRoot
);
1612 DropFieldEx(channel
);
1613 return PM3_ERFTRANS
;
1617 TLVPrintFromBuffer(buf
, len
);
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
);
1628 JsonSaveTLVTreeElm(root
, "$.Application.FCITemplate", fci
, true, true, false);
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
);
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
);
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
);
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
);
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));
1681 PrintAndLogEx(INFO
, "Read records from AFL");
1682 const struct tlv
*AFL
= tlvdb_get(tlvRoot
, 0x94, NULL
);
1684 while (AFL
&& AFL
->len
) {
1686 PrintAndLogEx(ERR
, "Wrong AFL length: %zu", AFL
->len
);
1690 json_t
*sfijson
= json_path_get(root
, "$.Application.Records");
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.");
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...");
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
);
1719 PrintAndLogEx(ERR
, "SFI[%02x]. APDU error %4x", SFI
, sw
);
1723 // Build Input list for Offline Data Authentication
1724 // EMV 4.3 book3 10.3, page 96
1725 if (first_time
&& SFIoffline
) {
1727 const unsigned char *abuf
= buf
;
1728 size_t elmlen
= len
;
1730 if (tlv_parse_tl(&abuf
, &elmlen
, &e
)) {
1731 memcpy(ODAI_list
+ ODAI_listlen
, &buf
[len
- elmlen
], elmlen
);
1732 ODAI_listlen
+= elmlen
;
1734 PrintAndLogEx(WARNING
, "Error SFI[%02x]. Creating input list for Offline Data Authentication error", SFI
);
1737 memcpy(ODAI_list
+ ODAI_listlen
, buf
, len
);
1738 ODAI_listlen
+= len
;
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
);
1759 JsonSaveTLVTreeElm(jsonelm
, "$.Data", rsfi
, true, true, false);
1767 // copy Input list for Offline Data Authentication
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);
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
) {
1794 strcpy((char *)filename
, fname
);
1798 res
= json_dump_file(root
, (char *)filename
, JSON_INDENT(2));
1800 PrintAndLogEx(ERR
, "Can't save the file: %s", filename
);
1804 PrintAndLogEx(SUCCESS
, "File " _YELLOW_("`%s`") " saved.", filename
);
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",
1823 void *argtable
[] = {
1825 arg_lit0("i", "ignore", "ignore timing tests for VM"),
1826 arg_lit0("l", "long", "run long tests too"),
1829 CLIExecWithReturn(ctx
, Cmd
, argtable
, true);
1831 bool ignoreTimeTest
= arg_get_lit(ctx
, 1);
1832 bool runSlowTests
= arg_get_lit(ctx
, 2);
1835 return ExecuteCryptoTests(true, ignoreTimeTest
, runSlowTests
);
1838 static int CmdEMVRoca(const char *Cmd
) {
1839 uint8_t AID
[APDU_AID_LEN
] = {0};
1841 uint8_t buf
[APDU_RES_LEN
] = {0};
1844 uint8_t ODAI_list
[4096];
1845 size_t ODAI_listlen
= 0;
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
[] = {
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"),
1862 CLIExecWithReturn(ctx
, Cmd
, argtable
, true);
1864 if (arg_get_lit(ctx
, 1)) {
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
;
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
;
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
);
1895 PrintAndLogEx(INFO
, "PPSE");
1896 res
= EMVSearchPSE(channel
, false, true, psenum
, false, tlvSelect
);
1898 // check PPSE and select application id
1900 TLVPrintAIDlistFromSelectTLV(tlvSelect
);
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
);
1922 PrintAndLogEx(INFO
, "Can't select AID or EMV AID not found, exiting");
1923 DropFieldEx(channel
);
1924 return PM3_ERFTRANS
;
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
);
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
);
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
);
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
);
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
) {
1984 PrintAndLogEx(ERR
, "Wrong AFL length: %zu", AFL
->len
);
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");
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
);
2005 PrintAndLogEx(ERR
, "SFI[%02x]. APDU error %4x", SFI
, sw
);
2009 // Build Input list for Offline Data Authentication
2010 // EMV 4.3 book3 10.3, page 96
2011 if (SFIoffline
> 0) {
2013 const unsigned char *abuf
= buf
;
2014 size_t elmlen
= len
;
2016 if (tlv_parse_tl(&abuf
, &elmlen
, &e
)) {
2017 memcpy(ODAI_list
+ ODAI_listlen
, &buf
[len
- elmlen
], elmlen
);
2018 ODAI_listlen
+= elmlen
;
2020 PrintAndLogEx(WARNING
, "Error SFI[%02x]. Creating input list for Offline Data Authentication error", SFI
);
2023 memcpy(ODAI_list
+ ODAI_listlen
, buf
, len
);
2024 ODAI_listlen
+= len
;
2033 // getting certificates
2034 int ret
= PM3_SUCCESS
;
2036 // copy Input list for Offline Data Authentication
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
);
2049 PrintAndLogEx(ERR
, "ERROR: Key not found, exiting");
2054 struct emv_pk
*issuer_pk
= emv_pki_recover_issuer_cert(pk
, tlvRoot
);
2057 PrintAndLogEx(WARNING
, "WARNING: Issuer certificate not found, exiting");
2062 PrintAndLogEx(SUCCESS
, "Issuer Public key recovered RID " _YELLOW_("%s") " IDX " _YELLOW_("%02hhx") " CSN " _YELLOW_("%s"),
2063 sprint_hex(issuer_pk
->rid
, 5),
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
);
2073 emv_pk_free(issuer_pk
);
2074 PrintAndLogEx(WARNING
, "WARNING: ICC certificate not found, exiting");
2079 PrintAndLogEx(SUCCESS
, "ICC Public key recovered RID " _YELLOW_("%s") " IDX " _YELLOW_("%02hhx") " CSN " _YELLOW_("%s"),
2080 sprint_hex(icc_pk
->rid
, 5),
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");
2095 PrintAndLogEx(INFO
, "ICC Public key is " _GREEN_("not subject") " to ROCA vulnerability, it is secure");
2099 PKISetStrictExecution(true);
2103 tlvdb_free(tlvRoot
);
2104 DropFieldEx(channel
);
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
);
2139 int CmdEMV(const char *Cmd
) {
2140 clearCommandBuffer();
2141 return CmdsParse(CommandTable
, Cmd
);