+int CmdHFEMVScan(const char *cmd) {
+ uint8_t AID[APDU_AID_LEN] = {0};
+ size_t AIDlen = 0;
+ uint8_t buf[APDU_RES_LEN] = {0};
+ size_t len = 0;
+ uint16_t sw = 0;
+ int res;
+ json_t *root;
+ json_error_t error;
+
+ CLIParserInit("hf emv scan",
+ "Scan EMV card and save it contents to a file.",
+ "It executes EMV contactless transaction and saves result to a file which can be used for emulation\n"
+ "Usage:\n\thf emv scan -at -> scan MSD transaction mode and show APDU and TLV\n"
+ "\thf emv scan -c -> scan CDA transaction mode\n");
+
+ void* argtable[] = {
+ arg_param_begin,
+ arg_lit0("aA", "apdu", "show APDU reqests and responses."),
+ arg_lit0("tT", "tlv", "TLV decode results."),
+ arg_lit0("eE", "extract", "Extract TLV elements and fill Application Data"),
+ arg_lit0("jJ", "jload", "Load transaction parameters from `emv/defparams.json` file."),
+ arg_rem("By default:", "Transaction type - MSD"),
+ arg_lit0("vV", "qvsdc", "Transaction type - qVSDC or M/Chip."),
+ arg_lit0("cC", "qvsdccda", "Transaction type - qVSDC or M/Chip plus CDA (SDAD generation)."),
+ arg_lit0("xX", "vsdc", "Transaction type - VSDC. For test only. Not a standart behavior."),
+ arg_lit0("gG", "acgpo", "VISA. generate AC from GPO."),
+ arg_lit0("mM", "merge", "Merge output file with card's data. (warning: the file may be corrupted!)"),
+ arg_str1(NULL, NULL, "output.json", "JSON output file name"),
+ arg_param_end
+ };
+ CLIExecWithReturn(cmd, argtable, true);
+
+ bool showAPDU = arg_get_lit(1);
+ bool decodeTLV = arg_get_lit(2);
+ bool extractTLVElements = arg_get_lit(3);
+ bool paramLoadJSON = arg_get_lit(4);
+
+ enum TransactionType TrType = TT_MSD;
+ if (arg_get_lit(6))
+ TrType = TT_QVSDCMCHIP;
+ if (arg_get_lit(7))
+ TrType = TT_CDA;
+ if (arg_get_lit(8))
+ TrType = TT_VSDC;
+
+ bool GenACGPO = arg_get_lit(9);
+ bool MergeJSON = arg_get_lit(10);
+ uint8_t relfname[250] ={0};
+ char *crelfname = (char *)relfname;
+ int relfnamelen = 0;
+ CLIGetStrWithReturn(11, relfname, &relfnamelen);
+ CLIParserFree();
+
+ SetAPDULogging(showAPDU);
+
+ // current path + file name
+ if (!strstr(crelfname, ".json"))
+ strcat(crelfname, ".json");
+ char fname[strlen(get_my_executable_directory()) + strlen(crelfname) + 1];
+ strcpy(fname, get_my_executable_directory());
+ strcat(fname, crelfname);
+
+ if (MergeJSON) {
+ root = json_load_file(fname, 0, &error);
+ if (!root) {
+ PrintAndLog("ERROR: json error on line %d: %s", error.line, error.text);
+ return 1;
+ }
+
+ if (!json_is_object(root)) {
+ PrintAndLog("ERROR: Invalid json format. root must be an object.");
+ return 1;
+ }
+ } else {
+ root = json_object();
+ }
+
+ // drop field at start
+ DropField();
+
+ // iso 14443 select
+ PrintAndLog("--> GET UID, ATS.");
+
+ iso14a_card_select_t card;
+ if (Hf14443_4aGetCardData(&card)) {
+ return 2;
+ }
+
+ JsonSaveStr(root, "$.File.Created", "proxmark3 `hf emv scan`");
+
+ JsonSaveStr(root, "$.Card.Communication", "iso14443-4a");
+ JsonSaveBufAsHex(root, "$.Card.UID", (uint8_t *)&card.uid, card.uidlen);
+ JsonSaveHex(root, "$.Card.ATQA", card.atqa[0] + (card.atqa[1] << 2), 2);
+ JsonSaveHex(root, "$.Card.SAK", card.sak, 0);
+ JsonSaveBufAsHex(root, "$.Card.ATS", (uint8_t *)card.ats, card.ats_len);
+
+ // init applets list tree
+ const char *al = "Applets list";
+ struct tlvdb *tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al);
+
+ // EMV PPSE
+ PrintAndLog("--> PPSE.");
+ res = EMVSelectPSE(true, true, 2, buf, sizeof(buf), &len, &sw);
+
+ if (!res && sw == 0x9000){
+ if (decodeTLV)
+ TLVPrintFromBuffer(buf, len);
+
+ JsonSaveBufAsHex(root, "$.PPSE.AID", (uint8_t *)"2PAY.SYS.DDF01", 14);
+
+ struct tlvdb *fci = tlvdb_parse_multi(buf, len);
+ if (extractTLVElements)
+ JsonSaveTLVTree(root, root, "$.PPSE.FCITemplate", fci);
+ else
+ JsonSaveTLVTreeElm(root, "$.PPSE.FCITemplate", fci, true, true, false);
+ JsonSaveTLVValue(root, "$.Application.KernelID", tlvdb_find_full(fci, 0x9f2a));
+ tlvdb_free(fci);
+ }
+
+ res = EMVSearchPSE(false, true, decodeTLV, tlvSelect);
+
+ // check PPSE and select application id
+ if (!res) {
+ TLVPrintAIDlistFromSelectTLV(tlvSelect);
+ } else {
+ // EMV SEARCH with AID list
+ SetAPDULogging(false);
+ PrintAndLog("--> AID search.");
+ if (EMVSearch(false, true, decodeTLV, tlvSelect)) {
+ PrintAndLog("E->Can't found any of EMV AID. Exit...");
+ tlvdb_free(tlvSelect);
+ DropField();
+ return 3;
+ }
+
+ // check search and select application id
+ TLVPrintAIDlistFromSelectTLV(tlvSelect);
+ }
+
+ // EMV SELECT application
+ SetAPDULogging(showAPDU);
+ EMVSelectApplication(tlvSelect, AID, &AIDlen);
+
+ tlvdb_free(tlvSelect);
+
+ if (!AIDlen) {
+ PrintAndLog("Can't select AID. EMV AID not found. Exit...");
+ DropField();
+ return 4;
+ }
+
+ JsonSaveBufAsHex(root, "$.Application.AID", AID, AIDlen);
+
+ // Init TLV tree
+ const char *alr = "Root terminal TLV tree";
+ struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr);
+
+ // EMV SELECT applet
+
+ PrintAndLog("\n-->Selecting AID:%s.", sprint_hex_inrow(AID, AIDlen));
+ SetAPDULogging(showAPDU);
+ res = EMVSelect(false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot);
+
+ if (res) {
+ PrintAndLog("E->Can't select AID (%d). Exit...", res);
+ tlvdb_free(tlvRoot);
+ DropField();
+ return 5;
+ }
+
+ if (decodeTLV)
+ TLVPrintFromBuffer(buf, len);
+
+ // save mode
+ if (tlvdb_get(tlvRoot, 0x9f38, NULL)) {
+ JsonSaveStr(root, "$.Application.Mode", TransactionTypeStr[TrType]);
+ }
+
+ struct tlvdb *fci = tlvdb_parse_multi(buf, len);
+ if (extractTLVElements)
+ JsonSaveTLVTree(root, root, "$.Application.FCITemplate", fci);
+ else
+ JsonSaveTLVTreeElm(root, "$.Application.FCITemplate", fci, true, true, false);
+ tlvdb_free(fci);
+
+ // create transaction parameters
+ PrintAndLog("-->Init transaction parameters.");
+ InitTransactionParameters(tlvRoot, paramLoadJSON, TrType, GenACGPO);
+
+ PrintAndLog("-->Calc PDOL.");
+ struct tlv *pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83);
+ if (!pdol_data_tlv){
+ PrintAndLog("E->Can't create PDOL TLV.");
+ tlvdb_free(tlvRoot);
+ DropField();
+ return 6;
+ }
+
+ size_t pdol_data_tlv_data_len;
+ unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len);
+ if (!pdol_data_tlv_data) {
+ PrintAndLog("E->Can't create PDOL data.");
+ tlvdb_free(tlvRoot);
+ DropField();
+ return 6;
+ }
+ PrintAndLog("PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len));
+
+ PrintAndLog("-->GPO.");
+ res = EMVGPO(true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot);
+
+ free(pdol_data_tlv_data);
+ free(pdol_data_tlv);
+
+ if (res) {
+ PrintAndLog("GPO error(%d): %4x. Exit...", res, sw);
+ tlvdb_free(tlvRoot);
+ DropField();
+ return 7;
+ }
+ ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV);
+
+ struct tlvdb *gpofci = tlvdb_parse_multi(buf, len);
+ if (extractTLVElements)
+ JsonSaveTLVTree(root, root, "$.Application.GPO", gpofci);
+ else
+ JsonSaveTLVTreeElm(root, "$.Application.GPO", gpofci, true, true, false);
+
+ JsonSaveTLVValue(root, "$.ApplicationData.AIP", tlvdb_find_full(gpofci, 0x82));
+ JsonSaveTLVValue(root, "$.ApplicationData.AFL", tlvdb_find_full(gpofci, 0x94));
+
+ tlvdb_free(gpofci);
+
+ PrintAndLog("-->Read records from AFL.");
+ const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL);
+
+ while(AFL && AFL->len) {
+ if (AFL->len % 4) {
+ PrintAndLog("E->Wrong AFL length: %d", AFL->len);
+ break;
+ }
+
+ json_t *sfijson = json_path_get(root, "$.Application.Records");
+ if (!sfijson) {
+ json_t *app = json_path_get(root, "$.Application");
+ json_object_set_new(app, "Records", json_array());
+
+ sfijson = json_path_get(root, "$.Application.Records");
+ }
+ if (!json_is_array(sfijson)) {
+ PrintAndLog("E->Internal logic error. `$.Application.Records` is not an array.");
+ break;
+ }
+ for (int i = 0; i < AFL->len / 4; i++) {
+ uint8_t SFI = AFL->value[i * 4 + 0] >> 3;
+ uint8_t SFIstart = AFL->value[i * 4 + 1];
+ uint8_t SFIend = AFL->value[i * 4 + 2];
+ uint8_t SFIoffline = AFL->value[i * 4 + 3];
+
+ PrintAndLog("--->SFI[%02x] start:%02x end:%02x offline:%02x", SFI, SFIstart, SFIend, SFIoffline);
+ if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) {
+ PrintAndLog("SFI ERROR! Skipped...");
+ continue;
+ }
+
+ for(int n = SFIstart; n <= SFIend; n++) {
+ PrintAndLog("---->SFI[%02x] %d", SFI, n);
+
+ res = EMVReadRecord(true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot);
+ if (res) {
+ PrintAndLog("E->SFI[%02x]. APDU error %4x", SFI, sw);
+ continue;
+ }
+
+ if (decodeTLV) {
+ TLVPrintFromBuffer(buf, len);
+ PrintAndLog("");
+ }
+
+ json_t *jsonelm = json_object();
+ json_array_append_new(sfijson, jsonelm);
+
+ JsonSaveHex(jsonelm, "SFI", SFI, 1);
+ JsonSaveHex(jsonelm, "RecordNum", n, 1);
+ JsonSaveHex(jsonelm, "Offline", SFIoffline, 1);
+
+ struct tlvdb *rsfi = tlvdb_parse_multi(buf, len);
+ if (extractTLVElements)
+ JsonSaveTLVTree(root, jsonelm, "$.Data", rsfi);
+ else
+ JsonSaveTLVTreeElm(jsonelm, "$.Data", rsfi, true, true, false);
+ tlvdb_free(rsfi);
+ }
+ }
+
+ break;
+ }
+
+ // getting certificates
+ if (tlvdb_get(tlvRoot, 0x90, NULL)) {
+ PrintAndLog("-->Recovering certificates.");
+ PKISetStrictExecution(false);
+ RecoveryCertificates(tlvRoot, root);
+ PKISetStrictExecution(true);
+ }
+
+ // free tlv object
+ tlvdb_free(tlvRoot);
+
+ // DropField
+ DropField();
+
+ res = json_dump_file(root, fname, JSON_INDENT(2));
+ if (res) {
+ PrintAndLog("ERROR: can't save the file: %s", fname);
+ return 200;
+ }
+ PrintAndLog("File `%s` saved.", fname);
+
+ // free json object
+ json_decref(root);
+
+ return 0;
+}
+
+int CmdHFEMVTest(const char *cmd) {
+ return ExecuteCryptoTests(true);
+}
+