From 9c320dc24151dcfbafb92d660b3ffa249040431f Mon Sep 17 00:00:00 2001
From: merlokk <807634+merlokk@users.noreply.github.com>
Date: Mon, 12 Jul 2021 18:45:59 +0300
Subject: [PATCH] getkeyversion works

---
 client/src/cmdhfmfdes.c               | 105 +++++++++++++++++++++++++-
 client/src/mifare/desfirecore.c       |   4 +-
 client/src/mifare/desfirecore.h       |   2 +-
 client/src/mifare/desfiresecurechan.c |   3 +
 4 files changed, 110 insertions(+), 4 deletions(-)

diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index ef87ab36a..4a760daeb 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -5201,8 +5201,10 @@ static int CmdHF14ADesChKeySettings(const char *Cmd) {
 
     uint32_t ksett32 = 0;
     res = arg_get_u32_hexstr_def_nlen(ctx, 12, 0x000000, &ksett32, 1, false);
-    if (res == 0)
+    if (res == 0) {
+        CLIParserFree(ctx);
         return PM3_ESOFT;
+    }
     if (res == 2) {
         PrintAndLogEx(ERR, "Key settings must have 1 byte length");
         CLIParserFree(ctx);
@@ -5237,6 +5239,107 @@ static int CmdHF14ADesChKeySettings(const char *Cmd) {
 }
 
 static int CmdHF14ADesGetKeyVersions(const char *Cmd) {
+    CLIParserContext *ctx;
+    CLIParserInit(&ctx, "hf mfdes getkeyversions",
+                  "Get key versions for card level or application level.",
+                  "hf mfdes getkeyversions  -> get picc key settings with default key/channel setup\n"\
+                  "hf mfdes getkeyversions --aid 123456 -> get app 123456 key settings with default key/channel setup");
+
+    void *argtable[] = {
+        arg_param_begin,
+        arg_lit0("a",  "apdu",    "show APDU requests and responses"),
+        arg_lit0("v",  "verbose", "show technical data"),
+        arg_int0("n",  "keyno",   "<keyno>", "Key number for authentication"),
+        arg_str0("t",  "algo",    "<DES/2TDEA/3TDEA/AES>",  "Crypt algo: DES, 2TDEA, 3TDEA, AES"),
+        arg_str0("k",  "key",     "<Key>",   "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"),
+        arg_str0("f",  "kdf",     "<none/AN10922/gallagher>",   "Key Derivation Function (KDF): None, AN10922, Gallagher"),
+        arg_str0("i",  "kdfi",    "<kdfi>",  "KDF input (HEX 1-31 bytes)"),
+        arg_str0("m",  "cmode",   "<plain/mac/encrypt>", "Communicaton mode: plain/mac/encrypt"),
+        arg_str0("c",  "ccset",   "<native/niso/iso>", "Communicaton command set: native/niso/iso"),
+        arg_str0("s",  "schann",  "<d40/ev1/ev2>", "Secure channel: d40/ev1/ev2"),
+        arg_str0(NULL, "aid",     "<app id hex>", "Application ID (3 hex bytes, big endian)"),
+        arg_str0(NULL, "keynum",  "<key number HEX>", "Key number (HEX 1 byte). App level: 00..0d - key num, 21..23 vc keys. PICC level: key number, default 0x00."),
+        arg_str0(NULL, "keyset",  "<keyset num HEX>", "Keyset number (HEX 1 byte)"),
+        arg_param_end
+    };
+    CLIExecWithReturn(ctx, Cmd, argtable, true);
+
+    bool APDULogging = arg_get_lit(ctx, 1);
+    bool verbose = arg_get_lit(ctx, 2);
+
+    DesfireContext dctx;
+    int securechann = defaultSecureChannel;
+    uint32_t appid = 0x000000;
+    int res = CmdDesGetSessionParameters(ctx, &dctx, 3, 4, 5, 6, 7, 8, 9, 10, 11, &securechann, DCMPlain, &appid); // DCMMACed
+    if (res) {
+        CLIParserFree(ctx);
+        return res;
+    }
+
+    uint32_t keynum32 = 0x00;
+    res = arg_get_u32_hexstr_def_nlen(ctx, 12, 0x00, &keynum32, 1, false);
+    if (res == 0) {
+        keynum32 = 0x00;
+    }
+    if (res == 2) {
+        PrintAndLogEx(ERR, "Key number must have 1 byte length");
+        CLIParserFree(ctx);
+        return PM3_EINVARG;
+    }
+
+    uint32_t keysetnum32 = 0x00;
+    bool keysetpresent = true;
+    res = arg_get_u32_hexstr_def_nlen(ctx, 13, 0x00, &keysetnum32, 1, false);
+    if (res == 0) {
+        keysetpresent = false;
+    }
+    if (res == 2) {
+        PrintAndLogEx(ERR, "Keyset number must have 1 byte length");
+        CLIParserFree(ctx);
+        return PM3_EINVARG;
+    }
+
+    if (keysetpresent && appid == 0x000000) {
+        PrintAndLogEx(WARNING, "Keyset only at Application level");
+        keysetpresent = false;
+    }
+
+    SetAPDULogging(APDULogging);
+    CLIParserFree(ctx);
+
+    res = DesfireSelectAndAuthenticate(&dctx, securechann, appid, verbose);
+    if (res != PM3_SUCCESS) {
+        DropField();
+        return res;
+    }
+
+    uint8_t buf[APDU_RES_LEN] = {0};
+    size_t buflen = 0;
+    
+    uint8_t data[2] = {0};
+    data[0] = keynum32 & 0xff;
+    if (keysetpresent) {
+        data[0] |= 0x40;
+        data[1] = keysetnum32 & 0xff;
+    }
+
+    res = DesfireGetKeyVersion(&dctx, data, (keysetpresent) ? 2 : 1, buf, &buflen);
+    if (res != PM3_SUCCESS) {
+        PrintAndLogEx(ERR, "Desfire DesfireGetKeyVersion command " _RED_("error") ". Result: %d", res);
+        DropField();
+        return PM3_ESOFT;
+    }
+
+    if (verbose)
+        PrintAndLogEx(INFO, "DesfireGetKeyVersion[%zu]: %s", buflen, sprint_hex(buf, buflen));
+
+    if (buflen > 0) {
+        PrintAndLogEx(INFO, "----------------------- " _CYAN_("Key Versions") " -----------------------");
+        for (int i = 0; i < buflen; i++)
+            PrintAndLogEx(INFO, "Key 0x%02x version 0x%02x", i, buf[i]);
+    } else {
+        PrintAndLogEx(INFO, "No key versions returned.");
+    }
     
     return PM3_SUCCESS;
 }
diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c
index 6eedd5ad1..e797d78b0 100644
--- a/client/src/mifare/desfirecore.c
+++ b/client/src/mifare/desfirecore.c
@@ -967,9 +967,9 @@ int DesfireGetKeySettings(DesfireContext *dctx, uint8_t *resp, size_t *resplen)
     return PM3_SUCCESS;
 }
 
-int DesfireGetKeyVersion(DesfireContext *dctx, uint8_t *resp, size_t *resplen) {
+int DesfireGetKeyVersion(DesfireContext *dctx, uint8_t *data, size_t len, uint8_t *resp, size_t *resplen) {
     uint8_t respcode = 0xff;
-    int res = DesfireExchange(dctx, MFDES_GET_KEY_VERSION, NULL, 0, &respcode, resp, resplen);
+    int res = DesfireExchange(dctx, MFDES_GET_KEY_VERSION, data, len, &respcode, resp, resplen);
     if (res != PM3_SUCCESS)
         return res;
     if (respcode != MFDES_S_OPERATION_OK)
diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h
index 9a31a53e9..4fd55909c 100644
--- a/client/src/mifare/desfirecore.h
+++ b/client/src/mifare/desfirecore.h
@@ -47,7 +47,7 @@ int DesfireGetDFList(DesfireContext *dctx, uint8_t *resp, size_t *resplen);
 int DesfireCreateApplication(DesfireContext *dctx, uint8_t *appdata, size_t appdatalen);
 int DesfireDeleteApplication(DesfireContext *dctx, uint32_t aid);
 
-int DesfireGetKeyVersion(DesfireContext *dctx, uint8_t *resp, size_t *resplen);
+int DesfireGetKeyVersion(DesfireContext *dctx, uint8_t *data, size_t len, uint8_t *resp, size_t *resplen);
 int DesfireGetKeySettings(DesfireContext *dctx, uint8_t *resp, size_t *resplen);
 int DesfireChangeKeySettings(DesfireContext *dctx, uint8_t *data, size_t len);
 void PrintKeySettings(uint8_t keysettings, uint8_t numkeys, bool applevel, bool print2ndbyte);
diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c
index ce24b22d2..c60ef1bb6 100644
--- a/client/src/mifare/desfiresecurechan.c
+++ b/client/src/mifare/desfiresecurechan.c
@@ -29,6 +29,7 @@ AllowedChannelModesS AllowedChannelModes[] = {
     {MFDES_GET_APPLICATION_IDS,   DACd40,  DCCNative,    DCMPlain},
     {MFDES_GET_DF_NAMES,          DACd40,  DCCNative,    DCMPlain},
     {MFDES_GET_KEY_SETTINGS,      DACd40,  DCCNative,    DCMPlain},
+    {MFDES_GET_KEY_VERSION,       DACd40,  DCCNative,    DCMPlain},
 
     {MFDES_READ_DATA,             DACd40,  DCCNative,    DCMMACed},
     {MFDES_WRITE_DATA,            DACd40,  DCCNative,    DCMMACed},
@@ -50,6 +51,8 @@ AllowedChannelModesS AllowedChannelModes[] = {
     {MFDES_READ_DATA,             DACd40,  DCCNative,    DCMEncrypted},
     {MFDES_WRITE_DATA,            DACd40,  DCCNative,    DCMEncrypted},
 
+    {MFDES_GET_KEY_VERSION,       DACEV1,  DCCNative,    DCMPlain},
+
     {MFDES_CREATE_APPLICATION,    DACEV1,  DCCNative,    DCMMACed},
     {MFDES_DELETE_APPLICATION,    DACEV1,  DCCNative,    DCMMACed},
     {MFDES_GET_APPLICATION_IDS,   DACEV1,  DCCNative,    DCMMACed},