1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2017, 2018 Merlok
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 //-----------------------------------------------------------------------------
13 #include "test/cryptotest.h"
14 #include "cliparser/cliparser.h"
17 #define TLV_ADD(tag, value)( tlvdb_change_or_add_node(tlvRoot, tag, sizeof(value) - 1, (const unsigned char *)value) )
18 void ParamLoadDefaults(struct tlvdb
*tlvRoot
) {
19 //9F02:(Amount, authorized (Numeric)) len:6
20 TLV_ADD(0x9F02, "\x00\x00\x00\x00\x01\x00");
21 //9F1A:(Terminal Country Code) len:2
22 TLV_ADD(0x9F1A, "ru");
23 //5F2A:(Transaction Currency Code) len:2
24 // USD 840, EUR 978, RUR 810, RUB 643, RUR 810(old), UAH 980, AZN 031, n/a 999
25 TLV_ADD(0x5F2A, "\x09\x80");
26 //9A:(Transaction Date) len:3
27 TLV_ADD(0x9A, "\x00\x00\x00");
28 //9C:(Transaction Type) len:1 | 00 => Goods and service #01 => Cash
29 TLV_ADD(0x9C, "\x00");
30 // 9F37 Unpredictable Number len:4
31 TLV_ADD(0x9F37, "\x01\x02\x03\x04");
32 // 9F6A Unpredictable Number (MSD for UDOL) len:4
33 TLV_ADD(0x9F6A, "\x01\x02\x03\x04");
34 //9F66:(Terminal Transaction Qualifiers (TTQ)) len:4
35 TLV_ADD(0x9F66, "\x26\x00\x00\x00"); // qVSDC
38 int CmdHFEMVSelect(const char *cmd
) {
39 uint8_t data
[APDU_AID_LEN
] = {0};
42 CLIParserInit("hf emv select",
43 "Executes select applet command",
44 "Usage:\n\thf emv select -s a00000000101 -> select card, select applet\n\thf emv select -st a00000000101 -> select card, select applet, show result in TLV\n");
48 arg_lit0("sS", "select", "activate field and select card"),
49 arg_lit0("kK", "keep", "keep field for next command"),
50 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
51 arg_lit0("tT", "tlv", "TLV decode results"),
52 arg_str0(NULL
, NULL
, "<HEX applet AID>", NULL
),
55 CLIExecWithReturn(cmd
, argtable
, true);
57 bool activateField
= arg_get_lit(1);
58 bool leaveSignalON
= arg_get_lit(2);
59 bool APDULogging
= arg_get_lit(3);
60 bool decodeTLV
= arg_get_lit(4);
61 CLIGetStrWithReturn(5, data
, &datalen
);
64 SetAPDULogging(APDULogging
);
67 uint8_t buf
[APDU_RES_LEN
] = {0};
70 int res
= EMVSelect(activateField
, leaveSignalON
, data
, datalen
, buf
, sizeof(buf
), &len
, &sw
, NULL
);
73 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
79 TLVPrintFromBuffer(buf
, len
);
84 int CmdHFEMVSearch(const char *cmd
) {
86 CLIParserInit("hf emv search",
87 "Tries to select all applets from applet list:\n",
88 "Usage:\n\thf emv search -s -> select card and search\n\thf emv search -st -> select card, search and show result in TLV\n");
92 arg_lit0("sS", "select", "activate field and select card"),
93 arg_lit0("kK", "keep", "keep field ON for next command"),
94 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
95 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
98 CLIExecWithReturn(cmd
, argtable
, true);
100 bool activateField
= arg_get_lit(1);
101 bool leaveSignalON
= arg_get_lit(2);
102 bool APDULogging
= arg_get_lit(3);
103 bool decodeTLV
= arg_get_lit(4);
106 SetAPDULogging(APDULogging
);
108 struct tlvdb
*t
= NULL
;
109 const char *al
= "Applets list";
110 t
= tlvdb_fixed(1, strlen(al
), (const unsigned char *)al
);
112 if (EMVSearch(activateField
, leaveSignalON
, decodeTLV
, t
)) {
117 PrintAndLog("Search completed.");
121 TLVPrintAIDlistFromSelectTLV(t
);
129 int CmdHFEMVPPSE(const char *cmd
) {
131 CLIParserInit("hf emv pse",
132 "Executes PSE/PPSE select command. It returns list of applet on the card:\n",
133 "Usage:\n\thf emv pse -s1 -> select, get pse\n\thf emv pse -st2 -> select, get ppse, show result in TLV\n");
137 arg_lit0("sS", "select", "activate field and select card"),
138 arg_lit0("kK", "keep", "keep field ON for next command"),
139 arg_lit0("1", "pse", "pse (1PAY.SYS.DDF01) mode"),
140 arg_lit0("2", "ppse", "ppse (2PAY.SYS.DDF01) mode (default mode)"),
141 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
142 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
145 CLIExecWithReturn(cmd
, argtable
, true);
147 bool activateField
= arg_get_lit(1);
148 bool leaveSignalON
= arg_get_lit(2);
154 bool APDULogging
= arg_get_lit(5);
155 bool decodeTLV
= arg_get_lit(6);
158 SetAPDULogging(APDULogging
);
161 uint8_t buf
[APDU_RES_LEN
] = {0};
164 int res
= EMVSelectPSE(activateField
, leaveSignalON
, PSENum
, buf
, sizeof(buf
), &len
, &sw
);
167 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
174 TLVPrintFromBuffer(buf
, len
);
179 int CmdHFEMVGPO(const char *cmd
) {
180 uint8_t data
[APDU_RES_LEN
] = {0};
183 CLIParserInit("hf emv gpo",
184 "Executes Get Processing Options command. It returns data in TLV format (0x77 - format2) or plain format (0x80 - format1).\nNeeds a EMV applet to be selected.",
185 "Usage:\n\thf emv gpo -k -> execute GPO\n"
186 "\thf emv gpo -st 01020304 -> execute GPO with 4-byte PDOL data, show result in TLV\n");
187 // here need to add load params from file and gen pdol
191 arg_lit0("kK", "keep", "keep field ON for next command"),
192 arg_lit0("pP", "params", "load parameters for PDOL making from `emv/defparams.json` file (by default uses default parameters) (NOT WORK!!!)"),
193 arg_lit0("mM", "make", "make PDOLdata from PDOL (tag 9F38) and parameters (NOT WORK!!!)"),
194 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
195 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
196 arg_str0(NULL
, NULL
, "<HEX PDOLdata/PDOL>", NULL
),
199 CLIExecWithReturn(cmd
, argtable
, true);
201 bool leaveSignalON
= arg_get_lit(1);
202 bool paramsLoadFromFile
= arg_get_lit(2);
203 bool dataMakeFromPDOL
= arg_get_lit(3);
204 bool APDULogging
= arg_get_lit(4);
205 bool decodeTLV
= arg_get_lit(5);
206 CLIGetStrWithReturn(6, data
, &datalen
);
209 SetAPDULogging(APDULogging
);
212 const char *alr
= "Root terminal TLV tree";
213 struct tlvdb
*tlvRoot
= tlvdb_fixed(1, strlen(alr
), (const unsigned char *)alr
);
216 struct tlv
*pdol_data_tlv
= NULL
;
217 struct tlv data_tlv
= {
220 .value
= (uint8_t *)data
,
222 if (dataMakeFromPDOL
) {
224 PrintAndLog("Make PDOL data not implemented!");
226 ParamLoadDefaults(tlvRoot
);
228 if (paramsLoadFromFile
) {
230 /* pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83);
232 PrintAndLog("ERROR: can't create PDOL TLV.");
238 pdol_data_tlv
= &data_tlv
;
241 size_t pdol_data_tlv_data_len
= 0;
242 unsigned char *pdol_data_tlv_data
= tlv_encode(pdol_data_tlv
, &pdol_data_tlv_data_len
);
243 if (!pdol_data_tlv_data
) {
244 PrintAndLog("ERROR: can't create PDOL data.");
248 PrintAndLog("PDOL data[%d]: %s", pdol_data_tlv_data_len
, sprint_hex(pdol_data_tlv_data
, pdol_data_tlv_data_len
));
251 uint8_t buf
[APDU_RES_LEN
] = {0};
254 int res
= EMVGPO(leaveSignalON
, pdol_data_tlv_data
, pdol_data_tlv_data_len
, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
256 free(pdol_data_tlv_data
);
260 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
266 TLVPrintFromBuffer(buf
, len
);
271 int CmdHFEMVReadRecord(const char *cmd
) {
272 uint8_t data
[APDU_RES_LEN
] = {0};
275 CLIParserInit("hf emv readrec",
276 "Executes Read Record command. It returns data in TLV format.\nNeeds a bank applet to be selected and sometimes needs GPO to be executed.",
277 "Usage:\n\thf emv readrec -k 0101 -> read file SFI=01, SFIrec=01\n\thf emv readrec -kt 0201-> read file 0201 and show result in TLV\n");
281 arg_lit0("kK", "keep", "keep field ON for next command"),
282 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
283 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
284 arg_str1(NULL
, NULL
, "<SFI 1byte HEX><SFIrec 1byte HEX>", NULL
),
287 CLIExecWithReturn(cmd
, argtable
, true);
289 bool leaveSignalON
= arg_get_lit(1);
290 bool APDULogging
= arg_get_lit(2);
291 bool decodeTLV
= arg_get_lit(3);
292 CLIGetStrWithReturn(4, data
, &datalen
);
296 PrintAndLog("ERROR: Command needs to have 2 bytes of data");
300 SetAPDULogging(APDULogging
);
303 uint8_t buf
[APDU_RES_LEN
] = {0};
306 int res
= EMVReadRecord(leaveSignalON
, data
[0], data
[1], buf
, sizeof(buf
), &len
, &sw
, NULL
);
309 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
316 TLVPrintFromBuffer(buf
, len
);
321 int CmdHFEMVAC(const char *cmd
) {
322 uint8_t data
[APDU_RES_LEN
] = {0};
325 CLIParserInit("hf emv genac",
326 "Generate Application Cryptogram command. It returns data in TLV format .\nNeeds a EMV applet to be selected and GPO to be executed.",
327 "Usage:\n\thf emv genac -k 0102 -> generate AC with 2-byte CDOLdata and keep field ON after command\n"
328 "\thf emv genac -t 01020304 -> generate AC with 4-byte CDOL data, show result in TLV\n"
329 "\thf emv genac -Daac 01020304 -> generate AC with 4-byte CDOL data and terminal decision 'declined'\n");
333 arg_lit0("kK", "keep", "keep field ON for next command"),
334 arg_lit0("cC", "cda", "executes CDA transaction. Needs to get SDAD in results."),
335 arg_str0("dD", "decision", "<aac|tc|arqc>", "Terminal decision. aac - declined, tc - approved, arqc - online authorisation requested"),
336 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
337 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
338 arg_str1(NULL
, NULL
, "<HEX CDOLdata>", NULL
),
341 CLIExecWithReturn(cmd
, argtable
, false);
343 bool leaveSignalON
= arg_get_lit(1);
344 bool trTypeCDA
= arg_get_lit(2);
345 uint8_t termDecision
= 0xff;
346 if (arg_get_str_len(3)) {
347 if (!strncmp(arg_get_str(3)->sval
[0], "aac", 4))
348 termDecision
= EMVAC_AAC
;
349 if (!strncmp(arg_get_str(3)->sval
[0], "tc", 4))
350 termDecision
= EMVAC_TC
;
351 if (!strncmp(arg_get_str(3)->sval
[0], "arqc", 4))
352 termDecision
= EMVAC_ARQC
;
354 if (termDecision
== 0xff) {
355 PrintAndLog("ERROR: can't find terminal decision '%s'", arg_get_str(3)->sval
[0]);
359 termDecision
= EMVAC_TC
;
362 termDecision
= termDecision
| EMVAC_CDAREQ
;
363 bool APDULogging
= arg_get_lit(4);
364 bool decodeTLV
= arg_get_lit(5);
365 CLIGetStrWithReturn(6, data
, &datalen
);
368 SetAPDULogging(APDULogging
);
371 const char *alr
= "Root terminal TLV tree";
372 struct tlvdb
*tlvRoot
= tlvdb_fixed(1, strlen(alr
), (const unsigned char *)alr
);
375 struct tlv
*cdol_data_tlv
= NULL
;
376 // struct tlv *cdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x8c, NULL), tlvRoot, 0x01); // 0x01 - dummy tag
377 struct tlv data_tlv
= {
380 .value
= (uint8_t *)data
,
382 cdol_data_tlv
= &data_tlv
;
383 PrintAndLog("CDOL data[%d]: %s", cdol_data_tlv
->len
, sprint_hex(cdol_data_tlv
->value
, cdol_data_tlv
->len
));
386 uint8_t buf
[APDU_RES_LEN
] = {0};
389 int res
= EMVAC(leaveSignalON
, termDecision
, (uint8_t *)cdol_data_tlv
->value
, cdol_data_tlv
->len
, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
391 // free(cdol_data_tlv);
395 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
401 TLVPrintFromBuffer(buf
, len
);
406 int CmdHFEMVGenerateChallenge(const char *cmd
) {
408 CLIParserInit("hf emv challenge",
409 "Executes Generate Challenge command. It returns 4 or 8-byte random number from card.\nNeeds a EMV applet to be selected and GPO to be executed.",
410 "Usage:\n\thf emv challenge -> get challenge\n\thf emv challenge -k -> get challenge, keep fileld ON\n");
414 arg_lit0("kK", "keep", "keep field ON for next command"),
415 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
418 CLIExecWithReturn(cmd
, argtable
, true);
420 bool leaveSignalON
= arg_get_lit(1);
421 bool APDULogging
= arg_get_lit(2);
424 SetAPDULogging(APDULogging
);
427 uint8_t buf
[APDU_RES_LEN
] = {0};
430 int res
= EMVGenerateChallenge(leaveSignalON
, buf
, sizeof(buf
), &len
, &sw
, NULL
);
433 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
438 PrintAndLog("Challenge: %s", sprint_hex(buf
, len
));
440 if (len
!= 4 && len
!= 8)
441 PrintAndLog("WARNING: length of challenge must be 4 or 8, but it %d", len
);
446 int CmdHFEMVInternalAuthenticate(const char *cmd
) {
447 uint8_t data
[APDU_RES_LEN
] = {0};
450 CLIParserInit("hf emv intauth",
451 "Generate Internal Authenticate command. Usually needs 4-byte random number. It returns data in TLV format .\nNeeds a EMV applet to be selected and GPO to be executed.",
452 "Usage:\n\thf emv intauth -k 01020304 -> execute Internal Authenticate with 4-byte DDOLdata and keep field ON after command\n"
453 "\thf emv intauth -t 01020304 -> execute Internal Authenticate with 4-byte DDOL data, show result in TLV\n");
457 arg_lit0("kK", "keep", "keep field ON for next command"),
458 arg_lit0("aA", "apdu", "show APDU reqests and responses"),
459 arg_lit0("tT", "tlv", "TLV decode results of selected applets"),
460 arg_str1(NULL
, NULL
, "<HEX DDOLdata>", NULL
),
463 CLIExecWithReturn(cmd
, argtable
, false);
465 bool leaveSignalON
= arg_get_lit(1);
466 bool APDULogging
= arg_get_lit(2);
467 bool decodeTLV
= arg_get_lit(3);
468 CLIGetStrWithReturn(4, data
, &datalen
);
471 SetAPDULogging(APDULogging
);
474 PrintAndLog("DDOL data[%d]: %s", datalen
, sprint_hex(data
, datalen
));
477 uint8_t buf
[APDU_RES_LEN
] = {0};
480 int res
= EMVInternalAuthenticate(leaveSignalON
, data
, datalen
, buf
, sizeof(buf
), &len
, &sw
, NULL
);
483 PrintAndLog("APDU response status: %04x - %s", sw
, GetAPDUCodeDescription(sw
>> 8, sw
& 0xff));
489 TLVPrintFromBuffer(buf
, len
);
494 #define dreturn(n) {free(pdol_data_tlv);tlvdb_free(tlvSelect);tlvdb_free(tlvRoot);DropField();return n;}
496 bool HexToBuffer(const char *errormsg
, const char *hexvalue
, uint8_t * buffer
, size_t maxbufferlen
, size_t *bufferlen
) {
499 switch(param_gethex_to_eol(hexvalue
, 0, buffer
, maxbufferlen
, &buflen
)) {
501 PrintAndLog("%s Invalid HEX value.", errormsg
);
504 PrintAndLog("%s Hex value too large.", errormsg
);
507 PrintAndLog("%s Hex value must have even number of digits.", errormsg
);
511 if (buflen
> maxbufferlen
) {
512 PrintAndLog("%s HEX length (%d) more than %d", errormsg
, *bufferlen
, maxbufferlen
);
521 bool ParamLoadFromJson(struct tlvdb
*tlv
) {
526 PrintAndLog("ERROR load params: tlv tree is NULL.");
530 // current path + file name
531 const char *relfname
= "emv/defparams.json";
532 char fname
[strlen(get_my_executable_directory()) + strlen(relfname
) + 1];
533 strcpy(fname
, get_my_executable_directory());
534 strcat(fname
, relfname
);
536 root
= json_load_file(fname
, 0, &error
);
538 PrintAndLog("Load params: json error on line %d: %s", error
.line
, error
.text
);
542 if (!json_is_array(root
)) {
543 PrintAndLog("Load params: Invalid json format. root must be array.");
547 PrintAndLog("Load params: json OK");
549 for(int i
= 0; i
< json_array_size(root
); i
++) {
550 json_t
*data
, *jtype
, *jlength
, *jvalue
;
552 data
= json_array_get(root
, i
);
553 if(!json_is_object(data
))
555 PrintAndLog("Load params: data [%d] is not an object", i
+ 1);
560 jtype
= json_object_get(data
, "type");
561 if(!json_is_string(jtype
))
563 PrintAndLog("Load params: data [%d] type is not a string", i
+ 1);
567 const char *tlvType
= json_string_value(jtype
);
569 jvalue
= json_object_get(data
, "value");
570 if(!json_is_string(jvalue
))
572 PrintAndLog("Load params: data [%d] value is not a string", i
+ 1);
576 const char *tlvValue
= json_string_value(jvalue
);
578 jlength
= json_object_get(data
, "length");
579 if(!json_is_number(jlength
))
581 PrintAndLog("Load params: data [%d] length is not a number", i
+ 1);
586 int tlvLength
= json_integer_value(jlength
);
587 if (tlvLength
> 250) {
588 PrintAndLog("Load params: data [%d] length more than 250", i
+ 1);
593 PrintAndLog("TLV param: %s[%d]=%s", tlvType
, tlvLength
, tlvValue
);
594 uint8_t buf
[251] = {0};
597 // here max length must be 4, but now tlv_tag_t is 2-byte var. so let it be 2 by now... TODO: needs refactoring tlv_tag_t...
598 if (!HexToBuffer("TLV Error type:", tlvType
, buf
, 2, &buflen
)) {
603 for (int i
= 0; i
< buflen
; i
++) {
604 tag
= (tag
<< 8) + buf
[i
];
607 if (!HexToBuffer("TLV Error value:", tlvValue
, buf
, sizeof(buf
) - 1, &buflen
)) {
612 if (buflen
!= tlvLength
) {
613 PrintAndLog("Load params: data [%d] length of HEX must(%d) be identical to length in TLV param(%d)", i
+ 1, buflen
, tlvLength
);
618 tlvdb_change_or_add_node(tlv
, tag
, tlvLength
, (const unsigned char *)buf
);
626 int CmdHFEMVExec(const char *cmd
) {
627 uint8_t buf
[APDU_RES_LEN
] = {0};
630 uint8_t AID
[APDU_AID_LEN
] = {0};
632 uint8_t ODAiList
[4096];
633 size_t ODAiListLen
= 0;
637 struct tlvdb
*tlvSelect
= NULL
;
638 struct tlvdb
*tlvRoot
= NULL
;
639 struct tlv
*pdol_data_tlv
= NULL
;
641 CLIParserInit("hf emv exec",
642 "Executes EMV contactless transaction",
643 "Usage:\n\thf emv exec -sat -> select card, execute MSD transaction, show APDU and TLV\n"
644 "\thf emv exec -satc -> select card, execute CDA transaction, show APDU and TLV\n");
648 arg_lit0("sS", "select", "activate field and select card."),
649 arg_lit0("aA", "apdu", "show APDU reqests and responses."),
650 arg_lit0("tT", "tlv", "TLV decode results."),
651 arg_lit0("jJ", "jload", "Load transaction parameters from `emv/defparams.json` file."),
652 arg_lit0("fF", "forceaid", "Force search AID. Search AID instead of execute PPSE."),
653 arg_rem("By default:", "Transaction type - MSD"),
654 arg_lit0("vV", "qvsdc", "Transaction type - qVSDC or M/Chip."),
655 arg_lit0("cC", "qvsdccda", "Transaction type - qVSDC or M/Chip plus CDA (SDAD generation)."),
656 arg_lit0("xX", "vsdc", "Transaction type - VSDC. For test only. Not a standart behavior."),
657 arg_lit0("gG", "acgpo", "VISA. generate AC from GPO."),
660 CLIExecWithReturn(cmd
, argtable
, true);
662 bool activateField
= arg_get_lit(1);
663 bool showAPDU
= arg_get_lit(2);
664 bool decodeTLV
= arg_get_lit(3);
665 bool paramLoadJSON
= arg_get_lit(4);
666 bool forceSearch
= arg_get_lit(5);
668 enum TransactionType TrType
= TT_MSD
;
670 TrType
= TT_QVSDCMCHIP
;
676 bool GenACGPO
= arg_get_lit(9);
679 SetAPDULogging(showAPDU
);
681 // init applets list tree
682 const char *al
= "Applets list";
683 tlvSelect
= tlvdb_fixed(1, strlen(al
), (const unsigned char *)al
);
685 // Application Selection
686 // https://www.openscdp.org/scripts/tutorial/emv/applicationselection.html
689 PrintAndLog("\n* PPSE.");
690 SetAPDULogging(showAPDU
);
691 res
= EMVSearchPSE(activateField
, true, decodeTLV
, tlvSelect
);
693 // check PPSE and select application id
695 TLVPrintAIDlistFromSelectTLV(tlvSelect
);
696 EMVSelectApplication(tlvSelect
, AID
, &AIDlen
);
702 PrintAndLog("\n* Search AID in list.");
703 SetAPDULogging(false);
704 if (EMVSearch(activateField
, true, decodeTLV
, tlvSelect
)) {
708 // check search and select application id
709 TLVPrintAIDlistFromSelectTLV(tlvSelect
);
710 EMVSelectApplication(tlvSelect
, AID
, &AIDlen
);
714 const char *alr
= "Root terminal TLV tree";
715 tlvRoot
= tlvdb_fixed(1, strlen(alr
), (const unsigned char *)alr
);
717 // check if we found EMV application on card
719 PrintAndLog("Can't select AID. EMV AID not found");
724 PrintAndLog("\n* Selecting AID:%s", sprint_hex_inrow(AID
, AIDlen
));
725 SetAPDULogging(showAPDU
);
726 res
= EMVSelect(false, true, AID
, AIDlen
, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
729 PrintAndLog("Can't select AID (%d). Exit...", res
);
734 TLVPrintFromBuffer(buf
, len
);
735 PrintAndLog("* Selected.");
737 PrintAndLog("\n* Init transaction parameters.");
739 ParamLoadDefaults(tlvRoot
);
742 PrintAndLog("* * Transaction parameters loading from JSON...");
743 ParamLoadFromJson(tlvRoot
);
746 //9F66:(Terminal Transaction Qualifiers (TTQ)) len:4
747 char *qVSDC
= "\x26\x00\x00\x00";
749 qVSDC
= "\x26\x80\x00\x00";
753 TLV_ADD(0x9F66, "\x86\x00\x00\x00"); // MSD
755 // not standard for contactless. just for test.
757 TLV_ADD(0x9F66, "\x46\x00\x00\x00"); // VSDC
760 TLV_ADD(0x9F66, qVSDC
); // qVSDC
763 TLV_ADD(0x9F66, qVSDC
); // qVSDC (VISA CDA not enabled)
769 TLVPrintFromTLV(tlvRoot
); // TODO delete!!!
771 PrintAndLog("\n* Calc PDOL.");
772 pdol_data_tlv
= dol_process(tlvdb_get(tlvRoot
, 0x9f38, NULL
), tlvRoot
, 0x83);
774 PrintAndLog("ERROR: can't create PDOL TLV.");
778 size_t pdol_data_tlv_data_len
;
779 unsigned char *pdol_data_tlv_data
= tlv_encode(pdol_data_tlv
, &pdol_data_tlv_data_len
);
780 if (!pdol_data_tlv_data
) {
781 PrintAndLog("ERROR: can't create PDOL data.");
784 PrintAndLog("PDOL data[%d]: %s", pdol_data_tlv_data_len
, sprint_hex(pdol_data_tlv_data
, pdol_data_tlv_data_len
));
786 PrintAndLog("\n* GPO.");
787 res
= EMVGPO(true, pdol_data_tlv_data
, pdol_data_tlv_data_len
, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
789 free(pdol_data_tlv_data
);
790 //free(pdol_data_tlv); --- free on exit.
793 PrintAndLog("GPO error(%d): %4x. Exit...", res
, sw
);
797 // process response template format 1 [id:80 2b AIP + x4b AFL] and format 2 [id:77 TLV]
798 if (buf
[0] == 0x80) {
800 PrintAndLog("GPO response format1:");
801 TLVPrintFromBuffer(buf
, len
);
804 if (len
< 4 || (len
- 4) % 4) {
805 PrintAndLog("ERROR: GPO response format1 parsing error. length=%d", len
);
808 struct tlvdb
* f1AIP
= tlvdb_fixed(0x82, 2, buf
+ 2);
809 tlvdb_add(tlvRoot
, f1AIP
);
811 PrintAndLog("\n* * Decode response format 1 (0x80) AIP and AFL:");
812 TLVPrintFromTLV(f1AIP
);
816 struct tlvdb
* f1AFL
= tlvdb_fixed(0x94, len
- 4, buf
+ 2 + 2);
817 tlvdb_add(tlvRoot
, f1AFL
);
819 TLVPrintFromTLV(f1AFL
);
823 TLVPrintFromBuffer(buf
, len
);
826 // extract PAN from track2
828 const struct tlv
*track2
= tlvdb_get(tlvRoot
, 0x57, NULL
);
829 if (!tlvdb_get(tlvRoot
, 0x5a, NULL
) && track2
&& track2
->len
>= 8) {
830 struct tlvdb
*pan
= GetPANFromTrack2(track2
);
832 tlvdb_add(tlvRoot
, pan
);
834 const struct tlv
*pantlv
= tlvdb_get(tlvRoot
, 0x5a, NULL
);
835 PrintAndLog("\n* * Extracted PAN from track2: %s", sprint_hex(pantlv
->value
, pantlv
->len
));
837 PrintAndLog("\n* * WARNING: Can't extract PAN from track2.");
842 PrintAndLog("\n* Read records from AFL.");
843 const struct tlv
*AFL
= tlvdb_get(tlvRoot
, 0x94, NULL
);
844 if (!AFL
|| !AFL
->len
) {
845 PrintAndLog("WARNING: AFL not found.");
848 while(AFL
&& AFL
->len
) {
850 PrintAndLog("ERROR: Wrong AFL length: %d", AFL
->len
);
854 for (int i
= 0; i
< AFL
->len
/ 4; i
++) {
855 uint8_t SFI
= AFL
->value
[i
* 4 + 0] >> 3;
856 uint8_t SFIstart
= AFL
->value
[i
* 4 + 1];
857 uint8_t SFIend
= AFL
->value
[i
* 4 + 2];
858 uint8_t SFIoffline
= AFL
->value
[i
* 4 + 3];
860 PrintAndLog("* * SFI[%02x] start:%02x end:%02x offline:%02x", SFI
, SFIstart
, SFIend
, SFIoffline
);
861 if (SFI
== 0 || SFI
== 31 || SFIstart
== 0 || SFIstart
> SFIend
) {
862 PrintAndLog("SFI ERROR! Skipped...");
866 for(int n
= SFIstart
; n
<= SFIend
; n
++) {
867 PrintAndLog("* * * SFI[%02x] %d", SFI
, n
);
869 res
= EMVReadRecord(true, SFI
, n
, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
871 PrintAndLog("ERROR SFI[%02x]. APDU error %4x", SFI
, sw
);
876 TLVPrintFromBuffer(buf
, len
);
880 // Build Input list for Offline Data Authentication
881 // EMV 4.3 book3 10.3, page 96
884 const unsigned char *abuf
= buf
;
887 if (tlv_parse_tl(&abuf
, &elmlen
, &e
)) {
888 memcpy(&ODAiList
[ODAiListLen
], &buf
[len
- elmlen
], elmlen
);
889 ODAiListLen
+= elmlen
;
891 PrintAndLog("ERROR SFI[%02x]. Creating input list for Offline Data Authentication error.", SFI
);
894 memcpy(&ODAiList
[ODAiListLen
], buf
, len
);
904 // copy Input list for Offline Data Authentication
906 struct tlvdb
*oda
= tlvdb_fixed(0x21, ODAiListLen
, ODAiList
); // not a standard tag
907 tlvdb_add(tlvRoot
, oda
);
908 PrintAndLog("* Input list for Offline Data Authentication added to TLV. len=%d \n", ODAiListLen
);
912 const struct tlv
*AIPtlv
= tlvdb_get(tlvRoot
, 0x82, NULL
);
913 uint16_t AIP
= AIPtlv
->value
[0] + AIPtlv
->value
[1] * 0x100;
914 PrintAndLog("* * AIP=%04x", AIP
);
918 PrintAndLog("\n* SDA");
924 PrintAndLog("\n* DDA");
925 trDDA(decodeTLV
, tlvRoot
);
931 if (TrType
== TT_QVSDCMCHIP
|| TrType
== TT_CDA
){
932 // 9F26: Application Cryptogram
933 const struct tlv
*AC
= tlvdb_get(tlvRoot
, 0x9F26, NULL
);
935 PrintAndLog("\n--> qVSDC transaction.");
936 PrintAndLog("* AC path");
938 // 9F36: Application Transaction Counter (ATC)
939 const struct tlv
*ATC
= tlvdb_get(tlvRoot
, 0x9F36, NULL
);
942 // 9F10: Issuer Application Data - optional
943 const struct tlv
*IAD
= tlvdb_get(tlvRoot
, 0x9F10, NULL
);
946 PrintAndLog("ATC: %s", sprint_hex(ATC
->value
, ATC
->len
));
947 PrintAndLog("AC: %s", sprint_hex(AC
->value
, AC
->len
));
949 PrintAndLog("IAD: %s", sprint_hex(IAD
->value
, IAD
->len
));
951 if (IAD
->len
>= IAD
->value
[0] + 1) {
952 PrintAndLog("\tKey index: 0x%02x", IAD
->value
[1]);
953 PrintAndLog("\tCrypto ver: 0x%02x(%03d)", IAD
->value
[2], IAD
->value
[2]);
954 PrintAndLog("\tCVR:", sprint_hex(&IAD
->value
[3], IAD
->value
[0] - 2));
955 struct tlvdb
* cvr
= tlvdb_fixed(0x20, IAD
->value
[0] - 2, &IAD
->value
[3]);
956 TLVPrintFromTLVLev(cvr
, 1);
959 PrintAndLog("WARNING: IAD not found.");
963 PrintAndLog("ERROR AC: Application Transaction Counter (ATC) not found.");
969 if (GetCardPSVendor(AID
, AIDlen
) == CV_MASTERCARD
&& (TrType
== TT_QVSDCMCHIP
|| TrType
== TT_CDA
)){
970 const struct tlv
*CDOL1
= tlvdb_get(tlvRoot
, 0x8c, NULL
);
971 if (CDOL1
&& GetCardPSVendor(AID
, AIDlen
) == CV_MASTERCARD
) { // and m/chip transaction flag
972 PrintAndLog("\n--> Mastercard M/Chip transaction.");
974 PrintAndLog("* * Generate challenge");
975 res
= EMVGenerateChallenge(true, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
977 PrintAndLog("ERROR GetChallenge. APDU error %4x", sw
);
981 PrintAndLog("ERROR GetChallenge. Wrong challenge length %d", len
);
985 // ICC Dynamic Number
986 struct tlvdb
* ICCDynN
= tlvdb_fixed(0x9f4c, len
, buf
);
987 tlvdb_add(tlvRoot
, ICCDynN
);
989 PrintAndLog("\n* * ICC Dynamic Number:");
990 TLVPrintFromTLV(ICCDynN
);
993 PrintAndLog("* * Calc CDOL1");
994 struct tlv
*cdol_data_tlv
= dol_process(tlvdb_get(tlvRoot
, 0x8c, NULL
), tlvRoot
, 0x01); // 0x01 - dummy tag
996 PrintAndLog("ERROR: can't create CDOL1 TLV.");
999 PrintAndLog("CDOL1 data[%d]: %s", cdol_data_tlv
->len
, sprint_hex(cdol_data_tlv
->value
, cdol_data_tlv
->len
));
1001 PrintAndLog("* * AC1");
1002 // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD
1003 res
= EMVAC(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
);
1006 PrintAndLog("AC1 error(%d): %4x. Exit...", res
, sw
);
1011 TLVPrintFromBuffer(buf
, len
);
1014 PrintAndLog("\n* CDA:");
1015 struct tlvdb
*ac_tlv
= tlvdb_parse_multi(buf
, len
);
1016 res
= trCDA(tlvRoot
, ac_tlv
, pdol_data_tlv
, cdol_data_tlv
);
1018 PrintAndLog("CDA error (%d)", res
);
1021 free(cdol_data_tlv
);
1023 PrintAndLog("\n* M/Chip transaction result:");
1024 // 9F27: Cryptogram Information Data (CID)
1025 const struct tlv
*CID
= tlvdb_get(tlvRoot
, 0x9F27, NULL
);
1027 emv_tag_dump(CID
, stdout
, 0);
1028 PrintAndLog("------------------------------");
1030 switch(CID
->value
[0] & EMVAC_AC_MASK
){
1032 PrintAndLog("Transaction DECLINED.");
1035 PrintAndLog("Transaction approved OFFLINE.");
1038 PrintAndLog("Transaction approved ONLINE.");
1041 PrintAndLog("ERROR: CID transaction code error %2x", CID
->value
[0] & EMVAC_AC_MASK
);
1045 PrintAndLog("ERROR: Wrong CID length %d", CID
->len
);
1048 PrintAndLog("ERROR: CID(9F27) not found.");
1055 if (AIP
& 0x8000 && TrType
== TT_MSD
) {
1056 PrintAndLog("\n--> MSD transaction.");
1058 PrintAndLog("* MSD dCVV path. Check dCVV");
1060 const struct tlv
*track2
= tlvdb_get(tlvRoot
, 0x57, NULL
);
1062 PrintAndLog("Track2: %s", sprint_hex(track2
->value
, track2
->len
));
1064 struct tlvdb
*dCVV
= GetdCVVRawFromTrack2(track2
);
1065 PrintAndLog("dCVV raw data:");
1066 TLVPrintFromTLV(dCVV
);
1068 if (GetCardPSVendor(AID
, AIDlen
) == CV_MASTERCARD
) {
1069 PrintAndLog("\n* Mastercard calculate UDOL");
1072 const struct tlv
*UDOL
= tlvdb_get(tlvRoot
, 0x9F69, NULL
);
1073 // UDOL(9F69) default: 9F6A (Unpredictable number) 4 bytes
1074 const struct tlv defUDOL
= {
1077 .value
= (uint8_t *)"\x9f\x6a\x04",
1080 PrintAndLog("Use default UDOL.");
1082 struct tlv
*udol_data_tlv
= dol_process(UDOL
? UDOL
: &defUDOL
, tlvRoot
, 0x01); // 0x01 - dummy tag
1083 if (!udol_data_tlv
){
1084 PrintAndLog("ERROR: can't create UDOL TLV.");
1088 PrintAndLog("UDOL data[%d]: %s", udol_data_tlv
->len
, sprint_hex(udol_data_tlv
->value
, udol_data_tlv
->len
));
1090 PrintAndLog("\n* Mastercard compute cryptographic checksum(UDOL)");
1092 res
= MSCComputeCryptoChecksum(true, (uint8_t *)udol_data_tlv
->value
, udol_data_tlv
->len
, buf
, sizeof(buf
), &len
, &sw
, tlvRoot
);
1094 PrintAndLog("ERROR Compute Crypto Checksum. APDU error %4x", sw
);
1095 free(udol_data_tlv
);
1100 TLVPrintFromBuffer(buf
, len
);
1103 free(udol_data_tlv
);
1107 PrintAndLog("ERROR MSD: Track2 data not found.");
1115 free(pdol_data_tlv
);
1116 tlvdb_free(tlvSelect
);
1117 tlvdb_free(tlvRoot
);
1119 PrintAndLog("\n* Transaction completed.");
1124 int UsageCmdHFEMVScan(void) {
1125 PrintAndLog("HELP : Scan EMV card and save it contents to a file. \n");
1126 PrintAndLog(" It executes EMV contactless transaction and saves result to a file which can be used for emulation.\n");
1127 PrintAndLog("Usage: hf emv scan [-a][-t][-v][-c][-x][-g] <file_name>\n");
1128 PrintAndLog(" Options:");
1129 PrintAndLog(" -a : show APDU reqests and responses\n");
1130 PrintAndLog(" -t : TLV decode results\n");
1131 PrintAndLog(" -v : transaction type - qVSDC or M/Chip.\n");
1132 PrintAndLog(" -c : transaction type - qVSDC or M/Chip plus CDA (SDAD generation).\n");
1133 PrintAndLog(" -x : transaction type - VSDC. For test only. Not a standart behavior.\n");
1134 PrintAndLog(" -g : VISA. generate AC from GPO\n");
1135 PrintAndLog("By default : transaction type - MSD.\n");
1136 PrintAndLog("Samples:");
1137 PrintAndLog(" hf emv scan -a -t -> scan MSD transaction mode");
1138 PrintAndLog(" hf emv scan -a -t -c -> scan CDA transaction mode");
1142 int CmdHFEMVScan(const char *cmd
) {
1143 UsageCmdHFEMVScan();
1148 int CmdHFEMVTest(const char *cmd
) {
1149 return ExecuteCryptoTests(true);
1152 int CmdHelp(const char *Cmd
);
1153 static command_t CommandTable
[] = {
1154 {"help", CmdHelp
, 1, "This help"},
1155 {"exec", CmdHFEMVExec
, 0, "Executes EMV contactless transaction."},
1156 {"pse", CmdHFEMVPPSE
, 0, "Execute PPSE. It selects 2PAY.SYS.DDF01 or 1PAY.SYS.DDF01 directory."},
1157 {"search", CmdHFEMVSearch
, 0, "Try to select all applets from applets list and print installed applets."},
1158 {"select", CmdHFEMVSelect
, 0, "Select applet."},
1159 {"gpo", CmdHFEMVGPO
, 0, "Execute GetProcessingOptions."},
1160 {"readrec", CmdHFEMVReadRecord
, 0, "Read files from card."},
1161 {"genac", CmdHFEMVAC
, 0, "Generate ApplicationCryptogram."},
1162 {"challenge", CmdHFEMVGenerateChallenge
, 0, "Generate challenge."},
1163 {"intauth", CmdHFEMVInternalAuthenticate
, 0, "Internal authentication."},
1164 // {"scan", CmdHFEMVScan, 0, "Scan EMV card and save it contents to json file for emulator."},
1165 {"test", CmdHFEMVTest
, 0, "Crypto logic test."},
1166 {NULL
, NULL
, 0, NULL
}
1169 int CmdHFEMV(const char *Cmd
) {
1170 CmdsParse(CommandTable
, Cmd
);
1174 int CmdHelp(const char *Cmd
) {
1175 CmdsHelp(CommandTable
);