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