]> cvs.zerfleddert.de Git - proxmark3-svn/blob - client/cmdhfmfhard.c
fix clang compiler warnings
[proxmark3-svn] / client / cmdhfmfhard.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2015, 2016 by piwi
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // Implements a card only attack based on crypto text (encrypted nonces
9 // received during a nested authentication) only. Unlike other card only
10 // attacks this doesn't rely on implementation errors but only on the
11 // inherent weaknesses of the crypto1 cypher. Described in
12 // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened
13 // Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on
14 // Computer and Communications Security, 2015
15 //-----------------------------------------------------------------------------
16
17 #include "cmdhfmfhard.h"
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <inttypes.h>
22 #include <string.h>
23 #include <time.h>
24 #include <pthread.h>
25 #include <locale.h>
26 #include <math.h>
27 #include "proxmark3.h"
28 #include "cmdmain.h"
29 #include "ui.h"
30 #include "util.h"
31 #include "util_posix.h"
32 #include "crapto1/crapto1.h"
33 #include "parity.h"
34 #include "hardnested/hardnested_bruteforce.h"
35 #include "hardnested/hardnested_bf_core.h"
36 #include "hardnested/hardnested_bitarray_core.h"
37 #include "zlib.h"
38
39 #define NUM_CHECK_BITFLIPS_THREADS (num_CPUs())
40 #define NUM_REDUCTION_WORKING_THREADS (num_CPUs())
41
42 #define IGNORE_BITFLIP_THRESHOLD 0.99 // ignore bitflip arrays which have nearly only valid states
43
44 #define STATE_FILES_DIRECTORY "hardnested/tables/"
45 #define STATE_FILE_TEMPLATE "bitflip_%d_%03" PRIx16 "_states.bin.z"
46
47 #define DEBUG_KEY_ELIMINATION
48 // #define DEBUG_REDUCTION
49
50 static uint16_t sums[NUM_SUMS] = {0, 32, 56, 64, 80, 96, 104, 112, 120, 128, 136, 144, 152, 160, 176, 192, 200, 224, 256}; // possible sum property values
51
52 #define NUM_PART_SUMS 9 // number of possible partial sum property values
53
54 typedef enum {
55 EVEN_STATE = 0,
56 ODD_STATE = 1
57 } odd_even_t;
58
59 static uint32_t num_acquired_nonces = 0;
60 static uint64_t start_time = 0;
61 static uint16_t effective_bitflip[2][0x400];
62 static uint16_t num_effective_bitflips[2] = {0, 0};
63 static uint16_t all_effective_bitflip[0x400];
64 static uint16_t num_all_effective_bitflips = 0;
65 static uint16_t num_1st_byte_effective_bitflips = 0;
66 #define CHECK_1ST_BYTES 0x01
67 #define CHECK_2ND_BYTES 0x02
68 static uint8_t hardnested_stage = CHECK_1ST_BYTES;
69 static uint64_t known_target_key;
70 static uint32_t test_state[2] = {0,0};
71 static float brute_force_per_second;
72
73
74 static void get_SIMD_instruction_set(char* instruction_set) {
75 switch(GetSIMDInstrAuto()) {
76 case SIMD_AVX512:
77 strcpy(instruction_set, "AVX512F");
78 break;
79 case SIMD_AVX2:
80 strcpy(instruction_set, "AVX2");
81 break;
82 case SIMD_AVX:
83 strcpy(instruction_set, "AVX");
84 break;
85 case SIMD_SSE2:
86 strcpy(instruction_set, "SSE2");
87 break;
88 case SIMD_MMX:
89 strcpy(instruction_set, "MMX");
90 break;
91 default:
92 strcpy(instruction_set, "no");
93 break;
94 }
95 }
96
97
98 static void print_progress_header(void) {
99 char progress_text[80];
100 char instr_set[12] = {0};
101 get_SIMD_instruction_set(instr_set);
102 sprintf(progress_text, "Start using %d threads and %s SIMD core", num_CPUs(), instr_set);
103 PrintAndLog("\n\n");
104 PrintAndLog(" time | #nonces | Activity | expected to brute force");
105 PrintAndLog(" | | | #states | time ");
106 PrintAndLog("------------------------------------------------------------------------------------------------------");
107 PrintAndLog(" 0 | 0 | %-55s | |", progress_text);
108 }
109
110
111 void hardnested_print_progress(uint32_t nonces, char *activity, float brute_force, uint64_t min_diff_print_time) {
112 static uint64_t last_print_time = 0;
113 if (msclock() - last_print_time > min_diff_print_time) {
114 last_print_time = msclock();
115 uint64_t total_time = msclock() - start_time;
116 float brute_force_time = brute_force / brute_force_per_second;
117 char brute_force_time_string[20];
118 if (brute_force_time < 90) {
119 sprintf(brute_force_time_string, "%2.0fs", brute_force_time);
120 } else if (brute_force_time < 60 * 90) {
121 sprintf(brute_force_time_string, "%2.0fmin", brute_force_time/60);
122 } else if (brute_force_time < 60 * 60 * 36) {
123 sprintf(brute_force_time_string, "%2.0fh", brute_force_time/(60*60));
124 } else {
125 sprintf(brute_force_time_string, "%2.0fd", brute_force_time/(60*60*24));
126 }
127 PrintAndLog(" %7.0f | %7d | %-55s | %15.0f | %5s", (float)total_time/1000.0, nonces, activity, brute_force, brute_force_time_string);
128 }
129 }
130
131
132 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
133 // bitarray functions
134
135 static inline void clear_bitarray24(uint32_t *bitarray)
136 {
137 memset(bitarray, 0x00, sizeof(uint32_t) * (1<<19));
138 }
139
140
141 static inline void set_bitarray24(uint32_t *bitarray)
142 {
143 memset(bitarray, 0xff, sizeof(uint32_t) * (1<<19));
144 }
145
146
147 static inline void set_bit24(uint32_t *bitarray, uint32_t index)
148 {
149 bitarray[index>>5] |= 0x80000000>>(index&0x0000001f);
150 }
151
152
153 static inline uint32_t test_bit24(uint32_t *bitarray, uint32_t index)
154 {
155 return bitarray[index>>5] & (0x80000000>>(index&0x0000001f));
156 }
157
158
159 static inline uint32_t next_state(uint32_t *bitarray, uint32_t state)
160 {
161 if (++state == 1<<24) return 1<<24;
162 uint32_t index = state >> 5;
163 uint_fast8_t bit = state & 0x1f;
164 uint32_t line = bitarray[index] << bit;
165 while (bit <= 0x1f) {
166 if (line & 0x80000000) return state;
167 state++;
168 bit++;
169 line <<= 1;
170 }
171 index++;
172 while (bitarray[index] == 0x00000000 && state < 1<<24) {
173 index++;
174 state += 0x20;
175 }
176 if (state >= 1<<24) return 1<<24;
177 #if defined __GNUC__
178 return state + __builtin_clz(bitarray[index]);
179 #else
180 bit = 0x00;
181 line = bitarray[index];
182 while (bit <= 0x1f) {
183 if (line & 0x80000000) return state;
184 state++;
185 bit++;
186 line <<= 1;
187 }
188 return 1<<24;
189 #endif
190 }
191
192
193
194
195 #define BITFLIP_2ND_BYTE 0x0200
196
197
198 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
199 // bitflip property bitarrays
200
201 static uint32_t *bitflip_bitarrays[2][0x400];
202 static uint32_t count_bitflip_bitarrays[2][0x400];
203
204 static int compare_count_bitflip_bitarrays(const void *b1, const void *b2)
205 {
206 uint64_t count1 = (uint64_t)count_bitflip_bitarrays[ODD_STATE][*(uint16_t *)b1] * count_bitflip_bitarrays[EVEN_STATE][*(uint16_t *)b1];
207 uint64_t count2 = (uint64_t)count_bitflip_bitarrays[ODD_STATE][*(uint16_t *)b2] * count_bitflip_bitarrays[EVEN_STATE][*(uint16_t *)b2];
208 return (count1 > count2) - (count2 > count1);
209 }
210
211
212 static voidpf inflate_malloc(voidpf opaque, uInt items, uInt size)
213 {
214 return malloc(items*size);
215 }
216
217
218 static void inflate_free(voidpf opaque, voidpf address)
219 {
220 free(address);
221 }
222
223 #define OUTPUT_BUFFER_LEN 80
224 #define INPUT_BUFFER_LEN 80
225
226 //----------------------------------------------------------------------------
227 // Initialize decompression of the respective (HF or LF) FPGA stream
228 //----------------------------------------------------------------------------
229 static void init_inflate(z_streamp compressed_stream, uint8_t *input_buffer, uint32_t insize, uint8_t *output_buffer, uint32_t outsize)
230 {
231
232 // initialize z_stream structure for inflate:
233 compressed_stream->next_in = input_buffer;
234 compressed_stream->avail_in = insize;
235 compressed_stream->next_out = output_buffer;
236 compressed_stream->avail_out = outsize;
237 compressed_stream->zalloc = &inflate_malloc;
238 compressed_stream->zfree = &inflate_free;
239
240 inflateInit2(compressed_stream, 0);
241
242 }
243
244
245 static void init_bitflip_bitarrays(void)
246 {
247 #if defined (DEBUG_REDUCTION)
248 uint8_t line = 0;
249 #endif
250
251
252 z_stream compressed_stream;
253
254 char state_files_path[strlen(get_my_executable_directory()) + strlen(STATE_FILES_DIRECTORY) + strlen(STATE_FILE_TEMPLATE) + 1];
255 char state_file_name[strlen(STATE_FILE_TEMPLATE)+1];
256
257 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
258 num_effective_bitflips[odd_even] = 0;
259 for (uint16_t bitflip = 0x001; bitflip < 0x400; bitflip++) {
260 bitflip_bitarrays[odd_even][bitflip] = NULL;
261 count_bitflip_bitarrays[odd_even][bitflip] = 1<<24;
262 sprintf(state_file_name, STATE_FILE_TEMPLATE, odd_even, bitflip);
263 strcpy(state_files_path, get_my_executable_directory());
264 strcat(state_files_path, STATE_FILES_DIRECTORY);
265 strcat(state_files_path, state_file_name);
266 FILE *statesfile = fopen(state_files_path, "rb");
267 if (statesfile == NULL) {
268 continue;
269 } else {
270 fseek(statesfile, 0, SEEK_END);
271 uint32_t filesize = (uint32_t)ftell(statesfile);
272 rewind(statesfile);
273 uint8_t input_buffer[filesize];
274 size_t bytesread = fread(input_buffer, 1, filesize, statesfile);
275 if (bytesread != filesize) {
276 printf("File read error with %s. Aborting...\n", state_file_name);
277 fclose(statesfile);
278 inflateEnd(&compressed_stream);
279 exit(5);
280 }
281 fclose(statesfile);
282 uint32_t count = 0;
283 init_inflate(&compressed_stream, input_buffer, filesize, (uint8_t *)&count, sizeof(count));
284 inflate(&compressed_stream, Z_SYNC_FLUSH);
285 if ((float)count/(1<<24) < IGNORE_BITFLIP_THRESHOLD) {
286 uint32_t *bitset = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
287 if (bitset == NULL) {
288 printf("Out of memory error in init_bitflip_statelists(). Aborting...\n");
289 inflateEnd(&compressed_stream);
290 exit(4);
291 }
292 compressed_stream.next_out = (uint8_t *)bitset;
293 compressed_stream.avail_out = sizeof(uint32_t) * (1<<19);
294 inflate(&compressed_stream, Z_SYNC_FLUSH);
295 effective_bitflip[odd_even][num_effective_bitflips[odd_even]++] = bitflip;
296 bitflip_bitarrays[odd_even][bitflip] = bitset;
297 count_bitflip_bitarrays[odd_even][bitflip] = count;
298 #if defined (DEBUG_REDUCTION)
299 printf("(%03" PRIx16 " %s:%5.1f%%) ", bitflip, odd_even?"odd ":"even", (float)count/(1<<24)*100.0);
300 line++;
301 if (line == 8) {
302 printf("\n");
303 line = 0;
304 }
305 #endif
306 }
307 inflateEnd(&compressed_stream);
308 }
309 }
310 effective_bitflip[odd_even][num_effective_bitflips[odd_even]] = 0x400; // EndOfList marker
311 }
312
313 uint16_t i = 0;
314 uint16_t j = 0;
315 num_all_effective_bitflips = 0;
316 num_1st_byte_effective_bitflips = 0;
317 while (i < num_effective_bitflips[EVEN_STATE] || j < num_effective_bitflips[ODD_STATE]) {
318 if (effective_bitflip[EVEN_STATE][i] < effective_bitflip[ODD_STATE][j]) {
319 all_effective_bitflip[num_all_effective_bitflips++] = effective_bitflip[EVEN_STATE][i];
320 i++;
321 } else if (effective_bitflip[EVEN_STATE][i] > effective_bitflip[ODD_STATE][j]) {
322 all_effective_bitflip[num_all_effective_bitflips++] = effective_bitflip[ODD_STATE][j];
323 j++;
324 } else {
325 all_effective_bitflip[num_all_effective_bitflips++] = effective_bitflip[EVEN_STATE][i];
326 i++; j++;
327 }
328 if (!(all_effective_bitflip[num_all_effective_bitflips-1] & BITFLIP_2ND_BYTE)) {
329 num_1st_byte_effective_bitflips = num_all_effective_bitflips;
330 }
331 }
332 qsort(all_effective_bitflip, num_1st_byte_effective_bitflips, sizeof(uint16_t), compare_count_bitflip_bitarrays);
333 #if defined (DEBUG_REDUCTION)
334 printf("\n1st byte effective bitflips (%d): \n", num_1st_byte_effective_bitflips);
335 for(uint16_t i = 0; i < num_1st_byte_effective_bitflips; i++) {
336 printf("%03x ", all_effective_bitflip[i]);
337 }
338 #endif
339 qsort(all_effective_bitflip+num_1st_byte_effective_bitflips, num_all_effective_bitflips - num_1st_byte_effective_bitflips, sizeof(uint16_t), compare_count_bitflip_bitarrays);
340 #if defined (DEBUG_REDUCTION)
341 printf("\n2nd byte effective bitflips (%d): \n", num_all_effective_bitflips - num_1st_byte_effective_bitflips);
342 for(uint16_t i = num_1st_byte_effective_bitflips; i < num_all_effective_bitflips; i++) {
343 printf("%03x ", all_effective_bitflip[i]);
344 }
345 #endif
346 char progress_text[80];
347 sprintf(progress_text, "Using %d precalculated bitflip state tables", num_all_effective_bitflips);
348 hardnested_print_progress(0, progress_text, (float)(1LL<<47), 0);
349 }
350
351
352 static void free_bitflip_bitarrays(void)
353 {
354 for (int16_t bitflip = 0x3ff; bitflip > 0x000; bitflip--) {
355 free_bitarray(bitflip_bitarrays[ODD_STATE][bitflip]);
356 }
357 for (int16_t bitflip = 0x3ff; bitflip > 0x000; bitflip--) {
358 free_bitarray(bitflip_bitarrays[EVEN_STATE][bitflip]);
359 }
360 }
361
362
363 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
364 // sum property bitarrays
365
366 static uint32_t *part_sum_a0_bitarrays[2][NUM_PART_SUMS];
367 static uint32_t *part_sum_a8_bitarrays[2][NUM_PART_SUMS];
368 static uint32_t *sum_a0_bitarrays[2][NUM_SUMS];
369
370 static uint16_t PartialSumProperty(uint32_t state, odd_even_t odd_even)
371 {
372 uint16_t sum = 0;
373 for (uint16_t j = 0; j < 16; j++) {
374 uint32_t st = state;
375 uint16_t part_sum = 0;
376 if (odd_even == ODD_STATE) {
377 for (uint16_t i = 0; i < 5; i++) {
378 part_sum ^= filter(st);
379 st = (st << 1) | ((j >> (3-i)) & 0x01) ;
380 }
381 part_sum ^= 1; // XOR 1 cancelled out for the other 8 bits
382 } else {
383 for (uint16_t i = 0; i < 4; i++) {
384 st = (st << 1) | ((j >> (3-i)) & 0x01) ;
385 part_sum ^= filter(st);
386 }
387 }
388 sum += part_sum;
389 }
390 return sum;
391 }
392
393
394 static void init_part_sum_bitarrays(void)
395 {
396 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
397 for (uint16_t part_sum_a0 = 0; part_sum_a0 < NUM_PART_SUMS; part_sum_a0++) {
398 part_sum_a0_bitarrays[odd_even][part_sum_a0] = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
399 if (part_sum_a0_bitarrays[odd_even][part_sum_a0] == NULL) {
400 printf("Out of memory error in init_part_suma0_statelists(). Aborting...\n");
401 exit(4);
402 }
403 clear_bitarray24(part_sum_a0_bitarrays[odd_even][part_sum_a0]);
404 }
405 }
406 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
407 //printf("(%d, %" PRIu16 ")...", odd_even, part_sum_a0);
408 for (uint32_t state = 0; state < (1<<20); state++) {
409 uint16_t part_sum_a0 = PartialSumProperty(state, odd_even) / 2;
410 for (uint16_t low_bits = 0; low_bits < 1<<4; low_bits++) {
411 set_bit24(part_sum_a0_bitarrays[odd_even][part_sum_a0], state<<4 | low_bits);
412 }
413 }
414 }
415
416 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
417 for (uint16_t part_sum_a8 = 0; part_sum_a8 < NUM_PART_SUMS; part_sum_a8++) {
418 part_sum_a8_bitarrays[odd_even][part_sum_a8] = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
419 if (part_sum_a8_bitarrays[odd_even][part_sum_a8] == NULL) {
420 printf("Out of memory error in init_part_suma8_statelists(). Aborting...\n");
421 exit(4);
422 }
423 clear_bitarray24(part_sum_a8_bitarrays[odd_even][part_sum_a8]);
424 }
425 }
426 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
427 //printf("(%d, %" PRIu16 ")...", odd_even, part_sum_a8);
428 for (uint32_t state = 0; state < (1<<20); state++) {
429 uint16_t part_sum_a8 = PartialSumProperty(state, odd_even) / 2;
430 for (uint16_t high_bits = 0; high_bits < 1<<4; high_bits++) {
431 set_bit24(part_sum_a8_bitarrays[odd_even][part_sum_a8], state | high_bits<<20);
432 }
433 }
434 }
435 }
436
437
438 static void free_part_sum_bitarrays(void)
439 {
440 for (int16_t part_sum_a8 = (NUM_PART_SUMS-1); part_sum_a8 >= 0; part_sum_a8--) {
441 free_bitarray(part_sum_a8_bitarrays[ODD_STATE][part_sum_a8]);
442 }
443 for (int16_t part_sum_a8 = (NUM_PART_SUMS-1); part_sum_a8 >= 0; part_sum_a8--) {
444 free_bitarray(part_sum_a8_bitarrays[EVEN_STATE][part_sum_a8]);
445 }
446 for (int16_t part_sum_a0 = (NUM_PART_SUMS-1); part_sum_a0 >= 0; part_sum_a0--) {
447 free_bitarray(part_sum_a0_bitarrays[ODD_STATE][part_sum_a0]);
448 }
449 for (int16_t part_sum_a0 = (NUM_PART_SUMS-1); part_sum_a0 >= 0; part_sum_a0--) {
450 free_bitarray(part_sum_a0_bitarrays[EVEN_STATE][part_sum_a0]);
451 }
452 }
453
454
455 static void init_sum_bitarrays(void)
456 {
457 for (uint16_t sum_a0 = 0; sum_a0 < NUM_SUMS; sum_a0++) {
458 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
459 sum_a0_bitarrays[odd_even][sum_a0] = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
460 if (sum_a0_bitarrays[odd_even][sum_a0] == NULL) {
461 printf("Out of memory error in init_sum_bitarrays(). Aborting...\n");
462 exit(4);
463 }
464 clear_bitarray24(sum_a0_bitarrays[odd_even][sum_a0]);
465 }
466 }
467 for (uint8_t p = 0; p < NUM_PART_SUMS; p++) {
468 for (uint8_t q = 0; q < NUM_PART_SUMS; q++) {
469 uint16_t sum_a0 = 2*p*(16-2*q) + (16-2*p)*2*q;
470 uint16_t sum_a0_idx = 0;
471 while (sums[sum_a0_idx] != sum_a0) sum_a0_idx++;
472 bitarray_OR(sum_a0_bitarrays[EVEN_STATE][sum_a0_idx], part_sum_a0_bitarrays[EVEN_STATE][q]);
473 bitarray_OR(sum_a0_bitarrays[ODD_STATE][sum_a0_idx], part_sum_a0_bitarrays[ODD_STATE][p]);
474 }
475 }
476 // for (uint16_t sum_a0 = 0; sum_a0 < NUM_SUMS; sum_a0++) {
477 // for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
478 // uint32_t count = count_states(sum_a0_bitarrays[odd_even][sum_a0]);
479 // printf("sum_a0_bitarray[%s][%d] has %d states (%5.2f%%)\n", odd_even==EVEN_STATE?"even":"odd ", sums[sum_a0], count, (float)count/(1<<24)*100.0);
480 // }
481 // }
482 }
483
484
485 static void free_sum_bitarrays(void)
486 {
487 for (int8_t sum_a0 = NUM_SUMS-1; sum_a0 >= 0; sum_a0--) {
488 free_bitarray(sum_a0_bitarrays[ODD_STATE][sum_a0]);
489 free_bitarray(sum_a0_bitarrays[EVEN_STATE][sum_a0]);
490 }
491 }
492
493
494 #ifdef DEBUG_KEY_ELIMINATION
495 char failstr[250] = "";
496 #endif
497
498 static const float p_K0[NUM_SUMS] = { // the probability that a random nonce has a Sum Property K
499 0.0290, 0.0083, 0.0006, 0.0339, 0.0048, 0.0934, 0.0119, 0.0489, 0.0602, 0.4180, 0.0602, 0.0489, 0.0119, 0.0934, 0.0048, 0.0339, 0.0006, 0.0083, 0.0290
500 };
501
502 static float my_p_K[NUM_SUMS];
503
504 static const float *p_K;
505
506 static uint32_t cuid;
507 static noncelist_t nonces[256];
508 static uint8_t best_first_bytes[256];
509 static uint64_t maximum_states = 0;
510 static uint8_t best_first_byte_smallest_bitarray = 0;
511 static uint16_t first_byte_Sum = 0;
512 static uint16_t first_byte_num = 0;
513 static bool write_stats = false;
514 static FILE *fstats = NULL;
515 static uint32_t *all_bitflips_bitarray[2];
516 static uint32_t num_all_bitflips_bitarray[2];
517 static bool all_bitflips_bitarray_dirty[2];
518 static uint64_t last_sample_clock = 0;
519 static uint64_t sample_period = 0;
520 static uint64_t num_keys_tested = 0;
521 static statelist_t *candidates = NULL;
522
523
524 static int add_nonce(uint32_t nonce_enc, uint8_t par_enc)
525 {
526 uint8_t first_byte = nonce_enc >> 24;
527 noncelistentry_t *p1 = nonces[first_byte].first;
528 noncelistentry_t *p2 = NULL;
529
530 if (p1 == NULL) { // first nonce with this 1st byte
531 first_byte_num++;
532 first_byte_Sum += evenparity32((nonce_enc & 0xff000000) | (par_enc & 0x08));
533 }
534
535 while (p1 != NULL && (p1->nonce_enc & 0x00ff0000) < (nonce_enc & 0x00ff0000)) {
536 p2 = p1;
537 p1 = p1->next;
538 }
539
540 if (p1 == NULL) { // need to add at the end of the list
541 if (p2 == NULL) { // list is empty yet. Add first entry.
542 p2 = nonces[first_byte].first = malloc(sizeof(noncelistentry_t));
543 } else { // add new entry at end of existing list.
544 p2 = p2->next = malloc(sizeof(noncelistentry_t));
545 }
546 } else if ((p1->nonce_enc & 0x00ff0000) != (nonce_enc & 0x00ff0000)) { // found distinct 2nd byte. Need to insert.
547 if (p2 == NULL) { // need to insert at start of list
548 p2 = nonces[first_byte].first = malloc(sizeof(noncelistentry_t));
549 } else {
550 p2 = p2->next = malloc(sizeof(noncelistentry_t));
551 }
552 } else { // we have seen this 2nd byte before. Nothing to add or insert.
553 return (0);
554 }
555
556 // add or insert new data
557 p2->next = p1;
558 p2->nonce_enc = nonce_enc;
559 p2->par_enc = par_enc;
560
561 nonces[first_byte].num++;
562 nonces[first_byte].Sum += evenparity32((nonce_enc & 0x00ff0000) | (par_enc & 0x04));
563 nonces[first_byte].sum_a8_guess_dirty = true; // indicates that we need to recalculate the Sum(a8) probability for this first byte
564 return (1); // new nonce added
565 }
566
567
568 static void init_nonce_memory(void)
569 {
570 for (uint16_t i = 0; i < 256; i++) {
571 nonces[i].num = 0;
572 nonces[i].Sum = 0;
573 nonces[i].first = NULL;
574 for (uint16_t j = 0; j < NUM_SUMS; j++) {
575 nonces[i].sum_a8_guess[j].sum_a8_idx = j;
576 nonces[i].sum_a8_guess[j].prob = 0.0;
577 }
578 nonces[i].sum_a8_guess_dirty = false;
579 for (uint16_t bitflip = 0x000; bitflip < 0x400; bitflip++) {
580 nonces[i].BitFlips[bitflip] = 0;
581 }
582 nonces[i].states_bitarray[EVEN_STATE] = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
583 if (nonces[i].states_bitarray[EVEN_STATE] == NULL) {
584 printf("Out of memory error in init_nonce_memory(). Aborting...\n");
585 exit(4);
586 }
587 set_bitarray24(nonces[i].states_bitarray[EVEN_STATE]);
588 nonces[i].num_states_bitarray[EVEN_STATE] = 1 << 24;
589 nonces[i].states_bitarray[ODD_STATE] = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
590 if (nonces[i].states_bitarray[ODD_STATE] == NULL) {
591 printf("Out of memory error in init_nonce_memory(). Aborting...\n");
592 exit(4);
593 }
594 set_bitarray24(nonces[i].states_bitarray[ODD_STATE]);
595 nonces[i].num_states_bitarray[ODD_STATE] = 1 << 24;
596 nonces[i].all_bitflips_dirty[EVEN_STATE] = false;
597 nonces[i].all_bitflips_dirty[ODD_STATE] = false;
598 }
599 first_byte_num = 0;
600 first_byte_Sum = 0;
601 }
602
603
604 static void free_nonce_list(noncelistentry_t *p)
605 {
606 if (p == NULL) {
607 return;
608 } else {
609 free_nonce_list(p->next);
610 free(p);
611 }
612 }
613
614
615 static void free_nonces_memory(void)
616 {
617 for (uint16_t i = 0; i < 256; i++) {
618 free_nonce_list(nonces[i].first);
619 }
620 for (int i = 255; i >= 0; i--) {
621 free_bitarray(nonces[i].states_bitarray[ODD_STATE]);
622 free_bitarray(nonces[i].states_bitarray[EVEN_STATE]);
623 }
624 }
625
626
627 // static double p_hypergeometric_cache[257][NUM_SUMS][257];
628
629 // #define CACHE_INVALID -1.0
630 // static void init_p_hypergeometric_cache(void)
631 // {
632 // for (uint16_t n = 0; n <= 256; n++) {
633 // for (uint16_t i_K = 0; i_K < NUM_SUMS; i_K++) {
634 // for (uint16_t k = 0; k <= 256; k++) {
635 // p_hypergeometric_cache[n][i_K][k] = CACHE_INVALID;
636 // }
637 // }
638 // }
639 // }
640
641
642 static double p_hypergeometric(uint16_t i_K, uint16_t n, uint16_t k)
643 {
644 // for efficient computation we are using the recursive definition
645 // (K-k+1) * (n-k+1)
646 // P(X=k) = P(X=k-1) * --------------------
647 // k * (N-K-n+k)
648 // and
649 // (N-K)*(N-K-1)*...*(N-K-n+1)
650 // P(X=0) = -----------------------------
651 // N*(N-1)*...*(N-n+1)
652
653
654 uint16_t const N = 256;
655 uint16_t K = sums[i_K];
656
657 // if (p_hypergeometric_cache[n][i_K][k] != CACHE_INVALID) {
658 // return p_hypergeometric_cache[n][i_K][k];
659 // }
660
661 if (n-k > N-K || k > K) return 0.0; // avoids log(x<=0) in calculation below
662 if (k == 0) {
663 // use logarithms to avoid overflow with huge factorials (double type can only hold 170!)
664 double log_result = 0.0;
665 for (int16_t i = N-K; i >= N-K-n+1; i--) {
666 log_result += log(i);
667 }
668 for (int16_t i = N; i >= N-n+1; i--) {
669 log_result -= log(i);
670 }
671 // p_hypergeometric_cache[n][i_K][k] = exp(log_result);
672 return exp(log_result);
673 } else {
674 if (n-k == N-K) { // special case. The published recursion below would fail with a divide by zero exception
675 double log_result = 0.0;
676 for (int16_t i = k+1; i <= n; i++) {
677 log_result += log(i);
678 }
679 for (int16_t i = K+1; i <= N; i++) {
680 log_result -= log(i);
681 }
682 // p_hypergeometric_cache[n][i_K][k] = exp(log_result);
683 return exp(log_result);
684 } else { // recursion
685 return (p_hypergeometric(i_K, n, k-1) * (K-k+1) * (n-k+1) / (k * (N-K-n+k)));
686 }
687 }
688 }
689
690
691 static float sum_probability(uint16_t i_K, uint16_t n, uint16_t k)
692 {
693 if (k > sums[i_K]) return 0.0;
694
695 double p_T_is_k_when_S_is_K = p_hypergeometric(i_K, n, k);
696 double p_S_is_K = p_K[i_K];
697 double p_T_is_k = 0;
698 for (uint16_t i = 0; i < NUM_SUMS; i++) {
699 p_T_is_k += p_K[i] * p_hypergeometric(i, n, k);
700 }
701 return(p_T_is_k_when_S_is_K * p_S_is_K / p_T_is_k);
702 }
703
704
705 static uint32_t part_sum_count[2][NUM_PART_SUMS][NUM_PART_SUMS];
706
707 static void init_allbitflips_array(void)
708 {
709 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
710 uint32_t *bitset = all_bitflips_bitarray[odd_even] = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
711 if (bitset == NULL) {
712 printf("Out of memory in init_allbitflips_array(). Aborting...");
713 exit(4);
714 }
715 set_bitarray24(bitset);
716 all_bitflips_bitarray_dirty[odd_even] = false;
717 num_all_bitflips_bitarray[odd_even] = 1<<24;
718 }
719 }
720
721
722 static void update_allbitflips_array(void)
723 {
724 if (hardnested_stage & CHECK_2ND_BYTES) {
725 for (uint16_t i = 0; i < 256; i++) {
726 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
727 if (nonces[i].all_bitflips_dirty[odd_even]) {
728 uint32_t old_count = num_all_bitflips_bitarray[odd_even];
729 num_all_bitflips_bitarray[odd_even] = count_bitarray_low20_AND(all_bitflips_bitarray[odd_even], nonces[i].states_bitarray[odd_even]);
730 nonces[i].all_bitflips_dirty[odd_even] = false;
731 if (num_all_bitflips_bitarray[odd_even] != old_count) {
732 all_bitflips_bitarray_dirty[odd_even] = true;
733 }
734 }
735 }
736 }
737 }
738 }
739
740
741 static uint32_t estimated_num_states_part_sum_coarse(uint16_t part_sum_a0_idx, uint16_t part_sum_a8_idx, odd_even_t odd_even)
742 {
743 return part_sum_count[odd_even][part_sum_a0_idx][part_sum_a8_idx];
744 }
745
746
747 static uint32_t estimated_num_states_part_sum(uint8_t first_byte, uint16_t part_sum_a0_idx, uint16_t part_sum_a8_idx, odd_even_t odd_even)
748 {
749 if (odd_even == ODD_STATE) {
750 return count_bitarray_AND3(part_sum_a0_bitarrays[odd_even][part_sum_a0_idx],
751 part_sum_a8_bitarrays[odd_even][part_sum_a8_idx],
752 nonces[first_byte].states_bitarray[odd_even]);
753 } else {
754 return count_bitarray_AND4(part_sum_a0_bitarrays[odd_even][part_sum_a0_idx],
755 part_sum_a8_bitarrays[odd_even][part_sum_a8_idx],
756 nonces[first_byte].states_bitarray[odd_even],
757 nonces[first_byte^0x80].states_bitarray[odd_even]);
758 }
759
760 // estimate reduction by all_bitflips_match()
761 // if (odd_even) {
762 // float p_bitflip = (float)nonces[first_byte ^ 0x80].num_states_bitarray[ODD_STATE] / num_all_bitflips_bitarray[ODD_STATE];
763 // return (float)count * p_bitflip; //(p_bitflip - 0.25*p_bitflip*p_bitflip);
764 // } else {
765 // return count;
766 // }
767 }
768
769
770 static uint64_t estimated_num_states(uint8_t first_byte, uint16_t sum_a0, uint16_t sum_a8)
771 {
772 uint64_t num_states = 0;
773 for (uint8_t p = 0; p < NUM_PART_SUMS; p++) {
774 for (uint8_t q = 0; q < NUM_PART_SUMS; q++) {
775 if (2*p*(16-2*q) + (16-2*p)*2*q == sum_a0) {
776 for (uint8_t r = 0; r < NUM_PART_SUMS; r++) {
777 for (uint8_t s = 0; s < NUM_PART_SUMS; s++) {
778 if (2*r*(16-2*s) + (16-2*r)*2*s == sum_a8) {
779 num_states += (uint64_t)estimated_num_states_part_sum(first_byte, p, r, ODD_STATE)
780 * estimated_num_states_part_sum(first_byte, q, s, EVEN_STATE);
781 }
782 }
783 }
784 }
785 }
786 }
787 return num_states;
788 }
789
790
791 static uint64_t estimated_num_states_coarse(uint16_t sum_a0, uint16_t sum_a8)
792 {
793 uint64_t num_states = 0;
794 for (uint8_t p = 0; p < NUM_PART_SUMS; p++) {
795 for (uint8_t q = 0; q < NUM_PART_SUMS; q++) {
796 if (2*p*(16-2*q) + (16-2*p)*2*q == sum_a0) {
797 for (uint8_t r = 0; r < NUM_PART_SUMS; r++) {
798 for (uint8_t s = 0; s < NUM_PART_SUMS; s++) {
799 if (2*r*(16-2*s) + (16-2*r)*2*s == sum_a8) {
800 num_states += (uint64_t)estimated_num_states_part_sum_coarse(p, r, ODD_STATE)
801 * estimated_num_states_part_sum_coarse(q, s, EVEN_STATE);
802 }
803 }
804 }
805 }
806 }
807 }
808 return num_states;
809 }
810
811
812 static void update_p_K(void)
813 {
814 if (hardnested_stage & CHECK_2ND_BYTES) {
815 uint64_t total_count = 0;
816 uint16_t sum_a0 = sums[first_byte_Sum];
817 for (uint8_t sum_a8_idx = 0; sum_a8_idx < NUM_SUMS; sum_a8_idx++) {
818 uint16_t sum_a8 = sums[sum_a8_idx];
819 total_count += estimated_num_states_coarse(sum_a0, sum_a8);
820 }
821 for (uint8_t sum_a8_idx = 0; sum_a8_idx < NUM_SUMS; sum_a8_idx++) {
822 uint16_t sum_a8 = sums[sum_a8_idx];
823 my_p_K[sum_a8_idx] = (float)estimated_num_states_coarse(sum_a0, sum_a8) / total_count;
824 }
825 // printf("my_p_K = [");
826 // for (uint8_t sum_a8_idx = 0; sum_a8_idx < NUM_SUMS; sum_a8_idx++) {
827 // printf("%7.4f ", my_p_K[sum_a8_idx]);
828 // }
829 p_K = my_p_K;
830 }
831 }
832
833
834 static void update_sum_bitarrays(odd_even_t odd_even)
835 {
836 if (all_bitflips_bitarray_dirty[odd_even]) {
837 for (uint8_t part_sum = 0; part_sum < NUM_PART_SUMS; part_sum++) {
838 bitarray_AND(part_sum_a0_bitarrays[odd_even][part_sum], all_bitflips_bitarray[odd_even]);
839 bitarray_AND(part_sum_a8_bitarrays[odd_even][part_sum], all_bitflips_bitarray[odd_even]);
840 }
841 for (uint16_t i = 0; i < 256; i++) {
842 nonces[i].num_states_bitarray[odd_even] = count_bitarray_AND(nonces[i].states_bitarray[odd_even], all_bitflips_bitarray[odd_even]);
843 }
844 for (uint8_t part_sum_a0 = 0; part_sum_a0 < NUM_PART_SUMS; part_sum_a0++) {
845 for (uint8_t part_sum_a8 = 0; part_sum_a8 < NUM_PART_SUMS; part_sum_a8++) {
846 part_sum_count[odd_even][part_sum_a0][part_sum_a8]
847 += count_bitarray_AND2(part_sum_a0_bitarrays[odd_even][part_sum_a0], part_sum_a8_bitarrays[odd_even][part_sum_a8]);
848 }
849 }
850 all_bitflips_bitarray_dirty[odd_even] = false;
851 }
852 }
853
854
855 static int compare_expected_num_brute_force(const void *b1, const void *b2)
856 {
857 uint8_t index1 = *(uint8_t *)b1;
858 uint8_t index2 = *(uint8_t *)b2;
859 float score1 = nonces[index1].expected_num_brute_force;
860 float score2 = nonces[index2].expected_num_brute_force;
861 return (score1 > score2) - (score1 < score2);
862 }
863
864
865 static int compare_sum_a8_guess(const void *b1, const void *b2)
866 {
867 float prob1 = ((guess_sum_a8_t *)b1)->prob;
868 float prob2 = ((guess_sum_a8_t *)b2)->prob;
869 return (prob1 < prob2) - (prob1 > prob2);
870
871 }
872
873
874 static float check_smallest_bitflip_bitarrays(void)
875 {
876 uint32_t num_odd, num_even;
877 uint64_t smallest = 1LL << 48;
878 // initialize best_first_bytes, do a rough estimation on remaining states
879 for (uint16_t i = 0; i < 256; i++) {
880 num_odd = nonces[i].num_states_bitarray[ODD_STATE];
881 num_even = nonces[i].num_states_bitarray[EVEN_STATE]; // * (float)nonces[i^0x80].num_states_bitarray[EVEN_STATE] / num_all_bitflips_bitarray[EVEN_STATE];
882 if ((uint64_t)num_odd * num_even < smallest) {
883 smallest = (uint64_t)num_odd * num_even;
884 best_first_byte_smallest_bitarray = i;
885 }
886 }
887
888 #if defined (DEBUG_REDUCTION)
889 num_odd = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[ODD_STATE];
890 num_even = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[EVEN_STATE]; // * (float)nonces[best_first_byte_smallest_bitarray^0x80].num_states_bitarray[EVEN_STATE] / num_all_bitflips_bitarray[EVEN_STATE];
891 printf("0x%02x: %8d * %8d = %12" PRIu64 " (2^%1.1f)\n", best_first_byte_smallest_bitarray, num_odd, num_even, (uint64_t)num_odd * num_even, log((uint64_t)num_odd * num_even)/log(2.0));
892 #endif
893 return (float)smallest/2.0;
894 }
895
896
897 static void update_expected_brute_force(uint8_t best_byte) {
898
899 float total_prob = 0.0;
900 for (uint8_t i = 0; i < NUM_SUMS; i++) {
901 total_prob += nonces[best_byte].sum_a8_guess[i].prob;
902 }
903 // linear adjust probabilities to result in total_prob = 1.0;
904 for (uint8_t i = 0; i < NUM_SUMS; i++) {
905 nonces[best_byte].sum_a8_guess[i].prob /= total_prob;
906 }
907 float prob_all_failed = 1.0;
908 nonces[best_byte].expected_num_brute_force = 0.0;
909 for (uint8_t i = 0; i < NUM_SUMS; i++) {
910 nonces[best_byte].expected_num_brute_force += nonces[best_byte].sum_a8_guess[i].prob * (float)nonces[best_byte].sum_a8_guess[i].num_states / 2.0;
911 prob_all_failed -= nonces[best_byte].sum_a8_guess[i].prob;
912 nonces[best_byte].expected_num_brute_force += prob_all_failed * (float)nonces[best_byte].sum_a8_guess[i].num_states / 2.0;
913 }
914 return;
915 }
916
917
918 static float sort_best_first_bytes(void)
919 {
920
921 // initialize best_first_bytes, do a rough estimation on remaining states for each Sum_a8 property
922 // and the expected number of states to brute force
923 for (uint16_t i = 0; i < 256; i++) {
924 best_first_bytes[i] = i;
925 float prob_all_failed = 1.0;
926 nonces[i].expected_num_brute_force = 0.0;
927 for (uint8_t j = 0; j < NUM_SUMS; j++) {
928 nonces[i].sum_a8_guess[j].num_states = estimated_num_states_coarse(sums[first_byte_Sum], sums[nonces[i].sum_a8_guess[j].sum_a8_idx]);
929 nonces[i].expected_num_brute_force += nonces[i].sum_a8_guess[j].prob * (float)nonces[i].sum_a8_guess[j].num_states / 2.0;
930 prob_all_failed -= nonces[i].sum_a8_guess[j].prob;
931 nonces[i].expected_num_brute_force += prob_all_failed * (float)nonces[i].sum_a8_guess[j].num_states / 2.0;
932 }
933 }
934
935 // sort based on expected number of states to brute force
936 qsort(best_first_bytes, 256, 1, compare_expected_num_brute_force);
937
938 // printf("refine estimations: ");
939 #define NUM_REFINES 1
940 // refine scores for the best:
941 for (uint16_t i = 0; i < NUM_REFINES; i++) {
942 // printf("%d...", i);
943 uint16_t first_byte = best_first_bytes[i];
944 for (uint8_t j = 0; j < NUM_SUMS && nonces[first_byte].sum_a8_guess[j].prob > 0.05; j++) {
945 nonces[first_byte].sum_a8_guess[j].num_states = estimated_num_states(first_byte, sums[first_byte_Sum], sums[nonces[first_byte].sum_a8_guess[j].sum_a8_idx]);
946 }
947 // while (nonces[first_byte].sum_a8_guess[0].num_states == 0
948 // || nonces[first_byte].sum_a8_guess[1].num_states == 0
949 // || nonces[first_byte].sum_a8_guess[2].num_states == 0) {
950 // if (nonces[first_byte].sum_a8_guess[0].num_states == 0) {
951 // nonces[first_byte].sum_a8_guess[0].prob = 0.0;
952 // printf("(0x%02x,%d)", first_byte, 0);
953 // }
954 // if (nonces[first_byte].sum_a8_guess[1].num_states == 0) {
955 // nonces[first_byte].sum_a8_guess[1].prob = 0.0;
956 // printf("(0x%02x,%d)", first_byte, 1);
957 // }
958 // if (nonces[first_byte].sum_a8_guess[2].num_states == 0) {
959 // nonces[first_byte].sum_a8_guess[2].prob = 0.0;
960 // printf("(0x%02x,%d)", first_byte, 2);
961 // }
962 // printf("|");
963 // qsort(nonces[first_byte].sum_a8_guess, NUM_SUMS, sizeof(guess_sum_a8_t), compare_sum_a8_guess);
964 // for (uint8_t j = 0; j < NUM_SUMS && nonces[first_byte].sum_a8_guess[j].prob > 0.05; j++) {
965 // nonces[first_byte].sum_a8_guess[j].num_states = estimated_num_states(first_byte, sums[first_byte_Sum], sums[nonces[first_byte].sum_a8_guess[j].sum_a8_idx]);
966 // }
967 // }
968 // float fix_probs = 0.0;
969 // for (uint8_t j = 0; j < NUM_SUMS; j++) {
970 // fix_probs += nonces[first_byte].sum_a8_guess[j].prob;
971 // }
972 // for (uint8_t j = 0; j < NUM_SUMS; j++) {
973 // nonces[first_byte].sum_a8_guess[j].prob /= fix_probs;
974 // }
975 // for (uint8_t j = 0; j < NUM_SUMS && nonces[first_byte].sum_a8_guess[j].prob > 0.05; j++) {
976 // nonces[first_byte].sum_a8_guess[j].num_states = estimated_num_states(first_byte, sums[first_byte_Sum], sums[nonces[first_byte].sum_a8_guess[j].sum_a8_idx]);
977 // }
978 float prob_all_failed = 1.0;
979 nonces[first_byte].expected_num_brute_force = 0.0;
980 for (uint8_t j = 0; j < NUM_SUMS; j++) {
981 nonces[first_byte].expected_num_brute_force += nonces[first_byte].sum_a8_guess[j].prob * (float)nonces[first_byte].sum_a8_guess[j].num_states / 2.0;
982 prob_all_failed -= nonces[first_byte].sum_a8_guess[j].prob;
983 nonces[first_byte].expected_num_brute_force += prob_all_failed * (float)nonces[first_byte].sum_a8_guess[j].num_states / 2.0;
984 }
985 }
986
987 // copy best byte to front:
988 float least_expected_brute_force = (1LL << 48);
989 uint8_t best_byte = 0;
990 for (uint16_t i = 0; i < 10; i++) {
991 uint16_t first_byte = best_first_bytes[i];
992 if (nonces[first_byte].expected_num_brute_force < least_expected_brute_force) {
993 least_expected_brute_force = nonces[first_byte].expected_num_brute_force;
994 best_byte = i;
995 }
996 }
997 if (best_byte != 0) {
998 // printf("0x%02x <-> 0x%02x", best_first_bytes[0], best_first_bytes[best_byte]);
999 uint8_t tmp = best_first_bytes[0];
1000 best_first_bytes[0] = best_first_bytes[best_byte];
1001 best_first_bytes[best_byte] = tmp;
1002 }
1003
1004 return nonces[best_first_bytes[0]].expected_num_brute_force;
1005 }
1006
1007
1008 static float update_reduction_rate(float last, bool init)
1009 {
1010 #define QUEUE_LEN 4
1011 static float queue[QUEUE_LEN];
1012
1013 for (uint16_t i = 0; i < QUEUE_LEN-1; i++) {
1014 if (init) {
1015 queue[i] = (float)(1LL << 48);
1016 } else {
1017 queue[i] = queue[i+1];
1018 }
1019 }
1020 if (init) {
1021 queue[QUEUE_LEN-1] = (float)(1LL << 48);
1022 } else {
1023 queue[QUEUE_LEN-1] = last;
1024 }
1025
1026 // linear regression
1027 float avg_y = 0.0;
1028 float avg_x = 0.0;
1029 for (uint16_t i = 0; i < QUEUE_LEN; i++) {
1030 avg_x += i;
1031 avg_y += queue[i];
1032 }
1033 avg_x /= QUEUE_LEN;
1034 avg_y /= QUEUE_LEN;
1035
1036 float dev_xy = 0.0;
1037 float dev_x2 = 0.0;
1038 for (uint16_t i = 0; i < QUEUE_LEN; i++) {
1039 dev_xy += (i - avg_x)*(queue[i] - avg_y);
1040 dev_x2 += (i - avg_x)*(i - avg_x);
1041 }
1042
1043 float reduction_rate = -1.0 * dev_xy / dev_x2; // the negative slope of the linear regression
1044
1045 #if defined (DEBUG_REDUCTION)
1046 printf("update_reduction_rate(%1.0f) = %1.0f per sample, brute_force_per_sample = %1.0f\n", last, reduction_rate, brute_force_per_second * (float)sample_period / 1000.0);
1047 #endif
1048 return reduction_rate;
1049 }
1050
1051
1052 static bool shrink_key_space(float *brute_forces)
1053 {
1054 #if defined(DEBUG_REDUCTION)
1055 printf("shrink_key_space() with stage = 0x%02x\n", hardnested_stage);
1056 #endif
1057 float brute_forces1 = check_smallest_bitflip_bitarrays();
1058 float brute_forces2 = (float)(1LL << 47);
1059 if (hardnested_stage & CHECK_2ND_BYTES) {
1060 brute_forces2 = sort_best_first_bytes();
1061 }
1062 *brute_forces = MIN(brute_forces1, brute_forces2);
1063 float reduction_rate = update_reduction_rate(*brute_forces, false);
1064 return ((hardnested_stage & CHECK_2ND_BYTES)
1065 && reduction_rate >= 0.0 && reduction_rate < brute_force_per_second * sample_period / 1000.0);
1066 }
1067
1068
1069 static void estimate_sum_a8(void)
1070 {
1071 if (first_byte_num == 256) {
1072 for (uint16_t i = 0; i < 256; i++) {
1073 if (nonces[i].sum_a8_guess_dirty) {
1074 for (uint16_t j = 0; j < NUM_SUMS; j++ ) {
1075 uint16_t sum_a8_idx = nonces[i].sum_a8_guess[j].sum_a8_idx;
1076 nonces[i].sum_a8_guess[j].prob = sum_probability(sum_a8_idx, nonces[i].num, nonces[i].Sum);
1077 }
1078 qsort(nonces[i].sum_a8_guess, NUM_SUMS, sizeof(guess_sum_a8_t), compare_sum_a8_guess);
1079 nonces[i].sum_a8_guess_dirty = false;
1080 }
1081 }
1082 }
1083 }
1084
1085
1086 static int read_nonce_file(void)
1087 {
1088 FILE *fnonces = NULL;
1089 size_t bytes_read;
1090 uint8_t trgBlockNo;
1091 uint8_t trgKeyType;
1092 uint8_t read_buf[9];
1093 uint32_t nt_enc1, nt_enc2;
1094 uint8_t par_enc;
1095
1096 num_acquired_nonces = 0;
1097 if ((fnonces = fopen("nonces.bin","rb")) == NULL) {
1098 PrintAndLog("Could not open file nonces.bin");
1099 return 1;
1100 }
1101
1102 hardnested_print_progress(0, "Reading nonces from file nonces.bin...", (float)(1LL<<47), 0);
1103 bytes_read = fread(read_buf, 1, 6, fnonces);
1104 if (bytes_read != 6) {
1105 PrintAndLog("File reading error.");
1106 fclose(fnonces);
1107 return 1;
1108 }
1109 cuid = bytes_to_num(read_buf, 4);
1110 trgBlockNo = bytes_to_num(read_buf+4, 1);
1111 trgKeyType = bytes_to_num(read_buf+5, 1);
1112
1113 bytes_read = fread(read_buf, 1, 9, fnonces);
1114 while (bytes_read == 9) {
1115 nt_enc1 = bytes_to_num(read_buf, 4);
1116 nt_enc2 = bytes_to_num(read_buf+4, 4);
1117 par_enc = bytes_to_num(read_buf+8, 1);
1118 add_nonce(nt_enc1, par_enc >> 4);
1119 add_nonce(nt_enc2, par_enc & 0x0f);
1120 num_acquired_nonces += 2;
1121 bytes_read = fread(read_buf, 1, 9, fnonces);
1122 }
1123 fclose(fnonces);
1124
1125 char progress_string[80];
1126 sprintf(progress_string, "Read %d nonces from file. cuid=%08x", num_acquired_nonces, cuid);
1127 hardnested_print_progress(num_acquired_nonces, progress_string, (float)(1LL<<47), 0);
1128 sprintf(progress_string, "Target Block=%d, Keytype=%c", trgBlockNo, trgKeyType==0?'A':'B');
1129 hardnested_print_progress(num_acquired_nonces, progress_string, (float)(1LL<<47), 0);
1130
1131 for (uint16_t i = 0; i < NUM_SUMS; i++) {
1132 if (first_byte_Sum == sums[i]) {
1133 first_byte_Sum = i;
1134 break;
1135 }
1136 }
1137
1138 return 0;
1139 }
1140
1141
1142 noncelistentry_t *SearchFor2ndByte(uint8_t b1, uint8_t b2)
1143 {
1144 noncelistentry_t *p = nonces[b1].first;
1145 while (p != NULL) {
1146 if ((p->nonce_enc >> 16 & 0xff) == b2) {
1147 return p;
1148 }
1149 p = p->next;
1150 }
1151 return NULL;
1152 }
1153
1154
1155 static bool timeout(void)
1156 {
1157 return (msclock() > last_sample_clock + sample_period);
1158 }
1159
1160
1161 static void *check_for_BitFlipProperties_thread(void *args)
1162 {
1163 uint8_t first_byte = ((uint8_t *)args)[0];
1164 uint8_t last_byte = ((uint8_t *)args)[1];
1165 uint8_t time_budget = ((uint8_t *)args)[2];
1166
1167 if (hardnested_stage & CHECK_1ST_BYTES) {
1168 // for (uint16_t bitflip = 0x001; bitflip < 0x200; bitflip++) {
1169 for (uint16_t bitflip_idx = 0; bitflip_idx < num_1st_byte_effective_bitflips; bitflip_idx++) {
1170 uint16_t bitflip = all_effective_bitflip[bitflip_idx];
1171 if (time_budget & timeout()) {
1172 #if defined (DEBUG_REDUCTION)
1173 printf("break at bitflip_idx %d...", bitflip_idx);
1174 #endif
1175 return NULL;
1176 }
1177 for (uint16_t i = first_byte; i <= last_byte; i++) {
1178 if (nonces[i].BitFlips[bitflip] == 0 && nonces[i].BitFlips[bitflip ^ 0x100] == 0
1179 && nonces[i].first != NULL && nonces[i^(bitflip&0xff)].first != NULL) {
1180 uint8_t parity1 = (nonces[i].first->par_enc) >> 3; // parity of first byte
1181 uint8_t parity2 = (nonces[i^(bitflip&0xff)].first->par_enc) >> 3; // parity of nonce with bits flipped
1182 if ((parity1 == parity2 && !(bitflip & 0x100)) // bitflip
1183 || (parity1 != parity2 && (bitflip & 0x100))) { // not bitflip
1184 nonces[i].BitFlips[bitflip] = 1;
1185 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
1186 if (bitflip_bitarrays[odd_even][bitflip] != NULL) {
1187 uint32_t old_count = nonces[i].num_states_bitarray[odd_even];
1188 nonces[i].num_states_bitarray[odd_even] = count_bitarray_AND(nonces[i].states_bitarray[odd_even], bitflip_bitarrays[odd_even][bitflip]);
1189 if (nonces[i].num_states_bitarray[odd_even] != old_count) {
1190 nonces[i].all_bitflips_dirty[odd_even] = true;
1191 }
1192 // printf("bitflip: %d old: %d, new: %d ", bitflip, old_count, nonces[i].num_states_bitarray[odd_even]);
1193 }
1194 }
1195 }
1196 }
1197 }
1198 ((uint8_t *)args)[1] = num_1st_byte_effective_bitflips - bitflip_idx - 1; // bitflips still to go in stage 1
1199 }
1200 }
1201
1202 ((uint8_t *)args)[1] = 0; // stage 1 definitely completed
1203
1204 if (hardnested_stage & CHECK_2ND_BYTES) {
1205 for (uint16_t bitflip_idx = num_1st_byte_effective_bitflips; bitflip_idx < num_all_effective_bitflips; bitflip_idx++) {
1206 uint16_t bitflip = all_effective_bitflip[bitflip_idx];
1207 if (time_budget & timeout()) {
1208 #if defined (DEBUG_REDUCTION)
1209 printf("break at bitflip_idx %d...", bitflip_idx);
1210 #endif
1211 return NULL;
1212 }
1213 for (uint16_t i = first_byte; i <= last_byte; i++) {
1214 // Check for Bit Flip Property of 2nd bytes
1215 if (nonces[i].BitFlips[bitflip] == 0) {
1216 for (uint16_t j = 0; j < 256; j++) { // for each 2nd Byte
1217 noncelistentry_t *byte1 = SearchFor2ndByte(i, j);
1218 noncelistentry_t *byte2 = SearchFor2ndByte(i, j^(bitflip&0xff));
1219 if (byte1 != NULL && byte2 != NULL) {
1220 uint8_t parity1 = byte1->par_enc >> 2 & 0x01; // parity of 2nd byte
1221 uint8_t parity2 = byte2->par_enc >> 2 & 0x01; // parity of 2nd byte with bits flipped
1222 if ((parity1 == parity2 && !(bitflip&0x100)) // bitflip
1223 || (parity1 != parity2 && (bitflip&0x100))) { // not bitflip
1224 nonces[i].BitFlips[bitflip] = 1;
1225 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
1226 if (bitflip_bitarrays[odd_even][bitflip] != NULL) {
1227 uint32_t old_count = nonces[i].num_states_bitarray[odd_even];
1228 nonces[i].num_states_bitarray[odd_even] = count_bitarray_AND(nonces[i].states_bitarray[odd_even], bitflip_bitarrays[odd_even][bitflip]);
1229 if (nonces[i].num_states_bitarray[odd_even] != old_count) {
1230 nonces[i].all_bitflips_dirty[odd_even] = true;
1231 }
1232 }
1233 }
1234 break;
1235 }
1236 }
1237 }
1238 }
1239 // printf("states_bitarray[0][%" PRIu16 "] contains %d ones.\n", i, count_states(nonces[i].states_bitarray[EVEN_STATE]));
1240 // printf("states_bitarray[1][%" PRIu16 "] contains %d ones.\n", i, count_states(nonces[i].states_bitarray[ODD_STATE]));
1241 }
1242 }
1243 }
1244
1245 return NULL;
1246 }
1247
1248
1249 static void check_for_BitFlipProperties(bool time_budget)
1250 {
1251 // create and run worker threads
1252 pthread_t thread_id[NUM_CHECK_BITFLIPS_THREADS];
1253
1254 uint8_t args[NUM_CHECK_BITFLIPS_THREADS][3];
1255 uint16_t bytes_per_thread = (256 + (NUM_CHECK_BITFLIPS_THREADS/2)) / NUM_CHECK_BITFLIPS_THREADS;
1256 for (uint8_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) {
1257 args[i][0] = i * bytes_per_thread;
1258 args[i][1] = MIN(args[i][0]+bytes_per_thread-1, 255);
1259 args[i][2] = time_budget;
1260 }
1261 args[NUM_CHECK_BITFLIPS_THREADS-1][1] = MAX(args[NUM_CHECK_BITFLIPS_THREADS-1][1], 255);
1262
1263 // start threads
1264 for (uint8_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) {
1265 pthread_create(&thread_id[i], NULL, check_for_BitFlipProperties_thread, args[i]);
1266 }
1267
1268 // wait for threads to terminate:
1269 for (uint8_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) {
1270 pthread_join(thread_id[i], NULL);
1271 }
1272
1273 if (hardnested_stage & CHECK_2ND_BYTES) {
1274 hardnested_stage &= ~CHECK_1ST_BYTES; // we are done with 1st stage, except...
1275 for (uint16_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) {
1276 if (args[i][1] != 0) {
1277 hardnested_stage |= CHECK_1ST_BYTES; // ... when any of the threads didn't complete in time
1278 break;
1279 }
1280 }
1281 }
1282 #if defined (DEBUG_REDUCTION)
1283 if (hardnested_stage & CHECK_1ST_BYTES) printf("stage 1 not completed yet\n");
1284 #endif
1285 }
1286
1287
1288 static void update_nonce_data(bool time_budget)
1289 {
1290 check_for_BitFlipProperties(time_budget);
1291 update_allbitflips_array();
1292 update_sum_bitarrays(EVEN_STATE);
1293 update_sum_bitarrays(ODD_STATE);
1294 update_p_K();
1295 estimate_sum_a8();
1296 }
1297
1298
1299 static void apply_sum_a0(void)
1300 {
1301 uint32_t old_count = num_all_bitflips_bitarray[EVEN_STATE];
1302 num_all_bitflips_bitarray[EVEN_STATE] = count_bitarray_AND(all_bitflips_bitarray[EVEN_STATE], sum_a0_bitarrays[EVEN_STATE][first_byte_Sum]);
1303 if (num_all_bitflips_bitarray[EVEN_STATE] != old_count) {
1304 all_bitflips_bitarray_dirty[EVEN_STATE] = true;
1305 }
1306 old_count = num_all_bitflips_bitarray[ODD_STATE];
1307 num_all_bitflips_bitarray[ODD_STATE] = count_bitarray_AND(all_bitflips_bitarray[ODD_STATE], sum_a0_bitarrays[ODD_STATE][first_byte_Sum]);
1308 if (num_all_bitflips_bitarray[ODD_STATE] != old_count) {
1309 all_bitflips_bitarray_dirty[ODD_STATE] = true;
1310 }
1311 }
1312
1313
1314 static void simulate_MFplus_RNG(uint32_t test_cuid, uint64_t test_key, uint32_t *nt_enc, uint8_t *par_enc)
1315 {
1316 struct Crypto1State sim_cs = {0, 0};
1317
1318 // init cryptostate with key:
1319 for(int8_t i = 47; i > 0; i -= 2) {
1320 sim_cs.odd = sim_cs.odd << 1 | BIT(test_key, (i - 1) ^ 7);
1321 sim_cs.even = sim_cs.even << 1 | BIT(test_key, i ^ 7);
1322 }
1323
1324 *par_enc = 0;
1325 uint32_t nt = (rand() & 0xff) << 24 | (rand() & 0xff) << 16 | (rand() & 0xff) << 8 | (rand() & 0xff);
1326 for (int8_t byte_pos = 3; byte_pos >= 0; byte_pos--) {
1327 uint8_t nt_byte_dec = (nt >> (8*byte_pos)) & 0xff;
1328 uint8_t nt_byte_enc = crypto1_byte(&sim_cs, nt_byte_dec ^ (test_cuid >> (8*byte_pos)), false) ^ nt_byte_dec; // encode the nonce byte
1329 *nt_enc = (*nt_enc << 8) | nt_byte_enc;
1330 uint8_t ks_par = filter(sim_cs.odd); // the keystream bit to encode/decode the parity bit
1331 uint8_t nt_byte_par_enc = ks_par ^ oddparity8(nt_byte_dec); // determine the nt byte's parity and encode it
1332 *par_enc = (*par_enc << 1) | nt_byte_par_enc;
1333 }
1334
1335 }
1336
1337
1338 static void simulate_acquire_nonces()
1339 {
1340 time_t time1 = time(NULL);
1341 last_sample_clock = 0;
1342 sample_period = 1000; // for simulation
1343 hardnested_stage = CHECK_1ST_BYTES;
1344 bool acquisition_completed = false;
1345 uint32_t total_num_nonces = 0;
1346 float brute_force;
1347 bool reported_suma8 = false;
1348
1349 cuid = (rand() & 0xff) << 24 | (rand() & 0xff) << 16 | (rand() & 0xff) << 8 | (rand() & 0xff);
1350 if (known_target_key == -1) {
1351 known_target_key = ((uint64_t)rand() & 0xfff) << 36 | ((uint64_t)rand() & 0xfff) << 24 | ((uint64_t)rand() & 0xfff) << 12 | ((uint64_t)rand() & 0xfff);
1352 }
1353
1354 char progress_text[80];
1355 sprintf(progress_text, "Simulating key %012" PRIx64 ", cuid %08" PRIx32 " ...", known_target_key, cuid);
1356 hardnested_print_progress(0, progress_text, (float)(1LL<<47), 0);
1357 fprintf(fstats, "%012" PRIx64 ";%" PRIx32 ";", known_target_key, cuid);
1358
1359 num_acquired_nonces = 0;
1360
1361 do {
1362 uint32_t nt_enc = 0;
1363 uint8_t par_enc = 0;
1364
1365 for (uint16_t i = 0; i < 113; i++) {
1366 simulate_MFplus_RNG(cuid, known_target_key, &nt_enc, &par_enc);
1367 num_acquired_nonces += add_nonce(nt_enc, par_enc);
1368 total_num_nonces++;
1369 }
1370
1371 last_sample_clock = msclock();
1372
1373 if (first_byte_num == 256 ) {
1374 if (hardnested_stage == CHECK_1ST_BYTES) {
1375 for (uint16_t i = 0; i < NUM_SUMS; i++) {
1376 if (first_byte_Sum == sums[i]) {
1377 first_byte_Sum = i;
1378 break;
1379 }
1380 }
1381 hardnested_stage |= CHECK_2ND_BYTES;
1382 apply_sum_a0();
1383 }
1384 update_nonce_data(true);
1385 acquisition_completed = shrink_key_space(&brute_force);
1386 if (!reported_suma8) {
1387 char progress_string[80];
1388 sprintf(progress_string, "Apply Sum property. Sum(a0) = %d", sums[first_byte_Sum]);
1389 hardnested_print_progress(num_acquired_nonces, progress_string, brute_force, 0);
1390 reported_suma8 = true;
1391 } else {
1392 hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
1393 }
1394 } else {
1395 update_nonce_data(true);
1396 acquisition_completed = shrink_key_space(&brute_force);
1397 hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
1398 }
1399 } while (!acquisition_completed);
1400
1401 time_t end_time = time(NULL);
1402 // PrintAndLog("Acquired a total of %" PRId32" nonces in %1.0f seconds (%1.0f nonces/minute)",
1403 // num_acquired_nonces,
1404 // difftime(end_time, time1),
1405 // difftime(end_time, time1)!=0.0?(float)total_num_nonces*60.0/difftime(end_time, time1):INFINITY
1406 // );
1407
1408 fprintf(fstats, "%" PRId32 ";%" PRId32 ";%1.0f;", total_num_nonces, num_acquired_nonces, difftime(end_time,time1));
1409
1410 }
1411
1412
1413 static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, bool nonce_file_write, bool slow)
1414 {
1415 last_sample_clock = msclock();
1416 sample_period = 2000; // initial rough estimate. Will be refined.
1417 bool initialize = true;
1418 bool field_off = false;
1419 hardnested_stage = CHECK_1ST_BYTES;
1420 bool acquisition_completed = false;
1421 uint32_t flags = 0;
1422 uint8_t write_buf[9];
1423 uint32_t total_num_nonces = 0;
1424 float brute_force;
1425 bool reported_suma8 = false;
1426 FILE *fnonces = NULL;
1427 UsbCommand resp;
1428
1429 num_acquired_nonces = 0;
1430
1431 clearCommandBuffer();
1432
1433 do {
1434 flags = 0;
1435 flags |= initialize ? 0x0001 : 0;
1436 flags |= slow ? 0x0002 : 0;
1437 flags |= field_off ? 0x0004 : 0;
1438 UsbCommand c = {CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, flags}};
1439 memcpy(c.d.asBytes, key, 6);
1440
1441 SendCommand(&c);
1442
1443 if (field_off) break;
1444
1445 if (initialize) {
1446 if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) return 1;
1447
1448 if (resp.arg[0]) return resp.arg[0]; // error during nested_hard
1449
1450 cuid = resp.arg[1];
1451 // PrintAndLog("Acquiring nonces for CUID 0x%08x", cuid);
1452 if (nonce_file_write && fnonces == NULL) {
1453 if ((fnonces = fopen("nonces.bin","wb")) == NULL) {
1454 PrintAndLog("Could not create file nonces.bin");
1455 return 3;
1456 }
1457 hardnested_print_progress(0, "Writing acquired nonces to binary file nonces.bin", (float)(1LL<<47), 0);
1458 num_to_bytes(cuid, 4, write_buf);
1459 fwrite(write_buf, 1, 4, fnonces);
1460 fwrite(&trgBlockNo, 1, 1, fnonces);
1461 fwrite(&trgKeyType, 1, 1, fnonces);
1462 }
1463 }
1464
1465 if (!initialize) {
1466 uint32_t nt_enc1, nt_enc2;
1467 uint8_t par_enc;
1468 uint16_t num_sampled_nonces = resp.arg[2];
1469 uint8_t *bufp = resp.d.asBytes;
1470 for (uint16_t i = 0; i < num_sampled_nonces; i+=2) {
1471 nt_enc1 = bytes_to_num(bufp, 4);
1472 nt_enc2 = bytes_to_num(bufp+4, 4);
1473 par_enc = bytes_to_num(bufp+8, 1);
1474
1475 //printf("Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc1, par_enc >> 4);
1476 num_acquired_nonces += add_nonce(nt_enc1, par_enc >> 4);
1477 //printf("Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc2, par_enc & 0x0f);
1478 num_acquired_nonces += add_nonce(nt_enc2, par_enc & 0x0f);
1479
1480 if (nonce_file_write) {
1481 fwrite(bufp, 1, 9, fnonces);
1482 }
1483 bufp += 9;
1484 }
1485 total_num_nonces += num_sampled_nonces;
1486
1487 if (first_byte_num == 256 ) {
1488 if (hardnested_stage == CHECK_1ST_BYTES) {
1489 for (uint16_t i = 0; i < NUM_SUMS; i++) {
1490 if (first_byte_Sum == sums[i]) {
1491 first_byte_Sum = i;
1492 break;
1493 }
1494 }
1495 hardnested_stage |= CHECK_2ND_BYTES;
1496 apply_sum_a0();
1497 }
1498 update_nonce_data(true);
1499 acquisition_completed = shrink_key_space(&brute_force);
1500 if (!reported_suma8) {
1501 char progress_string[80];
1502 sprintf(progress_string, "Apply Sum property. Sum(a0) = %d", sums[first_byte_Sum]);
1503 hardnested_print_progress(num_acquired_nonces, progress_string, brute_force, 0);
1504 reported_suma8 = true;
1505 } else {
1506 hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
1507 }
1508 } else {
1509 update_nonce_data(true);
1510 acquisition_completed = shrink_key_space(&brute_force);
1511 hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0);
1512 }
1513 }
1514
1515 if (acquisition_completed) {
1516 field_off = true; // switch off field with next SendCommand and then finish
1517 }
1518
1519 if (!initialize) {
1520 if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) {
1521 if (nonce_file_write) {
1522 fclose(fnonces);
1523 }
1524 return 1;
1525 }
1526 if (resp.arg[0]) {
1527 if (nonce_file_write) {
1528 fclose(fnonces);
1529 }
1530 return resp.arg[0]; // error during nested_hard
1531 }
1532 }
1533
1534 initialize = false;
1535
1536 if (msclock() - last_sample_clock < sample_period) {
1537 sample_period = msclock() - last_sample_clock;
1538 }
1539 last_sample_clock = msclock();
1540
1541 } while (!acquisition_completed || field_off);
1542
1543 if (nonce_file_write) {
1544 fclose(fnonces);
1545 }
1546
1547 // PrintAndLog("Sampled a total of %d nonces in %d seconds (%0.0f nonces/minute)",
1548 // total_num_nonces,
1549 // time(NULL)-time1,
1550 // (float)total_num_nonces*60.0/(time(NULL)-time1));
1551
1552 return 0;
1553 }
1554
1555
1556 static inline bool invariant_holds(uint_fast8_t byte_diff, uint_fast32_t state1, uint_fast32_t state2, uint_fast8_t bit, uint_fast8_t state_bit)
1557 {
1558 uint_fast8_t j_1_bit_mask = 0x01 << (bit-1);
1559 uint_fast8_t bit_diff = byte_diff & j_1_bit_mask; // difference of (j-1)th bit
1560 uint_fast8_t filter_diff = filter(state1 >> (4-state_bit)) ^ filter(state2 >> (4-state_bit)); // difference in filter function
1561 uint_fast8_t mask_y12_y13 = 0xc0 >> state_bit;
1562 uint_fast8_t state_bits_diff = (state1 ^ state2) & mask_y12_y13; // difference in state bits 12 and 13
1563 uint_fast8_t all_diff = evenparity8(bit_diff ^ state_bits_diff ^ filter_diff); // use parity function to XOR all bits
1564 return !all_diff;
1565 }
1566
1567
1568 static inline bool invalid_state(uint_fast8_t byte_diff, uint_fast32_t state1, uint_fast32_t state2, uint_fast8_t bit, uint_fast8_t state_bit)
1569 {
1570 uint_fast8_t j_bit_mask = 0x01 << bit;
1571 uint_fast8_t bit_diff = byte_diff & j_bit_mask; // difference of jth bit
1572 uint_fast8_t mask_y13_y16 = 0x48 >> state_bit;
1573 uint_fast8_t state_bits_diff = (state1 ^ state2) & mask_y13_y16; // difference in state bits 13 and 16
1574 uint_fast8_t all_diff = evenparity8(bit_diff ^ state_bits_diff); // use parity function to XOR all bits
1575 return all_diff;
1576 }
1577
1578
1579 static inline bool remaining_bits_match(uint_fast8_t num_common_bits, uint_fast8_t byte_diff, uint_fast32_t state1, uint_fast32_t state2, odd_even_t odd_even)
1580 {
1581 if (odd_even) {
1582 // odd bits
1583 switch (num_common_bits) {
1584 case 0: if (!invariant_holds(byte_diff, state1, state2, 1, 0)) return true;
1585 case 1: if (invalid_state(byte_diff, state1, state2, 1, 0)) return false;
1586 case 2: if (!invariant_holds(byte_diff, state1, state2, 3, 1)) return true;
1587 case 3: if (invalid_state(byte_diff, state1, state2, 3, 1)) return false;
1588 case 4: if (!invariant_holds(byte_diff, state1, state2, 5, 2)) return true;
1589 case 5: if (invalid_state(byte_diff, state1, state2, 5, 2)) return false;
1590 case 6: if (!invariant_holds(byte_diff, state1, state2, 7, 3)) return true;
1591 case 7: if (invalid_state(byte_diff, state1, state2, 7, 3)) return false;
1592 }
1593 } else {
1594 // even bits
1595 switch (num_common_bits) {
1596 case 0: if (invalid_state(byte_diff, state1, state2, 0, 0)) return false;
1597 case 1: if (!invariant_holds(byte_diff, state1, state2, 2, 1)) return true;
1598 case 2: if (invalid_state(byte_diff, state1, state2, 2, 1)) return false;
1599 case 3: if (!invariant_holds(byte_diff, state1, state2, 4, 2)) return true;
1600 case 4: if (invalid_state(byte_diff, state1, state2, 4, 2)) return false;
1601 case 5: if (!invariant_holds(byte_diff, state1, state2, 6, 3)) return true;
1602 case 6: if (invalid_state(byte_diff, state1, state2, 6, 3)) return false;
1603 }
1604 }
1605
1606 return true; // valid state
1607 }
1608
1609
1610 static pthread_mutex_t statelist_cache_mutex;
1611 static pthread_mutex_t book_of_work_mutex;
1612
1613
1614 typedef enum {
1615 TO_BE_DONE,
1616 WORK_IN_PROGRESS,
1617 COMPLETED
1618 } work_status_t;
1619
1620 static struct sl_cache_entry {
1621 uint32_t *sl;
1622 uint32_t len;
1623 work_status_t cache_status;
1624 } sl_cache[NUM_PART_SUMS][NUM_PART_SUMS][2];
1625
1626
1627 static void init_statelist_cache(void)
1628 {
1629 pthread_mutex_lock(&statelist_cache_mutex);
1630 for (uint16_t i = 0; i < NUM_PART_SUMS; i++) {
1631 for (uint16_t j = 0; j < NUM_PART_SUMS; j++) {
1632 for (uint16_t k = 0; k < 2; k++) {
1633 sl_cache[i][j][k].sl = NULL;
1634 sl_cache[i][j][k].len = 0;
1635 sl_cache[i][j][k].cache_status = TO_BE_DONE;
1636 }
1637 }
1638 }
1639 pthread_mutex_unlock(&statelist_cache_mutex);
1640 }
1641
1642
1643 static void free_statelist_cache(void)
1644 {
1645 pthread_mutex_lock(&statelist_cache_mutex);
1646 for (uint16_t i = 0; i < NUM_PART_SUMS; i++) {
1647 for (uint16_t j = 0; j < NUM_PART_SUMS; j++) {
1648 for (uint16_t k = 0; k < 2; k++) {
1649 free(sl_cache[i][j][k].sl);
1650 }
1651 }
1652 }
1653 pthread_mutex_unlock(&statelist_cache_mutex);
1654 }
1655
1656
1657 #ifdef DEBUG_KEY_ELIMINATION
1658 static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even, bool quiet)
1659 #else
1660 static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even)
1661 #endif
1662 {
1663 uint32_t *bitset = nonces[byte].states_bitarray[odd_even];
1664 bool possible = test_bit24(bitset, state);
1665 if (!possible) {
1666 #ifdef DEBUG_KEY_ELIMINATION
1667 if (!quiet && known_target_key != -1 && state == test_state[odd_even]) {
1668 printf("Initial state lists: %s test state eliminated by bitflip property.\n", odd_even==EVEN_STATE?"even":"odd");
1669 sprintf(failstr, "Initial %s Byte Bitflip property", odd_even==EVEN_STATE?"even":"odd");
1670 }
1671 #endif
1672 return false;
1673 } else {
1674 return true;
1675 }
1676 }
1677
1678
1679 static uint_fast8_t reverse(uint_fast8_t byte)
1680 {
1681 uint_fast8_t rev_byte = 0;
1682
1683 for (uint8_t i = 0; i < 8; i++) {
1684 rev_byte <<= 1;
1685 rev_byte |= (byte >> i) & 0x01;
1686 }
1687
1688 return rev_byte;
1689 }
1690
1691
1692 static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even)
1693 {
1694 uint32_t masks[2][8] = {{0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe, 0x00ffffff},
1695 {0x00fffff0, 0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe} };
1696
1697 for (uint16_t i = 1; i < 256; i++) {
1698 uint_fast8_t bytes_diff = reverse(i); // start with most common bits
1699 uint_fast8_t byte2 = byte ^ bytes_diff;
1700 uint_fast8_t num_common = trailing_zeros(bytes_diff);
1701 uint32_t mask = masks[odd_even][num_common];
1702 bool found_match = false;
1703 for (uint8_t remaining_bits = 0; remaining_bits <= (~mask & 0xff); remaining_bits++) {
1704 if (remaining_bits_match(num_common, bytes_diff, state, (state & mask) | remaining_bits, odd_even)) {
1705 #ifdef DEBUG_KEY_ELIMINATION
1706 if (bitflips_match(byte2, (state & mask) | remaining_bits, odd_even, true)) {
1707 #else
1708 if (bitflips_match(byte2, (state & mask) | remaining_bits, odd_even)) {
1709 #endif
1710 found_match = true;
1711 break;
1712 }
1713 }
1714 }
1715 if (!found_match) {
1716 #ifdef DEBUG_KEY_ELIMINATION
1717 if (known_target_key != -1 && state == test_state[odd_even]) {
1718 printf("all_bitflips_match() 1st Byte: %s test state (0x%06x): Eliminated. Bytes = %02x, %02x, Common Bits = %d\n",
1719 odd_even==ODD_STATE?"odd":"even",
1720 test_state[odd_even],
1721 byte, byte2, num_common);
1722 if (failstr[0] == '\0') {
1723 sprintf(failstr, "Other 1st Byte %s, all_bitflips_match(), no match", odd_even?"odd":"even");
1724 }
1725 }
1726 #endif
1727 return false;
1728 }
1729 }
1730
1731 return true;
1732 }
1733
1734
1735 static void bitarray_to_list(uint8_t byte, uint32_t *bitarray, uint32_t *state_list, uint32_t *len, odd_even_t odd_even)
1736 {
1737 uint32_t *p = state_list;
1738 for (uint32_t state = next_state(bitarray, -1L); state < (1<<24); state = next_state(bitarray, state)) {
1739 if (all_bitflips_match(byte, state, odd_even)) {
1740 *p++ = state;
1741 }
1742 }
1743 // add End Of List marker
1744 *p = 0xffffffff;
1745 *len = p - state_list;
1746 }
1747
1748
1749 static void add_cached_states(statelist_t *candidates, uint16_t part_sum_a0, uint16_t part_sum_a8, odd_even_t odd_even)
1750 {
1751 candidates->states[odd_even] = sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].sl;
1752 candidates->len[odd_even] = sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].len;
1753 return;
1754 }
1755
1756
1757 static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, uint8_t part_sum_a8, odd_even_t odd_even)
1758 {
1759 uint32_t worstcase_size = 1<<20;
1760 candidates->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
1761 if (candidates->states[odd_even] == NULL) {
1762 PrintAndLog("Out of memory error in add_matching_states() - statelist.\n");
1763 exit(4);
1764 }
1765 uint32_t *candidates_bitarray = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * (1<<19));
1766 if (candidates_bitarray == NULL) {
1767 PrintAndLog("Out of memory error in add_matching_states() - bitarray.\n");
1768 free(candidates->states[odd_even]);
1769 exit(4);
1770 }
1771
1772 uint32_t *bitarray_a0 = part_sum_a0_bitarrays[odd_even][part_sum_a0/2];
1773 uint32_t *bitarray_a8 = part_sum_a8_bitarrays[odd_even][part_sum_a8/2];
1774 uint32_t *bitarray_bitflips = nonces[best_first_bytes[0]].states_bitarray[odd_even];
1775
1776 // for (uint32_t i = 0; i < (1<<19); i++) {
1777 // candidates_bitarray[i] = bitarray_a0[i] & bitarray_a8[i] & bitarray_bitflips[i];
1778 // }
1779 bitarray_AND4(candidates_bitarray, bitarray_a0, bitarray_a8, bitarray_bitflips);
1780
1781 bitarray_to_list(best_first_bytes[0], candidates_bitarray, candidates->states[odd_even], &(candidates->len[odd_even]), odd_even);
1782 if (candidates->len[odd_even] == 0) {
1783 free(candidates->states[odd_even]);
1784 candidates->states[odd_even] = NULL;
1785 } else if (candidates->len[odd_even] + 1 < worstcase_size) {
1786 candidates->states[odd_even] = realloc(candidates->states[odd_even], sizeof(uint32_t) * (candidates->len[odd_even] + 1));
1787 }
1788 free_bitarray(candidates_bitarray);
1789
1790
1791 pthread_mutex_lock(&statelist_cache_mutex);
1792 sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].sl = candidates->states[odd_even];
1793 sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].len = candidates->len[odd_even];
1794 sl_cache[part_sum_a0/2][part_sum_a8/2][odd_even].cache_status = COMPLETED;
1795 pthread_mutex_unlock(&statelist_cache_mutex);
1796
1797 return;
1798 }
1799
1800
1801 static statelist_t *add_more_candidates(void)
1802 {
1803 statelist_t *new_candidates = candidates;
1804 if (candidates == NULL) {
1805 candidates = (statelist_t *)malloc(sizeof(statelist_t));
1806 new_candidates = candidates;
1807 } else {
1808 new_candidates = candidates;
1809 while (new_candidates->next != NULL) {
1810 new_candidates = new_candidates->next;
1811 }
1812 new_candidates = new_candidates->next = (statelist_t *)malloc(sizeof(statelist_t));
1813 }
1814 new_candidates->next = NULL;
1815 new_candidates->len[ODD_STATE] = 0;
1816 new_candidates->len[EVEN_STATE] = 0;
1817 new_candidates->states[ODD_STATE] = NULL;
1818 new_candidates->states[EVEN_STATE] = NULL;
1819 return new_candidates;
1820 }
1821
1822
1823 static void add_bitflip_candidates(uint8_t byte)
1824 {
1825 statelist_t *candidates = add_more_candidates();
1826
1827 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
1828 uint32_t worstcase_size = nonces[byte].num_states_bitarray[odd_even] + 1;
1829 candidates->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
1830 if (candidates->states[odd_even] == NULL) {
1831 PrintAndLog("Out of memory error in add_bitflip_candidates().\n");
1832 exit(4);
1833 }
1834
1835 bitarray_to_list(byte, nonces[byte].states_bitarray[odd_even], candidates->states[odd_even], &(candidates->len[odd_even]), odd_even);
1836
1837 if (candidates->len[odd_even] + 1 < worstcase_size) {
1838 candidates->states[odd_even] = realloc(candidates->states[odd_even], sizeof(uint32_t) * (candidates->len[odd_even] + 1));
1839 }
1840 }
1841 return;
1842 }
1843
1844
1845 static bool TestIfKeyExists(uint64_t key)
1846 {
1847 struct Crypto1State *pcs;
1848 pcs = crypto1_create(key);
1849 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
1850
1851 uint32_t state_odd = pcs->odd & 0x00ffffff;
1852 uint32_t state_even = pcs->even & 0x00ffffff;
1853
1854 uint64_t count = 0;
1855 for (statelist_t *p = candidates; p != NULL; p = p->next) {
1856 bool found_odd = false;
1857 bool found_even = false;
1858 uint32_t *p_odd = p->states[ODD_STATE];
1859 uint32_t *p_even = p->states[EVEN_STATE];
1860 if (p_odd != NULL && p_even != NULL) {
1861 while (*p_odd != 0xffffffff) {
1862 if ((*p_odd & 0x00ffffff) == state_odd) {
1863 found_odd = true;
1864 break;
1865 }
1866 p_odd++;
1867 }
1868 while (*p_even != 0xffffffff) {
1869 if ((*p_even & 0x00ffffff) == state_even) {
1870 found_even = true;
1871 }
1872 p_even++;
1873 }
1874 count += (uint64_t)(p_odd - p->states[ODD_STATE]) * (uint64_t)(p_even - p->states[EVEN_STATE]);
1875 }
1876 if (found_odd && found_even) {
1877 num_keys_tested += count;
1878 hardnested_print_progress(num_acquired_nonces, "(Test: Key found)", 0.0, 0);
1879 crypto1_destroy(pcs);
1880 return true;
1881 }
1882 }
1883
1884 num_keys_tested += count;
1885 hardnested_print_progress(num_acquired_nonces, "(Test: Key NOT found)", 0.0, 0);
1886
1887 crypto1_destroy(pcs);
1888 return false;
1889 }
1890
1891
1892 static work_status_t book_of_work[NUM_PART_SUMS][NUM_PART_SUMS][NUM_PART_SUMS][NUM_PART_SUMS];
1893
1894
1895 static void init_book_of_work(void)
1896 {
1897 for (uint8_t p = 0; p < NUM_PART_SUMS; p++) {
1898 for (uint8_t q = 0; q < NUM_PART_SUMS; q++) {
1899 for (uint8_t r = 0; r < NUM_PART_SUMS; r++) {
1900 for (uint8_t s = 0; s < NUM_PART_SUMS; s++) {
1901 book_of_work[p][q][r][s] = TO_BE_DONE;
1902 }
1903 }
1904 }
1905 }
1906 }
1907
1908
1909 static void *generate_candidates_worker_thread(void *args)
1910 {
1911 uint16_t *sum_args = (uint16_t *)args;
1912 uint16_t sum_a0 = sums[sum_args[0]];
1913 uint16_t sum_a8 = sums[sum_args[1]];
1914 // uint16_t my_thread_number = sums[2];
1915
1916 bool there_might_be_more_work = true;
1917 do {
1918 there_might_be_more_work = false;
1919 for (uint8_t p = 0; p < NUM_PART_SUMS; p++) {
1920 for (uint8_t q = 0; q < NUM_PART_SUMS; q++) {
1921 if (2*p*(16-2*q) + (16-2*p)*2*q == sum_a0) {
1922 // printf("Reducing Partial Statelists (p,q) = (%d,%d) with lengths %d, %d\n",
1923 // p, q, partial_statelist[p].len[ODD_STATE], partial_statelist[q].len[EVEN_STATE]);
1924 for (uint8_t r = 0; r < NUM_PART_SUMS; r++) {
1925 for (uint8_t s = 0; s < NUM_PART_SUMS; s++) {
1926 if (2*r*(16-2*s) + (16-2*r)*2*s == sum_a8) {
1927 pthread_mutex_lock(&book_of_work_mutex);
1928 if (book_of_work[p][q][r][s] != TO_BE_DONE) { // this has been done or is currently been done by another thread. Look for some other work.
1929 pthread_mutex_unlock(&book_of_work_mutex);
1930 continue;
1931 }
1932
1933 pthread_mutex_lock(&statelist_cache_mutex);
1934 if (sl_cache[p][r][ODD_STATE].cache_status == WORK_IN_PROGRESS
1935 || sl_cache[q][s][EVEN_STATE].cache_status == WORK_IN_PROGRESS) { // defer until not blocked by another thread.
1936 pthread_mutex_unlock(&statelist_cache_mutex);
1937 pthread_mutex_unlock(&book_of_work_mutex);
1938 there_might_be_more_work = true;
1939 continue;
1940 }
1941
1942 // we finally can do some work.
1943 book_of_work[p][q][r][s] = WORK_IN_PROGRESS;
1944 statelist_t *current_candidates = add_more_candidates();
1945
1946 // Check for cached results and add them first
1947 bool odd_completed = false;
1948 if (sl_cache[p][r][ODD_STATE].cache_status == COMPLETED) {
1949 add_cached_states(current_candidates, 2*p, 2*r, ODD_STATE);
1950 odd_completed = true;
1951 }
1952 bool even_completed = false;
1953 if (sl_cache[q][s][EVEN_STATE].cache_status == COMPLETED) {
1954 add_cached_states(current_candidates, 2*q, 2*s, EVEN_STATE);
1955 even_completed = true;
1956 }
1957
1958 bool work_required = true;
1959
1960 // if there had been two cached results, there is no more work to do
1961 if (even_completed && odd_completed) {
1962 work_required = false;
1963 }
1964
1965 // if there had been one cached empty result, there is no need to calculate the other part:
1966 if (work_required) {
1967 if (even_completed && !current_candidates->len[EVEN_STATE]) {
1968 current_candidates->len[ODD_STATE] = 0;
1969 current_candidates->states[ODD_STATE] = NULL;
1970 work_required = false;
1971 }
1972 if (odd_completed && !current_candidates->len[ODD_STATE]) {
1973 current_candidates->len[EVEN_STATE] = 0;
1974 current_candidates->states[EVEN_STATE] = NULL;
1975 work_required = false;
1976 }
1977 }
1978
1979 if (!work_required) {
1980 pthread_mutex_unlock(&statelist_cache_mutex);
1981 pthread_mutex_unlock(&book_of_work_mutex);
1982 } else {
1983 // we really need to calculate something
1984 if (even_completed) { // we had one cache hit with non-zero even states
1985 // printf("Thread #%u: start working on odd states p=%2d, r=%2d...\n", my_thread_number, p, r);
1986 sl_cache[p][r][ODD_STATE].cache_status = WORK_IN_PROGRESS;
1987 pthread_mutex_unlock(&statelist_cache_mutex);
1988 pthread_mutex_unlock(&book_of_work_mutex);
1989 add_matching_states(current_candidates, 2*p, 2*r, ODD_STATE);
1990 work_required = false;
1991 } else if (odd_completed) { // we had one cache hit with non-zero odd_states
1992 // printf("Thread #%u: start working on even states q=%2d, s=%2d...\n", my_thread_number, q, s);
1993 sl_cache[q][s][EVEN_STATE].cache_status = WORK_IN_PROGRESS;
1994 pthread_mutex_unlock(&statelist_cache_mutex);
1995 pthread_mutex_unlock(&book_of_work_mutex);
1996 add_matching_states(current_candidates, 2*q, 2*s, EVEN_STATE);
1997 work_required = false;
1998 }
1999 }
2000
2001 if (work_required) { // we had no cached result. Need to calculate both odd and even
2002 sl_cache[p][r][ODD_STATE].cache_status = WORK_IN_PROGRESS;
2003 sl_cache[q][s][EVEN_STATE].cache_status = WORK_IN_PROGRESS;
2004 pthread_mutex_unlock(&statelist_cache_mutex);
2005 pthread_mutex_unlock(&book_of_work_mutex);
2006
2007 add_matching_states(current_candidates, 2*p, 2*r, ODD_STATE);
2008 if(current_candidates->len[ODD_STATE]) {
2009 // printf("Thread #%u: start working on even states q=%2d, s=%2d...\n", my_thread_number, q, s);
2010 add_matching_states(current_candidates, 2*q, 2*s, EVEN_STATE);
2011 } else { // no need to calculate even states yet
2012 pthread_mutex_lock(&statelist_cache_mutex);
2013 sl_cache[q][s][EVEN_STATE].cache_status = TO_BE_DONE;
2014 pthread_mutex_unlock(&statelist_cache_mutex);
2015 current_candidates->len[EVEN_STATE] = 0;
2016 current_candidates->states[EVEN_STATE] = NULL;
2017 }
2018 }
2019
2020 // update book of work
2021 pthread_mutex_lock(&book_of_work_mutex);
2022 book_of_work[p][q][r][s] = COMPLETED;
2023 pthread_mutex_unlock(&book_of_work_mutex);
2024
2025 // if ((uint64_t)current_candidates->len[ODD_STATE] * current_candidates->len[EVEN_STATE]) {
2026 // printf("Candidates for p=%2u, q=%2u, r=%2u, s=%2u: %" PRIu32 " * %" PRIu32 " = %" PRIu64 " (2^%0.1f)\n",
2027 // 2*p, 2*q, 2*r, 2*s, current_candidates->len[ODD_STATE], current_candidates->len[EVEN_STATE],
2028 // (uint64_t)current_candidates->len[ODD_STATE] * current_candidates->len[EVEN_STATE],
2029 // log((uint64_t)current_candidates->len[ODD_STATE] * current_candidates->len[EVEN_STATE])/log(2));
2030 // uint32_t estimated_odd = estimated_num_states_part_sum(best_first_bytes[0], p, r, ODD_STATE);
2031 // uint32_t estimated_even= estimated_num_states_part_sum(best_first_bytes[0], q, s, EVEN_STATE);
2032 // uint64_t estimated_total = (uint64_t)estimated_odd * estimated_even;
2033 // printf("Estimated: %" PRIu32 " * %" PRIu32 " = %" PRIu64 " (2^%0.1f)\n", estimated_odd, estimated_even, estimated_total, log(estimated_total) / log(2));
2034 // if (estimated_odd < current_candidates->len[ODD_STATE] || estimated_even < current_candidates->len[EVEN_STATE]) {
2035 // printf("############################################################################ERROR! ESTIMATED < REAL !!!\n");
2036 // //exit(2);
2037 // }
2038 // }
2039 }
2040 }
2041 }
2042 }
2043 }
2044 }
2045 } while (there_might_be_more_work);
2046
2047 return NULL;
2048 }
2049
2050
2051 static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx)
2052 {
2053 // printf("Generating crypto1 state candidates... \n");
2054
2055 // estimate maximum candidate states
2056 // maximum_states = 0;
2057 // for (uint16_t sum_odd = 0; sum_odd <= 16; sum_odd += 2) {
2058 // for (uint16_t sum_even = 0; sum_even <= 16; sum_even += 2) {
2059 // if (sum_odd*(16-sum_even) + (16-sum_odd)*sum_even == sum_a0) {
2060 // maximum_states += (uint64_t)count_states(part_sum_a0_bitarrays[EVEN_STATE][sum_even/2])
2061 // * count_states(part_sum_a0_bitarrays[ODD_STATE][sum_odd/2]);
2062 // }
2063 // }
2064 // }
2065 // printf("Number of possible keys with Sum(a0) = %d: %" PRIu64 " (2^%1.1f)\n", sum_a0, maximum_states, log(maximum_states)/log(2.0));
2066
2067 init_statelist_cache();
2068 init_book_of_work();
2069
2070 // create mutexes for accessing the statelist cache and our "book of work"
2071 pthread_mutex_init(&statelist_cache_mutex, NULL);
2072 pthread_mutex_init(&book_of_work_mutex, NULL);
2073
2074 // create and run worker threads
2075 pthread_t thread_id[NUM_REDUCTION_WORKING_THREADS];
2076
2077 uint16_t sums[NUM_REDUCTION_WORKING_THREADS][3];
2078 for (uint16_t i = 0; i < NUM_REDUCTION_WORKING_THREADS; i++) {
2079 sums[i][0] = sum_a0_idx;
2080 sums[i][1] = sum_a8_idx;
2081 sums[i][2] = i+1;
2082 pthread_create(thread_id + i, NULL, generate_candidates_worker_thread, sums[i]);
2083 }
2084
2085 // wait for threads to terminate:
2086 for (uint16_t i = 0; i < NUM_REDUCTION_WORKING_THREADS; i++) {
2087 pthread_join(thread_id[i], NULL);
2088 }
2089
2090 // clean up mutex
2091 pthread_mutex_destroy(&statelist_cache_mutex);
2092
2093 maximum_states = 0;
2094 for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) {
2095 maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE];
2096 }
2097
2098 for (uint8_t i = 0; i < NUM_SUMS; i++) {
2099 if (nonces[best_first_bytes[0]].sum_a8_guess[i].sum_a8_idx == sum_a8_idx) {
2100 nonces[best_first_bytes[0]].sum_a8_guess[i].num_states = maximum_states;
2101 break;
2102 }
2103 }
2104 update_expected_brute_force(best_first_bytes[0]);
2105
2106 hardnested_print_progress(num_acquired_nonces, "Apply Sum(a8) and all bytes bitflip properties", nonces[best_first_bytes[0]].expected_num_brute_force, 0);
2107 }
2108
2109
2110 static void free_candidates_memory(statelist_t *sl)
2111 {
2112 if (sl == NULL) {
2113 return;
2114 } else {
2115 free_candidates_memory(sl->next);
2116 free(sl);
2117 }
2118 }
2119
2120
2121 static void pre_XOR_nonces(void)
2122 {
2123 // prepare acquired nonces for faster brute forcing.
2124
2125 // XOR the cryptoUID and its parity
2126 for (uint16_t i = 0; i < 256; i++) {
2127 noncelistentry_t *test_nonce = nonces[i].first;
2128 while (test_nonce != NULL) {
2129 test_nonce->nonce_enc ^= cuid;
2130 test_nonce->par_enc ^= oddparity8(cuid >> 0 & 0xff) << 0;
2131 test_nonce->par_enc ^= oddparity8(cuid >> 8 & 0xff) << 1;
2132 test_nonce->par_enc ^= oddparity8(cuid >> 16 & 0xff) << 2;
2133 test_nonce->par_enc ^= oddparity8(cuid >> 24 & 0xff) << 3;
2134 test_nonce = test_nonce->next;
2135 }
2136 }
2137 }
2138
2139
2140 static bool brute_force(void)
2141 {
2142 if (known_target_key != -1) {
2143 TestIfKeyExists(known_target_key);
2144 }
2145 return brute_force_bs(NULL, candidates, cuid, num_acquired_nonces, maximum_states, nonces, best_first_bytes);
2146 }
2147
2148
2149 static uint16_t SumProperty(struct Crypto1State *s)
2150 {
2151 uint16_t sum_odd = PartialSumProperty(s->odd, ODD_STATE);
2152 uint16_t sum_even = PartialSumProperty(s->even, EVEN_STATE);
2153 return (sum_odd*(16-sum_even) + (16-sum_odd)*sum_even);
2154 }
2155
2156
2157 static void Tests()
2158 {
2159
2160 /* #define NUM_STATISTICS 100000
2161 uint32_t statistics_odd[17];
2162 uint64_t statistics[257];
2163 uint32_t statistics_even[17];
2164 struct Crypto1State cs;
2165 uint64_t time1 = msclock();
2166
2167 for (uint16_t i = 0; i < 257; i++) {
2168 statistics[i] = 0;
2169 }
2170 for (uint16_t i = 0; i < 17; i++) {
2171 statistics_odd[i] = 0;
2172 statistics_even[i] = 0;
2173 }
2174
2175 for (uint64_t i = 0; i < NUM_STATISTICS; i++) {
2176 cs.odd = (rand() & 0xfff) << 12 | (rand() & 0xfff);
2177 cs.even = (rand() & 0xfff) << 12 | (rand() & 0xfff);
2178 uint16_t sum_property = SumProperty(&cs);
2179 statistics[sum_property] += 1;
2180 sum_property = PartialSumProperty(cs.even, EVEN_STATE);
2181 statistics_even[sum_property]++;
2182 sum_property = PartialSumProperty(cs.odd, ODD_STATE);
2183 statistics_odd[sum_property]++;
2184 if (i%(NUM_STATISTICS/100) == 0) printf(".");
2185 }
2186
2187 printf("\nTests: Calculated %d Sum properties in %0.3f seconds (%0.0f calcs/second)\n", NUM_STATISTICS, ((float)msclock() - time1)/1000.0, NUM_STATISTICS/((float)msclock() - time1)*1000.0);
2188 for (uint16_t i = 0; i < 257; i++) {
2189 if (statistics[i] != 0) {
2190 printf("probability[%3d] = %0.5f\n", i, (float)statistics[i]/NUM_STATISTICS);
2191 }
2192 }
2193 for (uint16_t i = 0; i <= 16; i++) {
2194 if (statistics_odd[i] != 0) {
2195 printf("probability odd [%2d] = %0.5f\n", i, (float)statistics_odd[i]/NUM_STATISTICS);
2196 }
2197 }
2198 for (uint16_t i = 0; i <= 16; i++) {
2199 if (statistics_odd[i] != 0) {
2200 printf("probability even [%2d] = %0.5f\n", i, (float)statistics_even[i]/NUM_STATISTICS);
2201 }
2202 }
2203 */
2204
2205 /* #define NUM_STATISTICS 100000000LL
2206 uint64_t statistics_a0[257];
2207 uint64_t statistics_a8[257][257];
2208 struct Crypto1State cs;
2209 uint64_t time1 = msclock();
2210
2211 for (uint16_t i = 0; i < 257; i++) {
2212 statistics_a0[i] = 0;
2213 for (uint16_t j = 0; j < 257; j++) {
2214 statistics_a8[i][j] = 0;
2215 }
2216 }
2217
2218 for (uint64_t i = 0; i < NUM_STATISTICS; i++) {
2219 cs.odd = (rand() & 0xfff) << 12 | (rand() & 0xfff);
2220 cs.even = (rand() & 0xfff) << 12 | (rand() & 0xfff);
2221 uint16_t sum_property_a0 = SumProperty(&cs);
2222 statistics_a0[sum_property_a0]++;
2223 uint8_t first_byte = rand() & 0xff;
2224 crypto1_byte(&cs, first_byte, true);
2225 uint16_t sum_property_a8 = SumProperty(&cs);
2226 statistics_a8[sum_property_a0][sum_property_a8] += 1;
2227 if (i%(NUM_STATISTICS/100) == 0) printf(".");
2228 }
2229
2230 printf("\nTests: Probability Distribution of a8 depending on a0:\n");
2231 printf("\n ");
2232 for (uint16_t i = 0; i < NUM_SUMS; i++) {
2233 printf("%7d ", sums[i]);
2234 }
2235 printf("\n-------------------------------------------------------------------------------------------------------------------------------------------\n");
2236 printf("a0: ");
2237 for (uint16_t i = 0; i < NUM_SUMS; i++) {
2238 printf("%7.5f ", (float)statistics_a0[sums[i]] / NUM_STATISTICS);
2239 }
2240 printf("\n");
2241 for (uint16_t i = 0; i < NUM_SUMS; i++) {
2242 printf("%3d ", sums[i]);
2243 for (uint16_t j = 0; j < NUM_SUMS; j++) {
2244 printf("%7.5f ", (float)statistics_a8[sums[i]][sums[j]] / statistics_a0[sums[i]]);
2245 }
2246 printf("\n");
2247 }
2248 printf("\nTests: Calculated %"lld" Sum properties in %0.3f seconds (%0.0f calcs/second)\n", NUM_STATISTICS, ((float)msclock() - time1)/1000.0, NUM_STATISTICS/((float)msclock() - time1)*1000.0);
2249 */
2250
2251 /* #define NUM_STATISTICS 100000LL
2252 uint64_t statistics_a8[257];
2253 struct Crypto1State cs;
2254 uint64_t time1 = msclock();
2255
2256 printf("\nTests: Probability Distribution of a8 depending on first byte:\n");
2257 printf("\n ");
2258 for (uint16_t i = 0; i < NUM_SUMS; i++) {
2259 printf("%7d ", sums[i]);
2260 }
2261 printf("\n-------------------------------------------------------------------------------------------------------------------------------------------\n");
2262 for (uint16_t first_byte = 0; first_byte < 256; first_byte++) {
2263 for (uint16_t i = 0; i < 257; i++) {
2264 statistics_a8[i] = 0;
2265 }
2266 for (uint64_t i = 0; i < NUM_STATISTICS; i++) {
2267 cs.odd = (rand() & 0xfff) << 12 | (rand() & 0xfff);
2268 cs.even = (rand() & 0xfff) << 12 | (rand() & 0xfff);
2269 crypto1_byte(&cs, first_byte, true);
2270 uint16_t sum_property_a8 = SumProperty(&cs);
2271 statistics_a8[sum_property_a8] += 1;
2272 }
2273 printf("%03x ", first_byte);
2274 for (uint16_t j = 0; j < NUM_SUMS; j++) {
2275 printf("%7.5f ", (float)statistics_a8[sums[j]] / NUM_STATISTICS);
2276 }
2277 printf("\n");
2278 }
2279 printf("\nTests: Calculated %"lld" Sum properties in %0.3f seconds (%0.0f calcs/second)\n", NUM_STATISTICS, ((float)msclock() - time1)/1000.0, NUM_STATISTICS/((float)msclock() - time1)*1000.0);
2280 */
2281
2282 /* printf("Tests: Sum Probabilities based on Partial Sums\n");
2283 for (uint16_t i = 0; i < 257; i++) {
2284 statistics[i] = 0;
2285 }
2286 uint64_t num_states = 0;
2287 for (uint16_t oddsum = 0; oddsum <= 16; oddsum += 2) {
2288 for (uint16_t evensum = 0; evensum <= 16; evensum += 2) {
2289 uint16_t sum = oddsum*(16-evensum) + (16-oddsum)*evensum;
2290 statistics[sum] += (uint64_t)partial_statelist[oddsum].len[ODD_STATE] * partial_statelist[evensum].len[EVEN_STATE] * (1<<8);
2291 num_states += (uint64_t)partial_statelist[oddsum].len[ODD_STATE] * partial_statelist[evensum].len[EVEN_STATE] * (1<<8);
2292 }
2293 }
2294 printf("num_states = %"lld", expected %"lld"\n", num_states, (1LL<<48));
2295 for (uint16_t i = 0; i < 257; i++) {
2296 if (statistics[i] != 0) {
2297 printf("probability[%3d] = %0.5f\n", i, (float)statistics[i]/num_states);
2298 }
2299 }
2300 */
2301
2302 /* struct Crypto1State *pcs;
2303 pcs = crypto1_create(0xffffffffffff);
2304 printf("\nTests: for key = 0xffffffffffff:\nSum(a0) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
2305 SumProperty(pcs), pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
2306 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
2307 printf("After adding best first byte 0x%02x:\nSum(a8) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
2308 best_first_bytes[0],
2309 SumProperty(pcs),
2310 pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
2311 //test_state_odd = pcs->odd & 0x00ffffff;
2312 //test_state_even = pcs->even & 0x00ffffff;
2313 crypto1_destroy(pcs);
2314 pcs = crypto1_create(0xa0a1a2a3a4a5);
2315 printf("Tests: for key = 0xa0a1a2a3a4a5:\nSum(a0) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
2316 SumProperty(pcs), pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
2317 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
2318 printf("After adding best first byte 0x%02x:\nSum(a8) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
2319 best_first_bytes[0],
2320 SumProperty(pcs),
2321 pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
2322 //test_state_odd = pcs->odd & 0x00ffffff;
2323 //test_state_even = pcs->even & 0x00ffffff;
2324 crypto1_destroy(pcs);
2325 pcs = crypto1_create(0xa6b9aa97b955);
2326 printf("Tests: for key = 0xa6b9aa97b955:\nSum(a0) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
2327 SumProperty(pcs), pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
2328 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
2329 printf("After adding best first byte 0x%02x:\nSum(a8) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
2330 best_first_bytes[0],
2331 SumProperty(pcs),
2332 pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
2333 test_state_odd = pcs->odd & 0x00ffffff;
2334 test_state_even = pcs->even & 0x00ffffff;
2335 crypto1_destroy(pcs);
2336 */
2337
2338 // printf("\nTests: Sorted First Bytes:\n");
2339 // for (uint16_t i = 0; i < 20; i++) {
2340 // uint8_t best_byte = best_first_bytes[i];
2341 // //printf("#%03d Byte: %02x, n = %3d, k = %3d, Sum(a8): %3d, Confidence: %5.1f%%\n",
2342 // printf("#%03d Byte: %02x, n = %3d, k = %3d, Sum(a8) = ", i, best_byte, nonces[best_byte].num, nonces[best_byte].Sum);
2343 // for (uint16_t j = 0; j < 3; j++) {
2344 // printf("%3d @ %4.1f%%, ", sums[nonces[best_byte].sum_a8_guess[j].sum_a8_idx], nonces[best_byte].sum_a8_guess[j].prob * 100.0);
2345 // }
2346 // printf(" %12" PRIu64 ", %12" PRIu64 ", %12" PRIu64 ", exp_brute: %12.0f\n",
2347 // nonces[best_byte].sum_a8_guess[0].num_states,
2348 // nonces[best_byte].sum_a8_guess[1].num_states,
2349 // nonces[best_byte].sum_a8_guess[2].num_states,
2350 // nonces[best_byte].expected_num_brute_force);
2351 // }
2352
2353 // printf("\nTests: Actual BitFlipProperties of best byte:\n");
2354 // printf("[%02x]:", best_first_bytes[0]);
2355 // for (uint16_t bitflip_idx = 0; bitflip_idx < num_all_effective_bitflips; bitflip_idx++) {
2356 // uint16_t bitflip_prop = all_effective_bitflip[bitflip_idx];
2357 // if (nonces[best_first_bytes[0]].BitFlips[bitflip_prop]) {
2358 // printf(" %03" PRIx16 , bitflip_prop);
2359 // }
2360 // }
2361 // printf("\n");
2362
2363 // printf("\nTests2: Actual BitFlipProperties of first_byte_smallest_bitarray:\n");
2364 // printf("[%02x]:", best_first_byte_smallest_bitarray);
2365 // for (uint16_t bitflip_idx = 0; bitflip_idx < num_all_effective_bitflips; bitflip_idx++) {
2366 // uint16_t bitflip_prop = all_effective_bitflip[bitflip_idx];
2367 // if (nonces[best_first_byte_smallest_bitarray].BitFlips[bitflip_prop]) {
2368 // printf(" %03" PRIx16 , bitflip_prop);
2369 // }
2370 // }
2371 // printf("\n");
2372
2373 if (known_target_key != -1) {
2374 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
2375 uint32_t *bitset = nonces[best_first_bytes[0]].states_bitarray[odd_even];
2376 if (!test_bit24(bitset, test_state[odd_even])) {
2377 printf("\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n",
2378 odd_even==EVEN_STATE?"even":"odd ",
2379 best_first_bytes[0]);
2380 }
2381 }
2382 }
2383
2384 if (known_target_key != -1) {
2385 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
2386 uint32_t *bitset = all_bitflips_bitarray[odd_even];
2387 if (!test_bit24(bitset, test_state[odd_even])) {
2388 printf("\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n",
2389 odd_even==EVEN_STATE?"even":"odd ");
2390 }
2391 }
2392 }
2393
2394 // if (known_target_key != -1) {
2395 // int16_t p = -1, q = -1, r = -1, s = -1;
2396
2397 // printf("\nTests: known target key is member of these partial sum_a0 bitsets:\n");
2398 // for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
2399 // printf("%s", odd_even==EVEN_STATE?"even:":"odd: ");
2400 // for (uint16_t i = 0; i < NUM_PART_SUMS; i++) {
2401 // uint32_t *bitset = part_sum_a0_bitarrays[odd_even][i];
2402 // if (test_bit24(bitset, test_state[odd_even])) {
2403 // printf("%d ", i);
2404 // if (odd_even == ODD_STATE) {
2405 // p = 2*i;
2406 // } else {
2407 // q = 2*i;
2408 // }
2409 // }
2410 // }
2411 // printf("\n");
2412 // }
2413
2414 // printf("\nTests: known target key is member of these partial sum_a8 bitsets:\n");
2415 // for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
2416 // printf("%s", odd_even==EVEN_STATE?"even:":"odd: ");
2417 // for (uint16_t i = 0; i < NUM_PART_SUMS; i++) {
2418 // uint32_t *bitset = part_sum_a8_bitarrays[odd_even][i];
2419 // if (test_bit24(bitset, test_state[odd_even])) {
2420 // printf("%d ", i);
2421 // if (odd_even == ODD_STATE) {
2422 // r = 2*i;
2423 // } else {
2424 // s = 2*i;
2425 // }
2426 // }
2427 // }
2428 // printf("\n");
2429 // }
2430
2431 // printf("Sum(a0) = p*(16-q) + (16-p)*q = %d*(16-%d) + (16-%d)*%d = %d\n", p, q, p, q, p*(16-q)+(16-p)*q);
2432 // printf("Sum(a8) = r*(16-s) + (16-r)*s = %d*(16-%d) + (16-%d)*%d = %d\n", r, s, r, s, r*(16-s)+(16-r)*s);
2433 // }
2434
2435 /* printf("\nTests: parity performance\n");
2436 uint64_t time1p = msclock();
2437 uint32_t par_sum = 0;
2438 for (uint32_t i = 0; i < 100000000; i++) {
2439 par_sum += parity(i);
2440 }
2441 printf("parsum oldparity = %d, time = %1.5fsec\n", par_sum, (float)(msclock() - time1p)/1000.0);
2442
2443 time1p = msclock();
2444 par_sum = 0;
2445 for (uint32_t i = 0; i < 100000000; i++) {
2446 par_sum += evenparity32(i);
2447 }
2448 printf("parsum newparity = %d, time = %1.5fsec\n", par_sum, (float)(msclock() - time1p)/1000.0);
2449 */
2450
2451 }
2452
2453
2454 static void Tests2(void)
2455 {
2456 if (known_target_key != -1) {
2457 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
2458 uint32_t *bitset = nonces[best_first_byte_smallest_bitarray].states_bitarray[odd_even];
2459 if (!test_bit24(bitset, test_state[odd_even])) {
2460 printf("\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n",
2461 odd_even==EVEN_STATE?"even":"odd ",
2462 best_first_byte_smallest_bitarray);
2463 }
2464 }
2465 }
2466
2467 if (known_target_key != -1) {
2468 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
2469 uint32_t *bitset = all_bitflips_bitarray[odd_even];
2470 if (!test_bit24(bitset, test_state[odd_even])) {
2471 printf("\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n",
2472 odd_even==EVEN_STATE?"even":"odd ");
2473 }
2474 }
2475 }
2476
2477 }
2478
2479
2480 static uint16_t real_sum_a8 = 0;
2481
2482 static void set_test_state(uint8_t byte)
2483 {
2484 struct Crypto1State *pcs;
2485 pcs = crypto1_create(known_target_key);
2486 crypto1_byte(pcs, (cuid >> 24) ^ byte, true);
2487 test_state[ODD_STATE] = pcs->odd & 0x00ffffff;
2488 test_state[EVEN_STATE] = pcs->even & 0x00ffffff;
2489 real_sum_a8 = SumProperty(pcs);
2490 crypto1_destroy(pcs);
2491 }
2492
2493
2494 int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests)
2495 {
2496 char progress_text[80];
2497
2498 char instr_set[12] = {0};
2499 get_SIMD_instruction_set(instr_set);
2500 PrintAndLog("Using %s SIMD core.", instr_set);
2501
2502 srand((unsigned) time(NULL));
2503 brute_force_per_second = brute_force_benchmark();
2504 write_stats = false;
2505
2506 if (tests) {
2507 // set the correct locale for the stats printing
2508 write_stats = true;
2509 setlocale(LC_NUMERIC, "");
2510 if ((fstats = fopen("hardnested_stats.txt","a")) == NULL) {
2511 PrintAndLog("Could not create/open file hardnested_stats.txt");
2512 return 3;
2513 }
2514 for (uint32_t i = 0; i < tests; i++) {
2515 start_time = msclock();
2516 print_progress_header();
2517 sprintf(progress_text, "Brute force benchmark: %1.0f million (2^%1.1f) keys/s", brute_force_per_second/1000000, log(brute_force_per_second)/log(2.0));
2518 hardnested_print_progress(0, progress_text, (float)(1LL<<47), 0);
2519 sprintf(progress_text, "Starting Test #%" PRIu32 " ...", i+1);
2520 hardnested_print_progress(0, progress_text, (float)(1LL<<47), 0);
2521 if (trgkey != NULL) {
2522 known_target_key = bytes_to_num(trgkey, 6);
2523 } else {
2524 known_target_key = -1;
2525 }
2526
2527 init_bitflip_bitarrays();
2528 init_part_sum_bitarrays();
2529 init_sum_bitarrays();
2530 init_allbitflips_array();
2531 init_nonce_memory();
2532 update_reduction_rate(0.0, true);
2533
2534 simulate_acquire_nonces();
2535
2536 set_test_state(best_first_bytes[0]);
2537
2538 Tests();
2539 free_bitflip_bitarrays();
2540
2541 fprintf(fstats, "%" PRIu16 ";%1.1f;", sums[first_byte_Sum], log(p_K0[first_byte_Sum])/log(2.0));
2542 fprintf(fstats, "%" PRIu16 ";%1.1f;", sums[nonces[best_first_bytes[0]].sum_a8_guess[0].sum_a8_idx], log(p_K[nonces[best_first_bytes[0]].sum_a8_guess[0].sum_a8_idx])/log(2.0));
2543 fprintf(fstats, "%" PRIu16 ";", real_sum_a8);
2544
2545 #ifdef DEBUG_KEY_ELIMINATION
2546 failstr[0] = '\0';
2547 #endif
2548 bool key_found = false;
2549 num_keys_tested = 0;
2550 uint32_t num_odd = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[ODD_STATE];
2551 uint32_t num_even = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[EVEN_STATE];
2552 float expected_brute_force1 = (float)num_odd * num_even / 2.0;
2553 float expected_brute_force2 = nonces[best_first_bytes[0]].expected_num_brute_force;
2554 fprintf(fstats, "%1.1f;%1.1f;", log(expected_brute_force1)/log(2.0), log(expected_brute_force2)/log(2.0));
2555 if (expected_brute_force1 < expected_brute_force2) {
2556 hardnested_print_progress(num_acquired_nonces, "(Ignoring Sum(a8) properties)", expected_brute_force1, 0);
2557 set_test_state(best_first_byte_smallest_bitarray);
2558 add_bitflip_candidates(best_first_byte_smallest_bitarray);
2559 Tests2();
2560 maximum_states = 0;
2561 for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) {
2562 maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE];
2563 }
2564 //printf("Number of remaining possible keys: %" PRIu64 " (2^%1.1f)\n", maximum_states, log(maximum_states)/log(2.0));
2565 // fprintf("fstats, "%" PRIu64 ";", maximum_states);
2566 best_first_bytes[0] = best_first_byte_smallest_bitarray;
2567 pre_XOR_nonces();
2568 prepare_bf_test_nonces(nonces, best_first_bytes[0]);
2569 hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force1, 0);
2570 key_found = brute_force();
2571 free(candidates->states[ODD_STATE]);
2572 free(candidates->states[EVEN_STATE]);
2573 free_candidates_memory(candidates);
2574 candidates = NULL;
2575 } else {
2576 pre_XOR_nonces();
2577 prepare_bf_test_nonces(nonces, best_first_bytes[0]);
2578 for (uint8_t j = 0; j < NUM_SUMS && !key_found; j++) {
2579 float expected_brute_force = nonces[best_first_bytes[0]].expected_num_brute_force;
2580 sprintf(progress_text, "(%d. guess: Sum(a8) = %" PRIu16 ")", j+1, sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx]);
2581 hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
2582 if (sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx] != real_sum_a8) {
2583 sprintf(progress_text, "(Estimated Sum(a8) is WRONG! Correct Sum(a8) = %" PRIu16 ")", real_sum_a8);
2584 hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
2585 }
2586 // printf("Estimated remaining states: %" PRIu64 " (2^%1.1f)\n", nonces[best_first_bytes[0]].sum_a8_guess[j].num_states, log(nonces[best_first_bytes[0]].sum_a8_guess[j].num_states)/log(2.0));
2587 generate_candidates(first_byte_Sum, nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx);
2588 // printf("Time for generating key candidates list: %1.0f sec (%1.1f sec CPU)\n", difftime(time(NULL), start_time), (float)(msclock() - start_clock)/1000.0);
2589 hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force, 0);
2590 key_found = brute_force();
2591 free_statelist_cache();
2592 free_candidates_memory(candidates);
2593 candidates = NULL;
2594 if (!key_found) {
2595 // update the statistics
2596 nonces[best_first_bytes[0]].sum_a8_guess[j].prob = 0;
2597 nonces[best_first_bytes[0]].sum_a8_guess[j].num_states = 0;
2598 // and calculate new expected number of brute forces
2599 update_expected_brute_force(best_first_bytes[0]);
2600 }
2601 }
2602 }
2603 #ifdef DEBUG_KEY_ELIMINATION
2604 fprintf(fstats, "%1.1f;%1.0f;%d;%s\n", log(num_keys_tested)/log(2.0), (float)num_keys_tested/brute_force_per_second, key_found, failstr);
2605 #else
2606 fprintf(fstats, "%1.0f;%d\n", log(num_keys_tested)/log(2.0), (float)num_keys_tested/brute_force_per_second, key_found);
2607 #endif
2608
2609 free_nonces_memory();
2610 free_bitarray(all_bitflips_bitarray[ODD_STATE]);
2611 free_bitarray(all_bitflips_bitarray[EVEN_STATE]);
2612 free_sum_bitarrays();
2613 free_part_sum_bitarrays();
2614 }
2615 fclose(fstats);
2616 } else {
2617 start_time = msclock();
2618 print_progress_header();
2619 sprintf(progress_text, "Brute force benchmark: %1.0f million (2^%1.1f) keys/s", brute_force_per_second/1000000, log(brute_force_per_second)/log(2.0));
2620 hardnested_print_progress(0, progress_text, (float)(1LL<<47), 0);
2621 init_bitflip_bitarrays();
2622 init_part_sum_bitarrays();
2623 init_sum_bitarrays();
2624 init_allbitflips_array();
2625 init_nonce_memory();
2626 update_reduction_rate(0.0, true);
2627
2628 if (nonce_file_read) { // use pre-acquired data from file nonces.bin
2629 if (read_nonce_file() != 0) {
2630 free_bitflip_bitarrays();
2631 free_nonces_memory();
2632 free_bitarray(all_bitflips_bitarray[ODD_STATE]);
2633 free_bitarray(all_bitflips_bitarray[EVEN_STATE]);
2634 free_sum_bitarrays();
2635 free_part_sum_bitarrays();
2636 return 3;
2637 }
2638 hardnested_stage = CHECK_1ST_BYTES | CHECK_2ND_BYTES;
2639 update_nonce_data(false);
2640 float brute_force;
2641 shrink_key_space(&brute_force);
2642 } else { // acquire nonces.
2643 uint16_t is_OK = acquire_nonces(blockNo, keyType, key, trgBlockNo, trgKeyType, nonce_file_write, slow);
2644 if (is_OK != 0) {
2645 free_bitflip_bitarrays();
2646 free_nonces_memory();
2647 free_bitarray(all_bitflips_bitarray[ODD_STATE]);
2648 free_bitarray(all_bitflips_bitarray[EVEN_STATE]);
2649 free_sum_bitarrays();
2650 free_part_sum_bitarrays();
2651 return is_OK;
2652 }
2653 }
2654
2655 if (trgkey != NULL) {
2656 known_target_key = bytes_to_num(trgkey, 6);
2657 set_test_state(best_first_bytes[0]);
2658 } else {
2659 known_target_key = -1;
2660 }
2661
2662 Tests();
2663
2664 free_bitflip_bitarrays();
2665 bool key_found = false;
2666 num_keys_tested = 0;
2667 uint32_t num_odd = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[ODD_STATE];
2668 uint32_t num_even = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[EVEN_STATE];
2669 float expected_brute_force1 = (float)num_odd * num_even / 2.0;
2670 float expected_brute_force2 = nonces[best_first_bytes[0]].expected_num_brute_force;
2671 if (expected_brute_force1 < expected_brute_force2) {
2672 hardnested_print_progress(num_acquired_nonces, "(Ignoring Sum(a8) properties)", expected_brute_force1, 0);
2673 set_test_state(best_first_byte_smallest_bitarray);
2674 add_bitflip_candidates(best_first_byte_smallest_bitarray);
2675 Tests2();
2676 maximum_states = 0;
2677 for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) {
2678 maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE];
2679 }
2680 // printf("Number of remaining possible keys: %" PRIu64 " (2^%1.1f)\n", maximum_states, log(maximum_states)/log(2.0));
2681 best_first_bytes[0] = best_first_byte_smallest_bitarray;
2682 pre_XOR_nonces();
2683 prepare_bf_test_nonces(nonces, best_first_bytes[0]);
2684 hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force1, 0);
2685 key_found = brute_force();
2686 free(candidates->states[ODD_STATE]);
2687 free(candidates->states[EVEN_STATE]);
2688 free_candidates_memory(candidates);
2689 candidates = NULL;
2690 } else {
2691 pre_XOR_nonces();
2692 prepare_bf_test_nonces(nonces, best_first_bytes[0]);
2693 for (uint8_t j = 0; j < NUM_SUMS && !key_found; j++) {
2694 float expected_brute_force = nonces[best_first_bytes[0]].expected_num_brute_force;
2695 sprintf(progress_text, "(%d. guess: Sum(a8) = %" PRIu16 ")", j+1, sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx]);
2696 hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
2697 if (trgkey != NULL && sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx] != real_sum_a8) {
2698 sprintf(progress_text, "(Estimated Sum(a8) is WRONG! Correct Sum(a8) = %" PRIu16 ")", real_sum_a8);
2699 hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0);
2700 }
2701 // printf("Estimated remaining states: %" PRIu64 " (2^%1.1f)\n", nonces[best_first_bytes[0]].sum_a8_guess[j].num_states, log(nonces[best_first_bytes[0]].sum_a8_guess[j].num_states)/log(2.0));
2702 generate_candidates(first_byte_Sum, nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx);
2703 // printf("Time for generating key candidates list: %1.0f sec (%1.1f sec CPU)\n", difftime(time(NULL), start_time), (float)(msclock() - start_clock)/1000.0);
2704 hardnested_print_progress(num_acquired_nonces, "Starting brute force...", expected_brute_force, 0);
2705 key_found = brute_force();
2706 free_statelist_cache();
2707 free_candidates_memory(candidates);
2708 candidates = NULL;
2709 if (!key_found) {
2710 // update the statistics
2711 nonces[best_first_bytes[0]].sum_a8_guess[j].prob = 0;
2712 nonces[best_first_bytes[0]].sum_a8_guess[j].num_states = 0;
2713 // and calculate new expected number of brute forces
2714 update_expected_brute_force(best_first_bytes[0]);
2715 }
2716
2717 }
2718 }
2719
2720 free_nonces_memory();
2721 free_bitarray(all_bitflips_bitarray[ODD_STATE]);
2722 free_bitarray(all_bitflips_bitarray[EVEN_STATE]);
2723 free_sum_bitarrays();
2724 free_part_sum_bitarrays();
2725 }
2726
2727 return 0;
2728 }
Impressum, Datenschutz