+
+static int WriteBlock(uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_credit_key, bool elite, bool rawkey, bool NRMAC_replay, bool verbose) {
+
+ uint8_t MAC[4] = {0x00,0x00,0x00,0x00};
+ uint8_t div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t CSN[8];
+
+ if (!iClass_select(CSN, verbose, true, true) || !iClass_authenticate(CSN, KEY, MAC, div_key, use_credit_key, elite, rawkey, NRMAC_replay, verbose)) {
+ DropField();
+ return 0;
+ }
+
+ UsbCommand resp;
+
+ Calc_wb_mac(blockno, bldata, div_key, MAC);
+
+ UsbCommand w = {CMD_ICLASS_WRITEBLOCK, {blockno}};
+ memcpy(w.d.asBytes, bldata, 8);
+ memcpy(w.d.asBytes + 8, MAC, 4);
+
+ clearCommandBuffer();
+ SendCommand(&w);
+ if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) {
+ PrintAndLog("Write Command execute timeout");
+ DropField();
+ return 0;
+ }
+ bool isOK = resp.arg[0];
+ if (!isOK) {
+ PrintAndLog("Write Block Failed");
+ DropField();
+ return 0;
+ }
+
+ PrintAndLog("Write Block Successful");
+ return 1;
+}
+
+
+static void usage_hf_iclass_writeblock(void) {
+ PrintAndLog("Options:");
+ PrintAndLog(" b <Block> : The block number as 2 hex symbols");
+ PrintAndLog(" d <data> : Set the Data to write as 16 hex symbols");
+ PrintAndLog(" k <Key> : Access Key as 16 hex symbols or 1 hex to select key from memory");
+ PrintAndLog(" c : If 'c' is specified, the key set is assumed to be the credit key\n");
+ PrintAndLog(" e : If 'e' is specified, elite computations applied to key");
+ PrintAndLog(" r : If 'r' is specified, no computations applied to key");
+ PrintAndLog(" o : override protection and allow modification of blocks 0...4");
+ PrintAndLog("Samples:");
+ PrintAndLog(" hf iclass writeblk b 0A d AAAAAAAAAAAAAAAA k 001122334455667B");
+ PrintAndLog(" hf iclass writeblk b 1B d AAAAAAAAAAAAAAAA k 001122334455667B c");
+ PrintAndLog(" hf iclass writeblk b 03 d AAAAAAAAAAAAAAAA k 001122334455667B c o");
+}
+
+
+static int CmdHFiClass_WriteBlock(const char *Cmd) {
+ uint8_t blockno = 0;
+ uint8_t bldata[8] = {0};
+ uint8_t KEY[8] = {0};
+ uint8_t keyNbr = 0;
+ uint8_t dataLen = 0;
+ char tempStr[50] = {0};
+ bool use_credit_key = false;
+ bool elite = false;
+ bool rawkey = false;
+ bool override_protection = false;
+ bool errors = false;
+ uint8_t cmdp = 0;
+
+ while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
+ switch(param_getchar(Cmd, cmdp)) {
+ case 'h':
+ case 'H':
+ usage_hf_iclass_writeblock();
+ return 0;
+ case 'b':
+ case 'B':
+ if (param_gethex(Cmd, cmdp+1, &blockno, 2)) {
+ PrintAndLog("Block No must include 2 HEX symbols\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'c':
+ case 'C':
+ use_credit_key = true;
+ cmdp++;
+ break;
+ case 'd':
+ case 'D':
+ if (param_gethex(Cmd, cmdp+1, bldata, 16)) {
+ PrintAndLog("Data must include 16 HEX symbols\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'e':
+ case 'E':
+ elite = true;
+ cmdp++;
+ break;
+ case 'k':
+ case 'K':
+ dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr));
+ if (dataLen == 16) {
+ errors = param_gethex(tempStr, 0, KEY, dataLen);
+ } else if (dataLen == 1) {
+ keyNbr = param_get8(Cmd, cmdp+1);
+ if (keyNbr < ICLASS_KEYS_MAX) {
+ memcpy(KEY, iClass_Key_Table[keyNbr], 8);
+ } else {
+ PrintAndLog("\nERROR: Credit KeyNbr is invalid\n");
+ errors = true;
+ }
+ } else {
+ PrintAndLog("\nERROR: Credit Key is incorrect length\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'r':
+ case 'R':
+ rawkey = true;
+ cmdp++;
+ break;
+ case 'o':
+ case 'O':
+ override_protection = true;
+ cmdp++;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
+ errors = true;
+ break;
+ }
+ if (errors) {
+ usage_hf_iclass_writeblock();
+ return 0;
+ }
+ }
+
+ if (elite && rawkey) {
+ PrintAndLog("You cannot combine the 'e' and 'r' options\n");
+ errors = true;
+ }
+
+ if (cmdp < 6) {
+ usage_hf_iclass_writeblock();
+ return 0;
+ }
+
+ if (blockno < 5) {
+ if (override_protection) {
+ PrintAndLog("Info: modifying keys, e-purse or configuration block.");
+ } else {
+ PrintAndLog("You are going to modify keys, e-purse or configuration block.");
+ PrintAndLog("You must add the 'o' (override) option to confirm that you know what you are doing");
+ return 0;
+ }
+ }
+
+ int ans = WriteBlock(blockno, bldata, KEY, use_credit_key, elite, rawkey, false, true);
+
+ DropField();
+ return ans;
+}
+
+
+static void usage_hf_iclass_clone(void) {
+ PrintAndLog("Usage: hf iclass clone f <tagfile.bin> b <first block> l <last block> k <KEY> c e|r o");
+ PrintAndLog("Options:");
+ PrintAndLog(" f <filename>: specify a filename to clone from");
+ PrintAndLog(" b <Block> : The first block to clone as 2 hex symbols");
+ PrintAndLog(" l <Last Blk>: The last block to clone as 2 hex symbols");
+ PrintAndLog(" k <Key> : Access Key as 16 hex symbols or 1 hex to select key from memory");
+ PrintAndLog(" c : If 'c' is specified, the key set is assumed to be the credit key\n");
+ PrintAndLog(" e : If 'e' is specified, elite computations applied to key");
+ PrintAndLog(" r : If 'r' is specified, no computations applied to key");
+ PrintAndLog(" o : override protection and allow modification of target blocks 0...4");
+ PrintAndLog("Samples:");
+ PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 06 l 1A k 1122334455667788 e");
+ PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 05 l 19 k 0");
+ PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 06 l 19 k 0 e");
+ PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 06 l 19 k 0 e");
+ PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 03 l 19 k 0 e o");
+}
+
+
+static int CmdHFiClassCloneTag(const char *Cmd) {
+ char filename[FILE_PATH_SIZE] = {0};
+ char tempStr[50]={0};
+ uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t keyNbr = 0;
+ uint8_t fileNameLen = 0;
+ uint8_t startblock = 0;
+ uint8_t endblock = 0;
+ uint8_t dataLen = 0;
+ bool use_credit_key = false;
+ bool elite = false;
+ bool rawkey = false;
+ bool override_protection = false;
+ bool errors = false;
+ uint8_t cmdp = 0;
+
+ while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
+ switch (param_getchar(Cmd, cmdp)) {
+ case 'h':
+ case 'H':
+ usage_hf_iclass_clone();
+ return 0;
+ case 'b':
+ case 'B':
+ if (param_gethex(Cmd, cmdp+1, &startblock, 2)) {
+ PrintAndLog("Start Block No must include 2 HEX symbols\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'c':
+ case 'C':
+ use_credit_key = true;
+ cmdp++;
+ break;
+ case 'e':
+ case 'E':
+ elite = true;
+ cmdp++;
+ break;
+ case 'f':
+ case 'F':
+ fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename));
+ if (fileNameLen < 1) {
+ PrintAndLog("No filename found after f");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'k':
+ case 'K':
+ dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr));
+ if (dataLen == 16) {
+ errors = param_gethex(tempStr, 0, KEY, dataLen);
+ } else if (dataLen == 1) {
+ keyNbr = param_get8(Cmd, cmdp+1);
+ if (keyNbr < ICLASS_KEYS_MAX) {
+ memcpy(KEY, iClass_Key_Table[keyNbr], 8);
+ } else {
+ PrintAndLog("\nERROR: Credit KeyNbr is invalid\n");
+ errors = true;
+ }
+ } else {
+ PrintAndLog("\nERROR: Credit Key is incorrect length\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'l':
+ case 'L':
+ if (param_gethex(Cmd, cmdp+1, &endblock, 2)) {
+ PrintAndLog("Last Block No must include 2 HEX symbols\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'r':
+ case 'R':
+ rawkey = true;
+ cmdp++;
+ break;
+ case 'o':
+ case 'O':
+ override_protection = true;
+ cmdp++;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
+ errors = true;
+ break;
+ }
+ if (errors) {
+ usage_hf_iclass_clone();
+ return 0;
+ }
+ }
+
+ if (cmdp < 8) {
+ usage_hf_iclass_clone();
+ return 0;
+ }
+
+ if (startblock < 5) {
+ if (override_protection) {
+ PrintAndLog("Info: modifying keys, e-purse or configuration block.");
+ } else {
+ PrintAndLog("You are going to modify keys, e-purse or configuration block.");
+ PrintAndLog("You must add the 'o' (override) option to confirm that you know what you are doing");
+ return 0;
+ }
+ }
+
+ if ((endblock - startblock + 1) * 12 > USB_CMD_DATA_SIZE) {
+ PrintAndLog("Trying to write too many blocks at once. Max: %d", USB_CMD_DATA_SIZE/12);
+ }
+
+ // file handling and reading
+ FILE *f;
+ f = fopen(filename,"rb");
+ if (!f) {
+ PrintAndLog("Failed to read from file '%s'", filename);
+ return 1;
+ }
+
+ uint8_t tag_data[USB_CMD_DATA_SIZE/12][8];
+ fseek(f, startblock*8, SEEK_SET);
+ for (int i = 0; i < endblock - startblock + 1; i++) {
+ if (fread(&tag_data[i], 1, 8, f) == 0 ) {
+ PrintAndLog("File reading error.");
+ fclose(f);
+ return 2;
+ }
+ }
+
+ uint8_t MAC[4] = {0x00, 0x00, 0x00, 0x00};
+ uint8_t div_key[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ uint8_t CSN[8];
+
+ if (!iClass_select(CSN, true, true, true) || !iClass_authenticate(CSN, KEY, MAC, div_key, use_credit_key, elite, rawkey, false, true)) {
+ DropField();
+ return 0;
+ }
+
+ UsbCommand w = {CMD_ICLASS_CLONE, {startblock, endblock}};
+ uint8_t *ptr;
+ // calculate MAC for every block we will write
+ for (int i = 0; i < endblock - startblock + 1; i++) {
+ Calc_wb_mac(startblock + i, tag_data[i], div_key, MAC);
+ ptr = w.d.asBytes + i * 12;
+ memcpy(ptr, tag_data[i], 8);
+ memcpy(ptr + 8, MAC, 4);
+ }
+
+ uint8_t p[12];
+ PrintAndLog("Cloning");
+ for (int i = 0; i < endblock - startblock + 1; i++){
+ memcpy(p, w.d.asBytes + (i * 12), 12);
+ PrintAndLog("Block |%02x| %02x%02x%02x%02x%02x%02x%02x%02x | MAC |%02x%02x%02x%02x|",
+ i + startblock, p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]);
+ }
+
+ UsbCommand resp;
+ SendCommand(&w);
+ if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) {
+ PrintAndLog("Command execute timeout");
+ DropField();
+ return 0;
+ }
+
+ DropField();
+ return 1;
+}
+
+
+static int ReadBlock(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, bool rawkey, bool NRMAC_replay, bool verbose, bool auth) {
+
+ uint8_t MAC[4]={0x00,0x00,0x00,0x00};
+ uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t CSN[8];
+
+ if (!iClass_select(CSN, verbose, true, true)) {
+ DropField();
+ return 0;
+ }
+
+ if (auth) {
+ if (!iClass_authenticate(CSN, KEY, MAC, div_key, (keyType==0x18), elite, rawkey, NRMAC_replay, verbose)) {
+ DropField();
+ return 0;
+ }
+ }
+
+ UsbCommand resp;
+ UsbCommand w = {CMD_ICLASS_READBLOCK, {blockno}};
+ clearCommandBuffer();
+ SendCommand(&w);
+ if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) {
+ PrintAndLog("Command execute timeout");
+ DropField();
+ return 0;
+ }
+ bool isOK = resp.arg[0];
+ if (!isOK) {
+ PrintAndLog("Read Block Failed");
+ DropField();
+ return 0;
+ }
+ //data read is stored in: resp.d.asBytes[0-15]
+ if (verbose)
+ PrintAndLog("Block %02X: %s\n",blockno, sprint_hex(resp.d.asBytes,8));
+
+ return 1;
+}
+
+
+static void usage_hf_iclass_readblock(void) {
+ PrintAndLog("Usage: hf iclass readblk b <Block> k <Key> [c] [e|r|n]\n");
+ PrintAndLog("Options:");
+ PrintAndLog(" b <Block> : The block number as 2 hex symbols");
+ PrintAndLog(" k <Key> : Access Key as 16 hex symbols or 1 hex to select key from memory");
+ PrintAndLog(" c : If 'c' is specified, the key set is assumed to be the credit key\n");
+ PrintAndLog(" e : If 'e' is specified, elite computations applied to key");
+ PrintAndLog(" r : If 'r' is specified, no computations applied to key");
+ PrintAndLog(" n : If 'n' is specified, <Key> specifies a NR/MAC pair which can be obtained by 'hf iclass snoop'");
+ PrintAndLog("Samples:");
+ PrintAndLog(" hf iclass readblk b 06 k 0011223344556677");
+ PrintAndLog(" hf iclass readblk b 1B k 0011223344556677 c");
+ PrintAndLog(" hf iclass readblk b 0A k 0");
+}
+
+
+static int CmdHFiClass_ReadBlock(const char *Cmd) {
+ uint8_t blockno=0;
+ uint8_t keyType = 0x88; //debit key
+ uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t keyNbr = 0;
+ uint8_t dataLen = 0;
+ char tempStr[50] = {0};
+ bool elite = false;
+ bool rawkey = false;
+ bool NRMAC_replay = false;
+ bool errors = false;
+ bool auth = false;
+ uint8_t cmdp = 0;
+
+ while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
+ switch (param_getchar(Cmd, cmdp)) {
+ case 'h':
+ case 'H':
+ usage_hf_iclass_readblock();
+ return 0;
+ case 'b':
+ case 'B':
+ if (param_gethex(Cmd, cmdp+1, &blockno, 2)) {
+ PrintAndLog("Block No must include 2 HEX symbols\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'c':
+ case 'C':
+ keyType = 0x18;
+ cmdp++;
+ break;
+ case 'e':
+ case 'E':
+ elite = true;
+ cmdp++;
+ break;
+ case 'k':
+ case 'K':
+ auth = true;
+ dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr));
+ if (dataLen == 16) {
+ errors = param_gethex(tempStr, 0, KEY, dataLen);
+ } else if (dataLen == 1) {
+ keyNbr = param_get8(Cmd, cmdp+1);
+ if (keyNbr < ICLASS_KEYS_MAX) {
+ memcpy(KEY, iClass_Key_Table[keyNbr], 8);
+ } else {
+ PrintAndLog("\nERROR: KeyNbr is invalid\n");
+ errors = true;
+ }
+ } else {
+ PrintAndLog("\nERROR: Key is incorrect length\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'r':
+ case 'R':
+ rawkey = true;
+ cmdp++;
+ break;
+ case 'n':
+ case 'N':
+ NRMAC_replay = true;
+ cmdp++;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
+ errors = true;
+ break;
+ }
+ }
+
+ if (elite + rawkey + NRMAC_replay > 1) {
+ PrintAndLog("You cannot combine the 'e', 'r', and 'n' options\n");
+ errors = true;
+ }
+
+ if (errors) {
+ usage_hf_iclass_readblock();
+ return 0;
+ }
+
+ if (cmdp < 2) {
+ usage_hf_iclass_readblock();
+ return 0;
+ }
+ if (!auth)
+ PrintAndLog("warning: no authentication used with read, only a few specific blocks can be read accurately without authentication.");
+
+ return ReadBlock(KEY, blockno, keyType, elite, rawkey, NRMAC_replay, true, auth);
+}
+
+
+static int CmdHFiClass_loclass(const char *Cmd) {
+ char opt = param_getchar(Cmd, 0);
+
+ if (strlen(Cmd)<1 || opt == 'h') {
+ PrintAndLog("Usage: hf iclass loclass [options]");
+ PrintAndLog("Options:");
+ PrintAndLog("h Show this help");
+ PrintAndLog("t Perform self-test");
+ PrintAndLog("f <filename> Bruteforce iclass dumpfile");
+ PrintAndLog(" An iclass dumpfile is assumed to consist of an arbitrary number of");
+ PrintAndLog(" malicious CSNs, and their protocol responses");
+ PrintAndLog(" The binary format of the file is expected to be as follows: ");
+ PrintAndLog(" <8 byte CSN><8 byte CC><4 byte NR><4 byte MAC>");
+ PrintAndLog(" <8 byte CSN><8 byte CC><4 byte NR><4 byte MAC>");
+ PrintAndLog(" <8 byte CSN><8 byte CC><4 byte NR><4 byte MAC>");
+ PrintAndLog(" ... totalling N*24 bytes");
+ return 0;
+ }
+ char fileName[255] = {0};
+ if(opt == 'f') {
+ if(param_getstr(Cmd, 1, fileName, sizeof(fileName)) > 0) {
+ return bruteforceFileNoKeys(fileName);
+ } else {
+ PrintAndLog("You must specify a filename");
+ }
+ } else if(opt == 't') {
+ int errors = testCipherUtils();
+ errors += testMAC();
+ errors += doKeyTests(0);
+ errors += testElite();
+ if(errors) {
+ prnlog("OBS! There were errors!!!");
+ }
+ return errors;
+ }
+
+ return 0;
+}
+
+
+static void usage_hf_iclass_readtagfile() {
+ PrintAndLog("Usage: hf iclass readtagfile <filename> [startblock] [endblock]");
+}
+
+
+static int CmdHFiClassReadTagFile(const char *Cmd) {
+ int startblock = 0;
+ int endblock = 0;
+ char tempnum[5];
+ FILE *f;
+ char filename[FILE_PATH_SIZE];
+ if (param_getstr(Cmd, 0, filename, sizeof(filename)) < 1) {
+ usage_hf_iclass_readtagfile();
+ return 0;
+ }
+ if (param_getstr(Cmd, 1, tempnum, sizeof(tempnum)) < 1)
+ startblock = 0;
+ else
+ sscanf(tempnum,"%d",&startblock);
+
+ if (param_getstr(Cmd,2, tempnum, sizeof(tempnum)) < 1)
+ endblock = 0;
+ else
+ sscanf(tempnum,"%d",&endblock);
+ // file handling and reading
+ f = fopen(filename,"rb");
+ if(!f) {
+ PrintAndLog("Failed to read from file '%s'", filename);
+ return 1;
+ }
+ fseek(f, 0, SEEK_END);
+ long fsize = ftell(f);
+ fseek(f, 0, SEEK_SET);
+
+ if ( fsize < 0 ) {
+ PrintAndLog("Error, when getting filesize");
+ fclose(f);
+ return 1;
+ }
+
+ uint8_t *dump = malloc(fsize);
+
+ size_t bytes_read = fread(dump, 1, fsize, f);
+ fclose(f);
+ uint8_t *csn = dump;
+ printf("------+--+-------------------------+\n");
+ printf("CSN |00| %s|\n", sprint_hex(csn, 8) );
+ // printIclassDumpInfo(dump);
+ printIclassDumpContents(dump,startblock,endblock,bytes_read);
+ free(dump);
+ return 0;
+}
+
+/*
+uint64_t xorcheck(uint64_t sdiv,uint64_t hdiv) {
+ uint64_t new_div = 0x00;
+ new_div ^= sdiv;
+ new_div ^= hdiv;
+ return new_div;
+}
+
+uint64_t hexarray_to_uint64(uint8_t *key) {
+ char temp[17];
+ uint64_t uint_key;
+ for (int i = 0;i < 8;i++)
+ sprintf(&temp[(i *2)],"%02X",key[i]);
+ temp[16] = '\0';
+ if (sscanf(temp,"%016" SCNx64,&uint_key) < 1)
+ return 0;
+ return uint_key;
+}
+*/
+
+
+//when told CSN, oldkey, newkey, if new key is elite (elite), and if old key was elite (oldElite)
+//calculate and return xor_div_key (ready for a key write command)
+//print all div_keys if verbose
+static void HFiClassCalcNewKey(uint8_t *CSN, uint8_t *OLDKEY, uint8_t *NEWKEY, uint8_t *xor_div_key, bool elite, bool oldElite, bool verbose){
+ uint8_t old_div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t new_div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ //get old div key
+ HFiClassCalcDivKey(CSN, OLDKEY, old_div_key, oldElite);
+ //get new div key
+ HFiClassCalcDivKey(CSN, NEWKEY, new_div_key, elite);
+
+ for (uint8_t i = 0; i < sizeof(old_div_key); i++){
+ xor_div_key[i] = old_div_key[i] ^ new_div_key[i];
+ }
+ if (verbose) {
+ printf("Old Div Key : %s\n",sprint_hex(old_div_key,8));
+ printf("New Div Key : %s\n",sprint_hex(new_div_key,8));
+ printf("Xor Div Key : %s\n",sprint_hex(xor_div_key,8));
+ }
+}
+
+
+static void usage_hf_iclass_calc_newkey(void) {
+ PrintAndLog("HELP : Manage iClass Keys in client memory:\n");
+ PrintAndLog("Usage: hf iclass calc_newkey o <Old key> n <New key> s [csn] e");
+ PrintAndLog(" Options:");
+ PrintAndLog(" o <oldkey> : *specify a key as 16 hex symbols or a key number as 1 symbol");
+ PrintAndLog(" n <newkey> : *specify a key as 16 hex symbols or a key number as 1 symbol");
+ PrintAndLog(" s <csn> : specify a card Serial number to diversify the key (if omitted will attempt to read a csn)");
+ PrintAndLog(" e : specify new key as elite calc");
+ PrintAndLog(" ee : specify old and new key as elite calc");
+ PrintAndLog("Samples:");
+ PrintAndLog(" e key to e key given csn : hf iclass calcnewkey o 1122334455667788 n 2233445566778899 s deadbeafdeadbeaf ee");
+ PrintAndLog(" std key to e key read csn: hf iclass calcnewkey o 1122334455667788 n 2233445566778899 e");
+ PrintAndLog(" std to std read csn : hf iclass calcnewkey o 1122334455667788 n 2233445566778899");
+ PrintAndLog("NOTE: * = required\n");
+}
+
+
+static int CmdHFiClassCalcNewKey(const char *Cmd) {
+ uint8_t OLDKEY[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t NEWKEY[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t xor_div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t CSN[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t keyNbr = 0;
+ uint8_t dataLen = 0;
+ char tempStr[50] = {0};
+ bool givenCSN = false;
+ bool oldElite = false;
+ bool elite = false;
+ bool errors = false;
+ uint8_t cmdp = 0;
+
+ while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
+ switch(param_getchar(Cmd, cmdp)) {
+ case 'h':
+ case 'H':
+ usage_hf_iclass_calc_newkey();
+ return 0;
+ case 'e':
+ case 'E':
+ dataLen = param_getstr(Cmd, cmdp, tempStr, sizeof(tempStr));
+ if (dataLen==2)
+ oldElite = true;
+ elite = true;
+ cmdp++;
+ break;
+ case 'n':
+ case 'N':
+ dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr));
+ if (dataLen == 16) {
+ errors = param_gethex(tempStr, 0, NEWKEY, dataLen);
+ } else if (dataLen == 1) {
+ keyNbr = param_get8(Cmd, cmdp+1);
+ if (keyNbr < ICLASS_KEYS_MAX) {
+ memcpy(NEWKEY, iClass_Key_Table[keyNbr], 8);
+ } else {
+ PrintAndLog("\nERROR: NewKey Nbr is invalid\n");
+ errors = true;
+ }
+ } else {
+ PrintAndLog("\nERROR: NewKey is incorrect length\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'o':
+ case 'O':
+ dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr));
+ if (dataLen == 16) {
+ errors = param_gethex(tempStr, 0, OLDKEY, dataLen);
+ } else if (dataLen == 1) {
+ keyNbr = param_get8(Cmd, cmdp+1);
+ if (keyNbr < ICLASS_KEYS_MAX) {
+ memcpy(OLDKEY, iClass_Key_Table[keyNbr], 8);
+ } else {
+ PrintAndLog("\nERROR: Credit KeyNbr is invalid\n");
+ errors = true;
+ }
+ } else {
+ PrintAndLog("\nERROR: Credit Key is incorrect length\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 's':
+ case 'S':
+ givenCSN = true;
+ if (param_gethex(Cmd, cmdp+1, CSN, 16)) {
+ usage_hf_iclass_calc_newkey();
+ return 0;
+ }
+ cmdp += 2;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
+ errors = true;
+ break;
+ }
+ if (errors) {
+ usage_hf_iclass_calc_newkey();
+ return 0;
+ }
+ }
+
+ if (cmdp < 4) {
+ usage_hf_iclass_calc_newkey();
+ return 0;
+ }
+
+ if (!givenCSN)
+ if (!iClass_select(CSN, true, true, true)) {
+ DropField();
+ return 0;
+ }
+ DropField();
+
+ HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, oldElite, true);
+ return 0;
+}
+
+
+static int loadKeys(char *filename) {
+ FILE *f;
+ f = fopen(filename,"rb");
+ if(!f) {
+ PrintAndLog("Failed to read from file '%s'", filename);
+ return 0;
+ }
+ fseek(f, 0, SEEK_END);
+ long fsize = ftell(f);
+ fseek(f, 0, SEEK_SET);
+
+ if ( fsize < 0 ) {
+ PrintAndLog("Error, when getting filesize");
+ fclose(f);
+ return 1;
+ }
+
+ uint8_t *dump = malloc(fsize);
+
+ size_t bytes_read = fread(dump, 1, fsize, f);
+ fclose(f);
+ if (bytes_read > ICLASS_KEYS_MAX * 8){
+ PrintAndLog("File is too long to load - bytes: %u", bytes_read);
+ free(dump);
+ return 0;
+ }
+ uint8_t i = 0;
+ for (; i < bytes_read/8; i++){
+ memcpy(iClass_Key_Table[i],dump+(i*8),8);
+ }
+ free(dump);
+ PrintAndLog("%u keys loaded", i);
+ return 1;
+}
+
+
+static int saveKeys(char *filename) {
+ FILE *f;
+ f = fopen(filename,"wb");
+ if (f == NULL) {
+ printf("error opening file %s\n",filename);
+ return 0;
+ }
+ for (uint8_t i = 0; i < ICLASS_KEYS_MAX; i++){
+ if (fwrite(iClass_Key_Table[i],8,1,f) != 1){
+ PrintAndLog("save key failed to write to file: %s", filename);
+ break;
+ }
+ }
+ fclose(f);
+ return 0;
+}
+
+
+static int printKeys(void) {
+ PrintAndLog("");
+ for (uint8_t i = 0; i < ICLASS_KEYS_MAX; i++){
+ PrintAndLog("%u: %s",i,sprint_hex(iClass_Key_Table[i],8));
+ }
+ PrintAndLog("");
+ return 0;
+}
+
+
+static void usage_hf_iclass_managekeys(void) {
+ PrintAndLog("HELP : Manage iClass Keys in client memory:\n");
+ PrintAndLog("Usage: hf iclass managekeys n [keynbr] k [key] f [filename] s l p\n");
+ PrintAndLog(" Options:");
+ PrintAndLog(" n <keynbr> : specify the keyNbr to set in memory");
+ PrintAndLog(" k <key> : set a key in memory");
+ PrintAndLog(" f <filename>: specify a filename to use with load or save operations");
+ PrintAndLog(" s : save keys in memory to file specified by filename");
+ PrintAndLog(" l : load keys to memory from file specified by filename");
+ PrintAndLog(" p : print keys loaded into memory\n");
+ PrintAndLog("Samples:");
+ PrintAndLog(" set key : hf iclass managekeys n 0 k 1122334455667788");
+ PrintAndLog(" save key file: hf iclass managekeys f mykeys.bin s");
+ PrintAndLog(" load key file: hf iclass managekeys f mykeys.bin l");
+ PrintAndLog(" print keys : hf iclass managekeys p\n");
+}
+
+
+static int CmdHFiClassManageKeys(const char *Cmd) {
+ uint8_t keyNbr = 0;
+ uint8_t dataLen = 0;
+ uint8_t KEY[8] = {0};
+ char filename[FILE_PATH_SIZE];
+ uint8_t fileNameLen = 0;
+ bool errors = false;
+ uint8_t operation = 0;
+ char tempStr[20];
+ uint8_t cmdp = 0;
+
+ while(param_getchar(Cmd, cmdp) != 0x00) {
+ switch(param_getchar(Cmd, cmdp)) {
+ case 'h':
+ case 'H':
+ usage_hf_iclass_managekeys();
+ return 0;
+ case 'f':
+ case 'F':
+ fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename));
+ if (fileNameLen < 1) {
+ PrintAndLog("No filename found after f");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'n':
+ case 'N':
+ keyNbr = param_get8(Cmd, cmdp+1);
+ if (keyNbr >= ICLASS_KEYS_MAX) {
+ PrintAndLog("Invalid block number");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'k':
+ case 'K':
+ operation += 3; //set key
+ dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr));
+ if (dataLen == 16) { //ul-c or ev1/ntag key length
+ errors = param_gethex(tempStr, 0, KEY, dataLen);
+ } else {
+ PrintAndLog("\nERROR: Key is incorrect length\n");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'p':
+ case 'P':
+ operation += 4; //print keys in memory
+ cmdp++;
+ break;
+ case 'l':
+ case 'L':
+ operation += 5; //load keys from file
+ cmdp++;
+ break;
+ case 's':
+ case 'S':
+ operation += 6; //save keys to file
+ cmdp++;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
+ errors = true;
+ break;
+ }
+ if (errors) {
+ usage_hf_iclass_managekeys();
+ return 0;
+ }
+ }
+
+ if (operation == 0){
+ PrintAndLog("no operation specified (load, save, or print)\n");
+ usage_hf_iclass_managekeys();
+ return 0;
+ }
+
+ if (operation > 6){
+ PrintAndLog("Too many operations specified\n");
+ usage_hf_iclass_managekeys();
+ return 0;
+ }
+ if (operation > 4 && fileNameLen == 0){
+ PrintAndLog("You must enter a filename when loading or saving\n");
+ usage_hf_iclass_managekeys();
+ return 0;
+ }
+
+ switch (operation){
+ case 3: memcpy(iClass_Key_Table[keyNbr], KEY, 8); return 1;
+ case 4: return printKeys();
+ case 5: return loadKeys(filename);
+ case 6: return saveKeys(filename);
+ break;
+ }
+ return 0;
+}
+
+
+static int CmdHFiClassCheckKeys(const char *Cmd) {
+
+ uint8_t mac[4] = {0x00,0x00,0x00,0x00};
+ uint8_t key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+ uint8_t div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
+
+ // elite key, raw key, standard key
+ bool use_elite = false;
+ bool use_raw = false;
+ bool found_debit = false;
+ bool found_credit = false;
+ bool errors = false;
+ uint8_t cmdp = 0x00;
+ FILE *f;
+ char filename[FILE_PATH_SIZE] = {0};
+ uint8_t fileNameLen = 0;
+ char buf[17];
+ uint8_t *keyBlock = NULL, *p;
+ int keycnt = 0;
+
+ while (param_getchar(Cmd, cmdp) != 0x00 && !errors) {
+ switch (param_getchar(Cmd, cmdp)) {
+ case 'h':
+ case 'H':
+ usage_hf_iclass_chk();
+ return 0;
+ case 'f':
+ case 'F':
+ fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename));
+ if (fileNameLen < 1) {
+ PrintAndLog("No filename found after f");
+ errors = true;
+ }
+ cmdp += 2;
+ break;
+ case 'e':
+ case 'E':
+ use_elite = true;
+ cmdp++;
+ break;
+ case 'r':
+ case 'R':
+ use_raw = true;
+ cmdp++;
+ break;
+ default:
+ PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp));
+ errors = true;
+ break;
+ }
+ }
+
+ if (errors) {
+ usage_hf_iclass_chk();
+ return 0;
+ }
+
+ if (!(f = fopen(filename , "r"))) {
+ PrintAndLog("File %s not found or locked.", filename);
+ return 1;
+ }
+
+ while (fgets(buf, sizeof(buf), f)) {
+ if (strlen(buf) < 16 || buf[15] == '\n')
+ continue;
+
+ while (fgetc(f) != '\n' && !feof(f)) ; //goto next line
+
+ if (buf[0] == '#') continue; //The line start with # is comment, skip
+
+ if (!isxdigit(buf[0])){
+ PrintAndLog("File content error. '%s' must include 16 HEX symbols", buf);
+ continue;
+ }
+
+ buf[16] = 0;
+
+ p = realloc(keyBlock, 8 * (keycnt + 1));
+ if (!p) {
+ PrintAndLog("Cannot allocate memory for default keys");
+ free(keyBlock);
+ fclose(f);
+ return 2;
+ }
+ keyBlock = p;
+
+ memset(keyBlock + 8 * keycnt, 0, 8);
+ num_to_bytes(strtoull(buf, NULL, 16), 8, keyBlock + 8 * keycnt);
+
+ keycnt++;
+ memset(buf, 0, sizeof(buf));
+ }
+ fclose(f);
+ PrintAndLog("Loaded %2d keys from %s", keycnt, filename);
+
+ uint8_t CSN[8];
+ if (!iClass_select(CSN, false, true, true)) {
+ DropField();
+ return 0;
+ }
+
+ for (uint32_t c = 0; c < keycnt; c++) {
+
+ memcpy(key, keyBlock + 8 * c, 8);
+
+ // debit key
+ if (iClass_authenticate(CSN, key, mac, div_key, false, use_elite, use_raw, false, false)) {
+ PrintAndLog("\n Found AA1 debit key\t\t[%s]", sprint_hex(key, 8));
+ found_debit = true;
+ }
+
+ // credit key
+ if (iClass_authenticate(CSN, key, mac, div_key, true, use_elite, use_raw, false, false)) {
+ PrintAndLog("\n Found AA2 credit key\t\t[%s]", sprint_hex(key, 8));
+ found_credit = true;
+ }
+
+ // both keys found.
+ if (found_debit && found_credit)
+ break;
+ }
+
+ DropField();
+ free(keyBlock);
+ PrintAndLog("");
+ return 0;
+}
+
+
+static void usage_hf_iclass_permutekey(void) {
+ PrintAndLogEx(NORMAL, "Convert keys from standard NIST to iClass format (and vice versa)");
+ PrintAndLogEx(NORMAL, "");
+ PrintAndLogEx(NORMAL, "Usage: hf iclass permute [h] [r] <key>");
+ PrintAndLogEx(NORMAL, "Options:");
+ PrintAndLogEx(NORMAL, " h This help");
+ PrintAndLogEx(NORMAL, " r reverse convert key from iClass to NIST format");
+ PrintAndLogEx(NORMAL, "");
+ PrintAndLogEx(NORMAL, "Examples:");
+ PrintAndLogEx(NORMAL, " hf iclass permute r 0123456789abcdef");
+}
+
+
+static int CmdHFiClassPermuteKey(const char *Cmd) {
+
+ uint8_t key[8] = {0};
+ uint8_t data[16] = {0};
+ bool isReverse = false;
+ int len = sizeof(data);
+ char cmdp = tolower(param_getchar(Cmd, 0));
+ if (strlen(Cmd) == 0 || cmdp == 'h') {
+ usage_hf_iclass_permutekey();
+ return 0;
+ }
+
+ if (cmdp == 'r') {
+ isReverse = true;
+ param_gethex_ex(Cmd, 1, data, &len);
+ } else if (cmdp == 'f') {
+ param_gethex_ex(Cmd, 1, data, &len);
+ } else {
+ param_gethex_ex(Cmd, 0, data, &len);
+ }
+
+
+ if (len % 2) {
+ usage_hf_iclass_permutekey();
+ return 0;
+ }
+
+ len >>= 1;
+
+ memcpy(key, data, 8);
+
+ if (isReverse) {
+ // generate_rev(data, len);
+ uint8_t key_std_format[8] = {0};
+ permutekey_rev(key, key_std_format);
+ PrintAndLogEx(SUCCESS, "key in standard NIST format: %s \n", sprint_hex(key_std_format, 8));
+ // if (mbedtls_des_key_check_key_parity(key_std_format
+ } else {
+ // generate(data, len);
+ uint8_t key_iclass_format[8] = {0};
+ permutekey(key, key_iclass_format);
+ PrintAndLogEx(SUCCESS, "key in iClass (permuted) format: %s \n", sprint_hex(key_iclass_format, 8));
+ }
+ return 0;
+}
+
+
+static int CmdHelp(const char *Cmd);
+
+static command_t CommandTable[] = {
+ {"help", CmdHelp, 1, "This help"},
+ {"calcnewkey", CmdHFiClassCalcNewKey, 1, "[options..] Calc Diversified keys (blocks 3 & 4) to write new keys"},
+ {"chk", CmdHFiClassCheckKeys, 0, " Check keys"},
+ {"clone", CmdHFiClassCloneTag, 0, "[options..] Authenticate and Clone from iClass bin file"},
+ {"decrypt", CmdHFiClassDecrypt, 1, "[f <fname>] Decrypt tagdump" },
+ {"dump", CmdHFiClassReader_Dump, 0, "[options..] Authenticate and Dump iClass tag's AA1 and/or AA2"},
+ {"eload", CmdHFiClassELoad, 0, "[f <fname>] (experimental) Load data into iClass emulator memory"},
+ {"encryptblk", CmdHFiClassEncryptBlk, 1, "<BlockData> Encrypt given block data"},
+ {"list", CmdHFiClassList, 0, " (Deprecated) List iClass history"},
+ {"loclass", CmdHFiClass_loclass, 1, "[options..] Use loclass to perform bruteforce of reader attack dump"},
+ {"managekeys", CmdHFiClassManageKeys, 1, "[options..] Manage the keys to use with iClass"},
+ {"permutekey", CmdHFiClassPermuteKey, 1, " iClass key permutation"},
+ {"readblk", CmdHFiClass_ReadBlock, 0, "[options..] Authenticate and Read iClass block"},
+ {"reader", CmdHFiClassReader, 0, " Look for iClass tags until a key or the pm3 button is pressed"},
+ {"readtagfile", CmdHFiClassReadTagFile, 1, "[options..] Display Content from tagfile"},
+ {"sim", CmdHFiClassSim, 0, "[options..] Simulate iClass tag"},
+ {"snoop", CmdHFiClassSnoop, 0, " Eavesdrop iClass communication"},
+ {"writeblk", CmdHFiClass_WriteBlock, 0, "[options..] Authenticate and Write iClass block"},
+ {NULL, NULL, 0, NULL}
+};
+
+
+int CmdHFiClass(const char *Cmd) {
+ clearCommandBuffer();
+ CmdsParse(CommandTable, Cmd);
+ return 0;
+}
+
+
+int CmdHelp(const char *Cmd) {
+ CmdsHelp(CommandTable);
+ return 0;