]> git.zerfleddert.de Git - proxmark3-svn/blame - client/cmdhfmfhard.c
code clean up, added some comments to hitag
[proxmark3-svn] / client / cmdhfmfhard.c
CommitLineData
8ce3e4b4 1//-----------------------------------------------------------------------------
2// Copyright (C) 2015 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 <stdio.h>
18#include <stdlib.h>
19#include <string.h>
20#include <pthread.h>
21#include <math.h>
22#include "proxmark3.h"
23#include "cmdmain.h"
24#include "ui.h"
25#include "util.h"
26#include "nonce2key/crapto1.h"
f8ada309 27#include "parity.h"
8ce3e4b4 28
29// uint32_t test_state_odd = 0;
30// uint32_t test_state_even = 0;
31
f8ada309 32#define CONFIDENCE_THRESHOLD 0.95 // Collect nonces until we are certain enough that the following brute force is successfull
a531720a 33#define GOOD_BYTES_REQUIRED 20
8ce3e4b4 34
35
36static const float p_K[257] = { // the probability that a random nonce has a Sum Property == K
37 0.0290, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
38 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
39 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
40 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
41 0.0083, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
42 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
43 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
44 0.0006, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
45 0.0339, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
46 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
47 0.0048, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
48 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
49 0.0934, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
50 0.0119, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
51 0.0489, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
52 0.0602, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
53 0.4180, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
54 0.0602, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
55 0.0489, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
56 0.0119, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
57 0.0934, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
58 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
59 0.0048, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
60 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
61 0.0339, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
62 0.0006, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
63 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
64 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
65 0.0083, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
66 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
67 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
68 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000,
69 0.0290 };
70
71
72typedef struct noncelistentry {
73 uint32_t nonce_enc;
74 uint8_t par_enc;
75 void *next;
76} noncelistentry_t;
77
78typedef struct noncelist {
79 uint16_t num;
80 uint16_t Sum;
81 uint16_t Sum8_guess;
82 uint8_t BitFlip[2];
83 float Sum8_prob;
84 bool updated;
85 noncelistentry_t *first;
a531720a 86 float score1, score2;
8ce3e4b4 87} noncelist_t;
88
89
90static uint32_t cuid;
91static noncelist_t nonces[256];
92static uint16_t first_byte_Sum = 0;
93static uint16_t first_byte_num = 0;
94static uint16_t num_good_first_bytes = 0;
f8ada309 95static uint64_t maximum_states = 0;
96static uint64_t known_target_key;
8ce3e4b4 97
f8ada309 98#define MAX_BEST_BYTES 256
8ce3e4b4 99static uint8_t best_first_bytes[MAX_BEST_BYTES];
100
101
102typedef enum {
103 EVEN_STATE = 0,
104 ODD_STATE = 1
105} odd_even_t;
106
107#define STATELIST_INDEX_WIDTH 16
108#define STATELIST_INDEX_SIZE (1<<STATELIST_INDEX_WIDTH)
109
110typedef struct {
111 uint32_t *states[2];
112 uint32_t len[2];
113 uint32_t *index[2][STATELIST_INDEX_SIZE];
114} partial_indexed_statelist_t;
115
116typedef struct {
117 uint32_t *states[2];
118 uint32_t len[2];
119 void* next;
120} statelist_t;
121
122
f8ada309 123static partial_indexed_statelist_t partial_statelist[17];
124static partial_indexed_statelist_t statelist_bitflip;
8ce3e4b4 125
f8ada309 126static statelist_t *candidates = NULL;
8ce3e4b4 127
128
129static int add_nonce(uint32_t nonce_enc, uint8_t par_enc)
130{
131 uint8_t first_byte = nonce_enc >> 24;
132 noncelistentry_t *p1 = nonces[first_byte].first;
133 noncelistentry_t *p2 = NULL;
134
135 if (p1 == NULL) { // first nonce with this 1st byte
136 first_byte_num++;
f8ada309 137 first_byte_Sum += evenparity32((nonce_enc & 0xff000000) | (par_enc & 0x08));
8ce3e4b4 138 // printf("Adding nonce 0x%08x, par_enc 0x%02x, parity(0x%08x) = %d\n",
139 // nonce_enc,
140 // par_enc,
141 // (nonce_enc & 0xff000000) | (par_enc & 0x08) |0x01,
f8ada309 142 // parity((nonce_enc & 0xff000000) | (par_enc & 0x08));
8ce3e4b4 143 }
144
145 while (p1 != NULL && (p1->nonce_enc & 0x00ff0000) < (nonce_enc & 0x00ff0000)) {
146 p2 = p1;
147 p1 = p1->next;
148 }
149
150 if (p1 == NULL) { // need to add at the end of the list
151 if (p2 == NULL) { // list is empty yet. Add first entry.
152 p2 = nonces[first_byte].first = malloc(sizeof(noncelistentry_t));
153 } else { // add new entry at end of existing list.
154 p2 = p2->next = malloc(sizeof(noncelistentry_t));
155 }
156 } else if ((p1->nonce_enc & 0x00ff0000) != (nonce_enc & 0x00ff0000)) { // found distinct 2nd byte. Need to insert.
157 if (p2 == NULL) { // need to insert at start of list
158 p2 = nonces[first_byte].first = malloc(sizeof(noncelistentry_t));
159 } else {
160 p2 = p2->next = malloc(sizeof(noncelistentry_t));
161 }
162 } else { // we have seen this 2nd byte before. Nothing to add or insert.
163 return (0);
164 }
165
166 // add or insert new data
167 p2->next = p1;
168 p2->nonce_enc = nonce_enc;
169 p2->par_enc = par_enc;
170
171 nonces[first_byte].num++;
f8ada309 172 nonces[first_byte].Sum += evenparity32((nonce_enc & 0x00ff0000) | (par_enc & 0x04));
8ce3e4b4 173 nonces[first_byte].updated = true; // indicates that we need to recalculate the Sum(a8) probability for this first byte
174
175 return (1); // new nonce added
176}
177
178
179static uint16_t PartialSumProperty(uint32_t state, odd_even_t odd_even)
180{
181 uint16_t sum = 0;
182 for (uint16_t j = 0; j < 16; j++) {
183 uint32_t st = state;
184 uint16_t part_sum = 0;
185 if (odd_even == ODD_STATE) {
186 for (uint16_t i = 0; i < 5; i++) {
187 part_sum ^= filter(st);
188 st = (st << 1) | ((j >> (3-i)) & 0x01) ;
189 }
f8ada309 190 part_sum ^= 1; // XOR 1 cancelled out for the other 8 bits
8ce3e4b4 191 } else {
192 for (uint16_t i = 0; i < 4; i++) {
193 st = (st << 1) | ((j >> (3-i)) & 0x01) ;
194 part_sum ^= filter(st);
195 }
196 }
197 sum += part_sum;
198 }
199 return sum;
200}
201
202
203static uint16_t SumProperty(struct Crypto1State *s)
204{
205 uint16_t sum_odd = PartialSumProperty(s->odd, ODD_STATE);
206 uint16_t sum_even = PartialSumProperty(s->even, EVEN_STATE);
207 return (sum_odd*(16-sum_even) + (16-sum_odd)*sum_even);
208}
209
210
211static double p_hypergeometric(uint16_t N, uint16_t K, uint16_t n, uint16_t k)
212{
213 // for efficient computation we are using the recursive definition
214 // (K-k+1) * (n-k+1)
215 // P(X=k) = P(X=k-1) * --------------------
216 // k * (N-K-n+k)
217 // and
218 // (N-K)*(N-K-1)*...*(N-K-n+1)
219 // P(X=0) = -----------------------------
220 // N*(N-1)*...*(N-n+1)
221
222 if (n-k > N-K || k > K) return 0.0; // avoids log(x<=0) in calculation below
223 if (k == 0) {
224 // use logarithms to avoid overflow with huge factorials (double type can only hold 170!)
225 double log_result = 0.0;
226 for (int16_t i = N-K; i >= N-K-n+1; i--) {
227 log_result += log(i);
228 }
229 for (int16_t i = N; i >= N-n+1; i--) {
230 log_result -= log(i);
231 }
232 return exp(log_result);
233 } else {
234 if (n-k == N-K) { // special case. The published recursion below would fail with a divide by zero exception
235 double log_result = 0.0;
236 for (int16_t i = k+1; i <= n; i++) {
237 log_result += log(i);
238 }
239 for (int16_t i = K+1; i <= N; i++) {
240 log_result -= log(i);
241 }
242 return exp(log_result);
243 } else { // recursion
244 return (p_hypergeometric(N, K, n, k-1) * (K-k+1) * (n-k+1) / (k * (N-K-n+k)));
245 }
246 }
247}
248
249
250static float sum_probability(uint16_t K, uint16_t n, uint16_t k)
251{
252 const uint16_t N = 256;
253
254
255
256 if (k > K || p_K[K] == 0.0) return 0.0;
257
258 double p_T_is_k_when_S_is_K = p_hypergeometric(N, K, n, k);
259 double p_S_is_K = p_K[K];
260 double p_T_is_k = 0;
261 for (uint16_t i = 0; i <= 256; i++) {
262 if (p_K[i] != 0.0) {
263 p_T_is_k += p_K[i] * p_hypergeometric(N, i, n, k);
264 }
265 }
266 return(p_T_is_k_when_S_is_K * p_S_is_K / p_T_is_k);
267}
268
269
a531720a 270
271
272static inline uint_fast8_t common_bits(uint_fast8_t bytes_diff)
273{
274 static const uint_fast8_t common_bits_LUT[256] = {
275 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
276 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
277 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
278 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
279 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
280 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
281 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
282 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
283 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
284 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
285 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
286 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
287 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
288 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
289 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
290 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
291 };
292
293 return common_bits_LUT[bytes_diff];
294}
295
296
8ce3e4b4 297static void Tests()
298{
299 printf("Tests: Partial Statelist sizes\n");
300 for (uint16_t i = 0; i <= 16; i+=2) {
301 printf("Partial State List Odd [%2d] has %8d entries\n", i, partial_statelist[i].len[ODD_STATE]);
302 }
303 for (uint16_t i = 0; i <= 16; i+=2) {
304 printf("Partial State List Even [%2d] has %8d entries\n", i, partial_statelist[i].len[EVEN_STATE]);
305 }
306
307 // #define NUM_STATISTICS 100000
8ce3e4b4 308 // uint32_t statistics_odd[17];
f8ada309 309 // uint64_t statistics[257];
8ce3e4b4 310 // uint32_t statistics_even[17];
311 // struct Crypto1State cs;
312 // time_t time1 = clock();
313
314 // for (uint16_t i = 0; i < 257; i++) {
315 // statistics[i] = 0;
316 // }
317 // for (uint16_t i = 0; i < 17; i++) {
318 // statistics_odd[i] = 0;
319 // statistics_even[i] = 0;
320 // }
321
322 // for (uint64_t i = 0; i < NUM_STATISTICS; i++) {
323 // cs.odd = (rand() & 0xfff) << 12 | (rand() & 0xfff);
324 // cs.even = (rand() & 0xfff) << 12 | (rand() & 0xfff);
325 // uint16_t sum_property = SumProperty(&cs);
326 // statistics[sum_property] += 1;
327 // sum_property = PartialSumProperty(cs.even, EVEN_STATE);
328 // statistics_even[sum_property]++;
329 // sum_property = PartialSumProperty(cs.odd, ODD_STATE);
330 // statistics_odd[sum_property]++;
331 // if (i%(NUM_STATISTICS/100) == 0) printf(".");
332 // }
333
334 // printf("\nTests: Calculated %d Sum properties in %0.3f seconds (%0.0f calcs/second)\n", NUM_STATISTICS, ((float)clock() - time1)/CLOCKS_PER_SEC, NUM_STATISTICS/((float)clock() - time1)*CLOCKS_PER_SEC);
335 // for (uint16_t i = 0; i < 257; i++) {
336 // if (statistics[i] != 0) {
337 // printf("probability[%3d] = %0.5f\n", i, (float)statistics[i]/NUM_STATISTICS);
338 // }
339 // }
340 // for (uint16_t i = 0; i <= 16; i++) {
341 // if (statistics_odd[i] != 0) {
342 // printf("probability odd [%2d] = %0.5f\n", i, (float)statistics_odd[i]/NUM_STATISTICS);
343 // }
344 // }
345 // for (uint16_t i = 0; i <= 16; i++) {
346 // if (statistics_odd[i] != 0) {
347 // printf("probability even [%2d] = %0.5f\n", i, (float)statistics_even[i]/NUM_STATISTICS);
348 // }
349 // }
350
351 // printf("Tests: Sum Probabilities based on Partial Sums\n");
352 // for (uint16_t i = 0; i < 257; i++) {
353 // statistics[i] = 0;
354 // }
355 // uint64_t num_states = 0;
356 // for (uint16_t oddsum = 0; oddsum <= 16; oddsum += 2) {
357 // for (uint16_t evensum = 0; evensum <= 16; evensum += 2) {
358 // uint16_t sum = oddsum*(16-evensum) + (16-oddsum)*evensum;
359 // statistics[sum] += (uint64_t)partial_statelist[oddsum].len[ODD_STATE] * partial_statelist[evensum].len[EVEN_STATE] * (1<<8);
360 // num_states += (uint64_t)partial_statelist[oddsum].len[ODD_STATE] * partial_statelist[evensum].len[EVEN_STATE] * (1<<8);
361 // }
362 // }
363 // printf("num_states = %lld, expected %lld\n", num_states, (1LL<<48));
364 // for (uint16_t i = 0; i < 257; i++) {
365 // if (statistics[i] != 0) {
366 // printf("probability[%3d] = %0.5f\n", i, (float)statistics[i]/num_states);
367 // }
368 // }
369
370 // printf("\nTests: Hypergeometric Probability for selected parameters\n");
371 // printf("p_hypergeometric(256, 206, 255, 206) = %0.8f\n", p_hypergeometric(256, 206, 255, 206));
372 // printf("p_hypergeometric(256, 206, 255, 205) = %0.8f\n", p_hypergeometric(256, 206, 255, 205));
373 // printf("p_hypergeometric(256, 156, 1, 1) = %0.8f\n", p_hypergeometric(256, 156, 1, 1));
374 // printf("p_hypergeometric(256, 156, 1, 0) = %0.8f\n", p_hypergeometric(256, 156, 1, 0));
375 // printf("p_hypergeometric(256, 1, 1, 1) = %0.8f\n", p_hypergeometric(256, 1, 1, 1));
376 // printf("p_hypergeometric(256, 1, 1, 0) = %0.8f\n", p_hypergeometric(256, 1, 1, 0));
377
378 struct Crypto1State *pcs;
379 pcs = crypto1_create(0xffffffffffff);
380 printf("\nTests: for key = 0xffffffffffff:\nSum(a0) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
381 SumProperty(pcs), pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
382 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
383 printf("After adding best first byte 0x%02x:\nSum(a8) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
384 best_first_bytes[0],
385 SumProperty(pcs),
386 pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
387 //test_state_odd = pcs->odd & 0x00ffffff;
388 //test_state_even = pcs->even & 0x00ffffff;
389 crypto1_destroy(pcs);
390 pcs = crypto1_create(0xa0a1a2a3a4a5);
391 printf("Tests: for key = 0xa0a1a2a3a4a5:\nSum(a0) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
392 SumProperty(pcs), pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
393 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
394 printf("After adding best first byte 0x%02x:\nSum(a8) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
395 best_first_bytes[0],
396 SumProperty(pcs),
397 pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
398 // test_state_odd = pcs->odd & 0x00ffffff;
399 // test_state_even = pcs->even & 0x00ffffff;
400 crypto1_destroy(pcs);
f8ada309 401 pcs = crypto1_create(0xa6b9aa97b955);
402 printf("Tests: for key = 0xa6b9aa97b955:\nSum(a0) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
403 SumProperty(pcs), pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
404 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
405 printf("After adding best first byte 0x%02x:\nSum(a8) = %d\nodd_state = 0x%06x\neven_state = 0x%06x\n",
406 best_first_bytes[0],
407 SumProperty(pcs),
408 pcs->odd & 0x00ffffff, pcs->even & 0x00ffffff);
409 //test_state_odd = pcs->odd & 0x00ffffff;
410 //test_state_even = pcs->even & 0x00ffffff;
411 crypto1_destroy(pcs);
412
8ce3e4b4 413
414
415 printf("\nTests: number of states with BitFlipProperty: %d, (= %1.3f%% of total states)\n", statelist_bitflip.len[0], 100.0 * statelist_bitflip.len[0] / (1<<20));
416
417 printf("\nTests: Actual BitFlipProperties odd/even:\n");
418 for (uint16_t i = 0; i < 256; i++) {
f8ada309 419 printf("[%02x]:%c%c ", i, nonces[i].BitFlip[ODD_STATE]?'o':' ', nonces[i].BitFlip[EVEN_STATE]?'e':' ');
8ce3e4b4 420 if (i % 8 == 7) {
421 printf("\n");
422 }
423 }
424
425 printf("\nTests: Best %d first bytes:\n", MAX_BEST_BYTES);
426 for (uint16_t i = 0; i < MAX_BEST_BYTES; i++) {
427 uint8_t best_byte = best_first_bytes[i];
a531720a 428 printf("#%03d Byte: %02x, n = %2d, k = %2d, Sum(a8): %3d, Confidence: %2.1f%%, Bitflip: %c%c\n",
429 //printf("#%03d Byte: %02x, n = %2d, k = %2d, Sum(a8): %3d, Confidence: %2.1f%%, Bitflip: %c%c, score1: %f, score2: %f\n",
430 i, best_byte,
431 nonces[best_byte].num,
432 nonces[best_byte].Sum,
433 nonces[best_byte].Sum8_guess,
434 nonces[best_byte].Sum8_prob * 100,
435 nonces[best_byte].BitFlip[ODD_STATE]?'o':' ',
436 nonces[best_byte].BitFlip[EVEN_STATE]?'e':' '
437 //nonces[best_byte].score1,
438 //nonces[best_byte].score2
439 );
8ce3e4b4 440 }
f8ada309 441
442 // printf("\nTests: parity performance\n");
443 // time_t time1p = clock();
444 // uint32_t par_sum = 0;
445 // for (uint32_t i = 0; i < 100000000; i++) {
446 // par_sum += parity(i);
447 // }
448 // printf("parsum oldparity = %d, time = %1.5fsec\n", par_sum, (float)(clock() - time1p)/CLOCKS_PER_SEC);
449
450 // time1p = clock();
451 // par_sum = 0;
452 // for (uint32_t i = 0; i < 100000000; i++) {
453 // par_sum += evenparity32(i);
454 // }
455 // printf("parsum newparity = %d, time = %1.5fsec\n", par_sum, (float)(clock() - time1p)/CLOCKS_PER_SEC);
456
8ce3e4b4 457
f8ada309 458}
459
460
461static void sort_best_first_bytes(void)
462{
463 // first, sort based on probability for correct guess
8ce3e4b4 464 for (uint16_t i = 0; i < 256; i++ ) {
f8ada309 465 uint16_t j = 0;
8ce3e4b4 466 float prob1 = nonces[i].Sum8_prob;
f8ada309 467 float prob2 = nonces[best_first_bytes[0]].Sum8_prob;
8ce3e4b4 468 while (prob1 < prob2 && j < MAX_BEST_BYTES-1) {
469 prob2 = nonces[best_first_bytes[++j]].Sum8_prob;
470 }
471 if (prob1 >= prob2) {
472 for (uint16_t k = MAX_BEST_BYTES-1; k > j; k--) {
473 best_first_bytes[k] = best_first_bytes[k-1];
474 }
475 best_first_bytes[j] = i;
476 }
477 }
f8ada309 478
479 // determine, how many are above the CONFIDENCE_THRESHOLD
480 uint16_t num_good_nonces = 0;
481 for (uint16_t i = 0; i < MAX_BEST_BYTES; i++) {
482 if (nonces[best_first_bytes[i]].Sum8_prob > CONFIDENCE_THRESHOLD) {
483 ++num_good_nonces;
484 }
485 }
486
487 uint16_t best_first_byte = 0;
488
489 // select the best possible first byte based on number of common bits with all {b'}
490 // uint16_t max_common_bits = 0;
491 // for (uint16_t i = 0; i < num_good_nonces; i++) {
492 // uint16_t sum_common_bits = 0;
493 // for (uint16_t j = 0; j < num_good_nonces; j++) {
494 // if (i != j) {
495 // sum_common_bits += common_bits(best_first_bytes[i],best_first_bytes[j]);
496 // }
497 // }
498 // if (sum_common_bits > max_common_bits) {
499 // max_common_bits = sum_common_bits;
500 // best_first_byte = i;
501 // }
502 // }
503
504 // select best possible first byte {b} based on least likely sum/bitflip property
505 float min_p_K = 1.0;
506 for (uint16_t i = 0; i < num_good_nonces; i++ ) {
507 uint16_t sum8 = nonces[best_first_bytes[i]].Sum8_guess;
508 float bitflip_prob = 1.0;
509 if (nonces[best_first_bytes[i]].BitFlip[ODD_STATE] || nonces[best_first_bytes[i]].BitFlip[EVEN_STATE]) {
510 bitflip_prob = 0.09375;
511 }
a531720a 512 nonces[best_first_bytes[i]].score1 = p_K[sum8] * bitflip_prob;
f8ada309 513 if (p_K[sum8] * bitflip_prob <= min_p_K) {
514 min_p_K = p_K[sum8] * bitflip_prob;
f8ada309 515 }
516 }
517
a531720a 518
f8ada309 519 // use number of commmon bits as a tie breaker
520 uint16_t max_common_bits = 0;
521 for (uint16_t i = 0; i < num_good_nonces; i++) {
522 float bitflip_prob = 1.0;
523 if (nonces[best_first_bytes[i]].BitFlip[ODD_STATE] || nonces[best_first_bytes[i]].BitFlip[EVEN_STATE]) {
524 bitflip_prob = 0.09375;
525 }
526 if (p_K[nonces[best_first_bytes[i]].Sum8_guess] * bitflip_prob == min_p_K) {
527 uint16_t sum_common_bits = 0;
528 for (uint16_t j = 0; j < num_good_nonces; j++) {
a531720a 529 sum_common_bits += common_bits(best_first_bytes[i] ^ best_first_bytes[j]);
f8ada309 530 }
a531720a 531 nonces[best_first_bytes[i]].score2 = sum_common_bits;
f8ada309 532 if (sum_common_bits > max_common_bits) {
533 max_common_bits = sum_common_bits;
534 best_first_byte = i;
535 }
536 }
537 }
538
a531720a 539 // swap best possible first byte to the pole position
f8ada309 540 uint16_t temp = best_first_bytes[0];
541 best_first_bytes[0] = best_first_bytes[best_first_byte];
542 best_first_bytes[best_first_byte] = temp;
543
8ce3e4b4 544}
545
546
547static uint16_t estimate_second_byte_sum(void)
548{
549 for (uint16_t i = 0; i < MAX_BEST_BYTES; i++) {
550 best_first_bytes[i] = 0;
551 }
552
553 for (uint16_t first_byte = 0; first_byte < 256; first_byte++) {
554 float Sum8_prob = 0.0;
555 uint16_t Sum8 = 0;
556 if (nonces[first_byte].updated) {
557 for (uint16_t sum = 0; sum <= 256; sum++) {
558 float prob = sum_probability(sum, nonces[first_byte].num, nonces[first_byte].Sum);
559 if (prob > Sum8_prob) {
560 Sum8_prob = prob;
561 Sum8 = sum;
562 }
563 }
564 nonces[first_byte].Sum8_guess = Sum8;
565 nonces[first_byte].Sum8_prob = Sum8_prob;
566 nonces[first_byte].updated = false;
567 }
568 }
569
570 sort_best_first_bytes();
571
572 uint16_t num_good_nonces = 0;
573 for (uint16_t i = 0; i < MAX_BEST_BYTES; i++) {
574 if (nonces[best_first_bytes[i]].Sum8_prob > CONFIDENCE_THRESHOLD) {
575 ++num_good_nonces;
576 }
577 }
578
579 return num_good_nonces;
580}
581
582
583static int read_nonce_file(void)
584{
585 FILE *fnonces = NULL;
586 uint8_t trgBlockNo;
587 uint8_t trgKeyType;
588 uint8_t read_buf[9];
589 uint32_t nt_enc1, nt_enc2;
590 uint8_t par_enc;
591 int total_num_nonces = 0;
592
593 if ((fnonces = fopen("nonces.bin","rb")) == NULL) {
594 PrintAndLog("Could not open file nonces.bin");
595 return 1;
596 }
597
598 PrintAndLog("Reading nonces from file nonces.bin...");
599 if (fread(read_buf, 1, 6, fnonces) == 0) {
600 PrintAndLog("File reading error.");
601 fclose(fnonces);
602 return 1;
603 }
604 cuid = bytes_to_num(read_buf, 4);
605 trgBlockNo = bytes_to_num(read_buf+4, 1);
606 trgKeyType = bytes_to_num(read_buf+5, 1);
607
608 while (fread(read_buf, 1, 9, fnonces) == 9) {
609 nt_enc1 = bytes_to_num(read_buf, 4);
610 nt_enc2 = bytes_to_num(read_buf+4, 4);
611 par_enc = bytes_to_num(read_buf+8, 1);
612 //printf("Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc1, par_enc >> 4);
613 //printf("Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc2, par_enc & 0x0f);
614 add_nonce(nt_enc1, par_enc >> 4);
615 add_nonce(nt_enc2, par_enc & 0x0f);
616 total_num_nonces += 2;
617 }
618 fclose(fnonces);
619 PrintAndLog("Read %d nonces from file. cuid=%08x, Block=%d, Keytype=%c", total_num_nonces, cuid, trgBlockNo, trgKeyType==0?'A':'B');
620
621 return 0;
622}
623
624
a531720a 625static void Check_for_FilterFlipProperties(void)
626{
627 printf("Checking for Filter Flip Properties...\n");
628
629 for (uint16_t i = 0; i < 256; i++) {
630 nonces[i].BitFlip[ODD_STATE] = false;
631 nonces[i].BitFlip[EVEN_STATE] = false;
632 }
633
634 for (uint16_t i = 0; i < 256; i++) {
635 uint8_t parity1 = (nonces[i].first->par_enc) >> 3; // parity of first byte
636 uint8_t parity2_odd = (nonces[i^0x80].first->par_enc) >> 3; // XOR 0x80 = last bit flipped
637 uint8_t parity2_even = (nonces[i^0x40].first->par_enc) >> 3; // XOR 0x40 = second last bit flipped
638
639 if (parity1 == parity2_odd) { // has Bit Flip Property for odd bits
640 nonces[i].BitFlip[ODD_STATE] = true;
641 } else if (parity1 == parity2_even) { // has Bit Flip Property for even bits
642 nonces[i].BitFlip[EVEN_STATE] = true;
643 }
644 }
645}
646
647
f8ada309 648static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, bool nonce_file_write, bool slow)
8ce3e4b4 649{
650 clock_t time1 = clock();
651 bool initialize = true;
652 bool field_off = false;
653 bool finished = false;
a531720a 654 bool filter_flip_checked = false;
8ce3e4b4 655 uint32_t flags = 0;
656 uint8_t write_buf[9];
657 uint32_t total_num_nonces = 0;
658 uint32_t next_fivehundred = 500;
659 uint32_t total_added_nonces = 0;
660 FILE *fnonces = NULL;
661 UsbCommand resp;
662
663 printf("Acquiring nonces...\n");
664
665 clearCommandBuffer();
666
667 do {
668 flags = 0;
669 flags |= initialize ? 0x0001 : 0;
670 flags |= slow ? 0x0002 : 0;
671 flags |= field_off ? 0x0004 : 0;
672 UsbCommand c = {CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, flags}};
673 memcpy(c.d.asBytes, key, 6);
674
675 SendCommand(&c);
676
677 if (field_off) finished = true;
678
679 if (initialize) {
680 if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) return 1;
681 if (resp.arg[0]) return resp.arg[0]; // error during nested_hard
682
683 cuid = resp.arg[1];
684 // PrintAndLog("Acquiring nonces for CUID 0x%08x", cuid);
685 if (nonce_file_write && fnonces == NULL) {
686 if ((fnonces = fopen("nonces.bin","wb")) == NULL) {
687 PrintAndLog("Could not create file nonces.bin");
688 return 3;
689 }
690 PrintAndLog("Writing acquired nonces to binary file nonces.bin");
691 num_to_bytes(cuid, 4, write_buf);
692 fwrite(write_buf, 1, 4, fnonces);
693 fwrite(&trgBlockNo, 1, 1, fnonces);
694 fwrite(&trgKeyType, 1, 1, fnonces);
695 }
696 }
697
698 if (!initialize) {
699 uint32_t nt_enc1, nt_enc2;
700 uint8_t par_enc;
701 uint16_t num_acquired_nonces = resp.arg[2];
702 uint8_t *bufp = resp.d.asBytes;
703 for (uint16_t i = 0; i < num_acquired_nonces; i+=2) {
704 nt_enc1 = bytes_to_num(bufp, 4);
705 nt_enc2 = bytes_to_num(bufp+4, 4);
706 par_enc = bytes_to_num(bufp+8, 1);
707
708 //printf("Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc1, par_enc >> 4);
709 total_added_nonces += add_nonce(nt_enc1, par_enc >> 4);
710 //printf("Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc2, par_enc & 0x0f);
711 total_added_nonces += add_nonce(nt_enc2, par_enc & 0x0f);
712
713
714 if (nonce_file_write) {
715 fwrite(bufp, 1, 9, fnonces);
716 }
717
718 bufp += 9;
719 }
720
721 total_num_nonces += num_acquired_nonces;
722 }
723
724 if (first_byte_num == 256 ) {
725 // printf("first_byte_num = %d, first_byte_Sum = %d\n", first_byte_num, first_byte_Sum);
a531720a 726 if (!filter_flip_checked) {
727 Check_for_FilterFlipProperties();
728 filter_flip_checked = true;
729 }
8ce3e4b4 730 num_good_first_bytes = estimate_second_byte_sum();
731 if (total_num_nonces > next_fivehundred) {
732 next_fivehundred = (total_num_nonces/500+1) * 500;
733 printf("Acquired %5d nonces (%5d with distinct bytes 0 and 1). Number of bytes with probability for correctly guessed Sum(a8) > %1.1f%%: %d\n",
734 total_num_nonces,
735 total_added_nonces,
736 CONFIDENCE_THRESHOLD * 100.0,
737 num_good_first_bytes);
738 }
739 if (num_good_first_bytes >= GOOD_BYTES_REQUIRED) {
740 field_off = true; // switch off field with next SendCommand and then finish
741 }
742 }
743
744 if (!initialize) {
745 if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) return 1;
746 if (resp.arg[0]) return resp.arg[0]; // error during nested_hard
747 }
748
749 initialize = false;
750
751 } while (!finished);
752
753
754 if (nonce_file_write) {
755 fclose(fnonces);
756 }
757
f8ada309 758 PrintAndLog("Acquired a total of %d nonces in %1.1f seconds (%0.0f nonces/minute)",
8ce3e4b4 759 total_num_nonces,
760 ((float)clock()-time1)/CLOCKS_PER_SEC,
f8ada309 761 total_num_nonces*60.0*CLOCKS_PER_SEC/((float)clock()-time1));
8ce3e4b4 762
763 return 0;
764}
765
766
767static int init_partial_statelists(void)
768{
f8ada309 769 const uint32_t sizes_odd[17] = { 126757, 0, 18387, 0, 74241, 0, 181737, 0, 248801, 0, 182033, 0, 73421, 0, 17607, 0, 125601 };
8ce3e4b4 770 const uint32_t sizes_even[17] = { 125723, 0, 17867, 0, 74305, 0, 178707, 0, 248801, 0, 185063, 0, 73356, 0, 18127, 0, 126634 };
771
772 printf("Allocating memory for partial statelists...\n");
773 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
774 for (uint16_t i = 0; i <= 16; i+=2) {
775 partial_statelist[i].len[odd_even] = 0;
776 uint32_t num_of_states = odd_even == ODD_STATE ? sizes_odd[i] : sizes_even[i];
777 partial_statelist[i].states[odd_even] = malloc(sizeof(uint32_t) * num_of_states);
778 if (partial_statelist[i].states[odd_even] == NULL) {
779 PrintAndLog("Cannot allocate enough memory. Aborting");
780 return 4;
781 }
782 for (uint32_t j = 0; j < STATELIST_INDEX_SIZE; j++) {
783 partial_statelist[i].index[odd_even][j] = NULL;
784 }
785 }
786 }
787
788 printf("Generating partial statelists...\n");
789 for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) {
790 uint32_t index = -1;
791 uint32_t num_of_states = 1<<20;
792 for (uint32_t state = 0; state < num_of_states; state++) {
793 uint16_t sum_property = PartialSumProperty(state, odd_even);
794 uint32_t *p = partial_statelist[sum_property].states[odd_even];
795 p += partial_statelist[sum_property].len[odd_even];
796 *p = state;
797 partial_statelist[sum_property].len[odd_even]++;
798 uint32_t index_mask = (STATELIST_INDEX_SIZE-1) << (20-STATELIST_INDEX_WIDTH);
799 if ((state & index_mask) != index) {
800 index = state & index_mask;
801 }
802 if (partial_statelist[sum_property].index[odd_even][index >> (20-STATELIST_INDEX_WIDTH)] == NULL) {
803 partial_statelist[sum_property].index[odd_even][index >> (20-STATELIST_INDEX_WIDTH)] = p;
804 }
805 }
806 // add End Of List markers
807 for (uint16_t i = 0; i <= 16; i += 2) {
808 uint32_t *p = partial_statelist[i].states[odd_even];
809 p += partial_statelist[i].len[odd_even];
810 *p = 0xffffffff;
811 }
812 }
813
814 return 0;
815}
816
817
818static void init_BitFlip_statelist(void)
819{
820 printf("Generating bitflip statelist...\n");
821 uint32_t *p = statelist_bitflip.states[0] = malloc(sizeof(uint32_t) * 1<<20);
822 uint32_t index = -1;
823 uint32_t index_mask = (STATELIST_INDEX_SIZE-1) << (20-STATELIST_INDEX_WIDTH);
824 for (uint32_t state = 0; state < (1 << 20); state++) {
825 if (filter(state) != filter(state^1)) {
826 if ((state & index_mask) != index) {
827 index = state & index_mask;
828 }
829 if (statelist_bitflip.index[0][index >> (20-STATELIST_INDEX_WIDTH)] == NULL) {
830 statelist_bitflip.index[0][index >> (20-STATELIST_INDEX_WIDTH)] = p;
831 }
832 *p++ = state;
833 }
834 }
835 // set len and add End Of List marker
836 statelist_bitflip.len[0] = p - statelist_bitflip.states[0];
837 *p = 0xffffffff;
838 statelist_bitflip.states[0] = realloc(statelist_bitflip.states[0], sizeof(uint32_t) * (statelist_bitflip.len[0] + 1));
839}
840
841
a531720a 842static inline uint32_t *find_first_state(uint32_t state, uint32_t mask, partial_indexed_statelist_t *sl, odd_even_t odd_even)
8ce3e4b4 843{
844 uint32_t *p = sl->index[odd_even][(state & mask) >> (20-STATELIST_INDEX_WIDTH)]; // first Bits as index
845
846 if (p == NULL) return NULL;
a531720a 847 while (*p < (state & mask)) p++;
8ce3e4b4 848 if (*p == 0xffffffff) return NULL; // reached end of list, no match
849 if ((*p & mask) == (state & mask)) return p; // found a match.
850 return NULL; // no match
851}
852
853
a531720a 854static inline bool /*__attribute__((always_inline))*/ invariant_holds(uint_fast8_t byte_diff, uint_fast32_t state1, uint_fast32_t state2, uint_fast8_t bit, uint_fast8_t state_bit)
8ce3e4b4 855{
a531720a 856 uint_fast8_t j_1_bit_mask = 0x01 << (bit-1);
857 uint_fast8_t bit_diff = byte_diff & j_1_bit_mask; // difference of (j-1)th bit
858 uint_fast8_t filter_diff = filter(state1 >> (4-state_bit)) ^ filter(state2 >> (4-state_bit)); // difference in filter function
859 uint_fast8_t mask_y12_y13 = 0xc0 >> state_bit;
860 uint_fast8_t state_bits_diff = (state1 ^ state2) & mask_y12_y13; // difference in state bits 12 and 13
861 uint_fast8_t all_diff = evenparity8(bit_diff ^ state_bits_diff ^ filter_diff); // use parity function to XOR all bits
862 return !all_diff;
863}
864
865
866static inline bool /*__attribute__((always_inline))*/ invalid_state(uint_fast8_t byte_diff, uint_fast32_t state1, uint_fast32_t state2, uint_fast8_t bit, uint_fast8_t state_bit)
867{
868 uint_fast8_t j_bit_mask = 0x01 << bit;
869 uint_fast8_t bit_diff = byte_diff & j_bit_mask; // difference of jth bit
870 uint_fast8_t mask_y13_y16 = 0x48 >> state_bit;
871 uint_fast8_t state_bits_diff = (state1 ^ state2) & mask_y13_y16; // difference in state bits 13 and 16
872 uint_fast8_t all_diff = evenparity8(bit_diff ^ state_bits_diff); // use parity function to XOR all bits
873 return all_diff;
874}
875
876
877static 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)
878{
879 if (odd_even) {
880 // odd bits
881 switch (num_common_bits) {
882 case 0: if (!invariant_holds(byte_diff, state1, state2, 1, 0)) return true;
883 case 1: if (invalid_state(byte_diff, state1, state2, 1, 0)) return false;
884 case 2: if (!invariant_holds(byte_diff, state1, state2, 3, 1)) return true;
885 case 3: if (invalid_state(byte_diff, state1, state2, 3, 1)) return false;
886 case 4: if (!invariant_holds(byte_diff, state1, state2, 5, 2)) return true;
887 case 5: if (invalid_state(byte_diff, state1, state2, 5, 2)) return false;
888 case 6: if (!invariant_holds(byte_diff, state1, state2, 7, 3)) return true;
889 case 7: if (invalid_state(byte_diff, state1, state2, 7, 3)) return false;
8ce3e4b4 890 }
a531720a 891 } else {
892 // even bits
893 switch (num_common_bits) {
894 case 0: if (invalid_state(byte_diff, state1, state2, 0, 0)) return false;
895 case 1: if (!invariant_holds(byte_diff, state1, state2, 2, 1)) return true;
896 case 2: if (invalid_state(byte_diff, state1, state2, 2, 1)) return false;
897 case 3: if (!invariant_holds(byte_diff, state1, state2, 4, 2)) return true;
898 case 4: if (invalid_state(byte_diff, state1, state2, 4, 2)) return false;
899 case 5: if (!invariant_holds(byte_diff, state1, state2, 6, 3)) return true;
900 case 6: if (invalid_state(byte_diff, state1, state2, 6, 3)) return false;
8ce3e4b4 901 }
8ce3e4b4 902 }
903
904 return true; // valid state
905}
906
907
908static bool all_other_first_bytes_match(uint32_t state, odd_even_t odd_even)
909{
910 for (uint16_t i = 1; i < num_good_first_bytes; i++) {
911 uint16_t sum_a8 = nonces[best_first_bytes[i]].Sum8_guess;
a531720a 912 uint_fast8_t bytes_diff = best_first_bytes[0] ^ best_first_bytes[i];
913 uint_fast8_t j = common_bits(bytes_diff);
8ce3e4b4 914 uint32_t mask = 0xfffffff0;
915 if (odd_even == ODD_STATE) {
a531720a 916 mask >>= j/2;
8ce3e4b4 917 } else {
a531720a 918 mask >>= (j+1)/2;
8ce3e4b4 919 }
920 mask &= 0x000fffff;
921 //printf("bytes 0x%02x and 0x%02x: %d common bits, mask = 0x%08x, state = 0x%08x, sum_a8 = %d", best_first_bytes[0], best_first_bytes[i], j, mask, state, sum_a8);
922 bool found_match = false;
923 for (uint16_t r = 0; r <= 16 && !found_match; r += 2) {
924 for (uint16_t s = 0; s <= 16 && !found_match; s += 2) {
925 if (r*(16-s) + (16-r)*s == sum_a8) {
926 //printf("Checking byte 0x%02x for partial sum (%s) %d\n", best_first_bytes[i], odd_even==ODD_STATE?"odd":"even", odd_even==ODD_STATE?r:s);
927 uint16_t part_sum_a8 = (odd_even == ODD_STATE) ? r : s;
928 uint32_t *p = find_first_state(state, mask, &partial_statelist[part_sum_a8], odd_even);
929 if (p != NULL) {
930 while ((state & mask) == (*p & mask) && (*p != 0xffffffff)) {
a531720a 931 if (remaining_bits_match(j, bytes_diff, state, (state&0x00fffff0) | *p, odd_even)) {
8ce3e4b4 932 found_match = true;
933 // if ((odd_even == ODD_STATE && state == test_state_odd)
934 // || (odd_even == EVEN_STATE && state == test_state_even)) {
935 // printf("all_other_first_bytes_match(): %s test state: remaining bits matched. Bytes = %02x, %02x, Common Bits=%d, mask=0x%08x, PartSum(a8)=%d\n",
936 // odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j, mask, part_sum_a8);
937 // }
938 break;
939 } else {
940 // if ((odd_even == ODD_STATE && state == test_state_odd)
941 // || (odd_even == EVEN_STATE && state == test_state_even)) {
942 // printf("all_other_first_bytes_match(): %s test state: remaining bits didn't match. Bytes = %02x, %02x, Common Bits=%d, mask=0x%08x, PartSum(a8)=%d\n",
943 // odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j, mask, part_sum_a8);
944 // }
945 }
946 p++;
947 }
948 } else {
949 // if ((odd_even == ODD_STATE && state == test_state_odd)
950 // || (odd_even == EVEN_STATE && state == test_state_even)) {
951 // printf("all_other_first_bytes_match(): %s test state: couldn't find a matching state. Bytes = %02x, %02x, Common Bits=%d, mask=0x%08x, PartSum(a8)=%d\n",
952 // odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j, mask, part_sum_a8);
953 // }
954 }
955 }
956 }
957 }
958
959 if (!found_match) {
960 // if ((odd_even == ODD_STATE && state == test_state_odd)
961 // || (odd_even == EVEN_STATE && state == test_state_even)) {
962 // printf("all_other_first_bytes_match(): %s test state: Eliminated. Bytes = %02x, %02x, Common Bits = %d\n", odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j);
963 // }
964 return false;
965 }
966 }
967
968 return true;
969}
970
971
f8ada309 972static bool all_bit_flips_match(uint32_t state, odd_even_t odd_even)
973{
974 for (uint16_t i = 0; i < 256; i++) {
975 if (nonces[i].BitFlip[odd_even] && i != best_first_bytes[0]) {
a531720a 976 uint_fast8_t bytes_diff = best_first_bytes[0] ^ i;
977 uint_fast8_t j = common_bits(bytes_diff);
f8ada309 978 uint32_t mask = 0xfffffff0;
979 if (odd_even == ODD_STATE) {
a531720a 980 mask >>= j/2;
f8ada309 981 } else {
a531720a 982 mask >>= (j+1)/2;
f8ada309 983 }
984 mask &= 0x000fffff;
985 //printf("bytes 0x%02x and 0x%02x: %d common bits, mask = 0x%08x, state = 0x%08x, sum_a8 = %d", best_first_bytes[0], best_first_bytes[i], j, mask, state, sum_a8);
986 bool found_match = false;
987 uint32_t *p = find_first_state(state, mask, &statelist_bitflip, 0);
988 if (p != NULL) {
989 while ((state & mask) == (*p & mask) && (*p != 0xffffffff)) {
a531720a 990 if (remaining_bits_match(j, bytes_diff, state, (state&0x00fffff0) | *p, odd_even)) {
f8ada309 991 found_match = true;
992 // if ((odd_even == ODD_STATE && state == test_state_odd)
993 // || (odd_even == EVEN_STATE && state == test_state_even)) {
994 // printf("all_other_first_bytes_match(): %s test state: remaining bits matched. Bytes = %02x, %02x, Common Bits=%d, mask=0x%08x, PartSum(a8)=%d\n",
995 // odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j, mask, part_sum_a8);
996 // }
997 break;
998 } else {
999 // if ((odd_even == ODD_STATE && state == test_state_odd)
1000 // || (odd_even == EVEN_STATE && state == test_state_even)) {
1001 // printf("all_other_first_bytes_match(): %s test state: remaining bits didn't match. Bytes = %02x, %02x, Common Bits=%d, mask=0x%08x, PartSum(a8)=%d\n",
1002 // odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j, mask, part_sum_a8);
1003 // }
1004 }
1005 p++;
1006 }
1007 } else {
1008 // if ((odd_even == ODD_STATE && state == test_state_odd)
1009 // || (odd_even == EVEN_STATE && state == test_state_even)) {
1010 // printf("all_other_first_bytes_match(): %s test state: couldn't find a matching state. Bytes = %02x, %02x, Common Bits=%d, mask=0x%08x, PartSum(a8)=%d\n",
1011 // odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j, mask, part_sum_a8);
1012 // }
1013 }
1014 if (!found_match) {
1015 // if ((odd_even == ODD_STATE && state == test_state_odd)
1016 // || (odd_even == EVEN_STATE && state == test_state_even)) {
1017 // printf("all_other_first_bytes_match(): %s test state: Eliminated. Bytes = %02x, %02x, Common Bits = %d\n", odd_even==ODD_STATE?"odd":"even", best_first_bytes[0], best_first_bytes[i], j);
1018 // }
1019 return false;
1020 }
1021 }
1022
1023 }
1024
1025 return true;
1026}
1027
1028
a531720a 1029static struct sl_cache_entry {
1030 uint32_t *sl;
1031 uint32_t len;
1032 } sl_cache[17][17][2];
1033
1034
1035static void init_statelist_cache(void)
1036{
1037
1038 for (uint16_t i = 0; i < 17; i+=2) {
1039 for (uint16_t j = 0; j < 17; j+=2) {
1040 for (uint16_t k = 0; k < 2; k++) {
1041 sl_cache[i][j][k].sl = NULL;
1042 sl_cache[i][j][k].len = 0;
1043 }
1044 }
1045 }
1046}
1047
f8ada309 1048
8ce3e4b4 1049static int add_matching_states(statelist_t *candidates, uint16_t part_sum_a0, uint16_t part_sum_a8, odd_even_t odd_even)
1050{
1051 uint32_t worstcase_size = 1<<20;
1052
a531720a 1053 // check cache for existing results
1054 if (sl_cache[part_sum_a0][part_sum_a8][odd_even].sl != NULL) {
1055 candidates->states[odd_even] = sl_cache[part_sum_a0][part_sum_a8][odd_even].sl;
1056 candidates->len[odd_even] = sl_cache[part_sum_a0][part_sum_a8][odd_even].len;
1057 return 0;
1058 }
1059
8ce3e4b4 1060 candidates->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
1061 if (candidates->states[odd_even] == NULL) {
1062 PrintAndLog("Out of memory error.\n");
1063 return 4;
1064 }
a531720a 1065 uint32_t *add_p = candidates->states[odd_even];
8ce3e4b4 1066 for (uint32_t *p1 = partial_statelist[part_sum_a0].states[odd_even]; *p1 != 0xffffffff; p1++) {
1067 uint32_t search_mask = 0x000ffff0;
1068 uint32_t *p2 = find_first_state((*p1 << 4), search_mask, &partial_statelist[part_sum_a8], odd_even);
1069 if (p2 != NULL) {
1070 while (((*p1 << 4) & search_mask) == (*p2 & search_mask) && *p2 != 0xffffffff) {
a531720a 1071 if ((nonces[best_first_bytes[0]].BitFlip[odd_even] && find_first_state((*p1 << 4) | *p2, 0x000fffff, &statelist_bitflip, 0))
1072 || !nonces[best_first_bytes[0]].BitFlip[odd_even]) {
8ce3e4b4 1073 if (all_other_first_bytes_match((*p1 << 4) | *p2, odd_even)) {
f8ada309 1074 if (all_bit_flips_match((*p1 << 4) | *p2, odd_even)) {
a531720a 1075 *add_p++ = (*p1 << 4) | *p2;
1076 }
8ce3e4b4 1077 }
f8ada309 1078 }
8ce3e4b4 1079 p2++;
1080 }
1081 }
8ce3e4b4 1082 }
f8ada309 1083
a531720a 1084 // set end of list marker and len
1085 *add_p = 0xffffffff;
1086 candidates->len[odd_even] = add_p - candidates->states[odd_even];
f8ada309 1087
8ce3e4b4 1088 candidates->states[odd_even] = realloc(candidates->states[odd_even], sizeof(uint32_t) * (candidates->len[odd_even] + 1));
1089
a531720a 1090 sl_cache[part_sum_a0][part_sum_a8][odd_even].sl = candidates->states[odd_even];
1091 sl_cache[part_sum_a0][part_sum_a8][odd_even].len = candidates->len[odd_even];
1092
8ce3e4b4 1093 return 0;
1094}
1095
1096
1097static statelist_t *add_more_candidates(statelist_t *current_candidates)
1098{
1099 statelist_t *new_candidates = NULL;
1100 if (current_candidates == NULL) {
1101 if (candidates == NULL) {
1102 candidates = (statelist_t *)malloc(sizeof(statelist_t));
1103 }
1104 new_candidates = candidates;
1105 } else {
1106 new_candidates = current_candidates->next = (statelist_t *)malloc(sizeof(statelist_t));
1107 }
1108 new_candidates->next = NULL;
1109 new_candidates->len[ODD_STATE] = 0;
1110 new_candidates->len[EVEN_STATE] = 0;
1111 new_candidates->states[ODD_STATE] = NULL;
1112 new_candidates->states[EVEN_STATE] = NULL;
1113 return new_candidates;
1114}
1115
1116
1117static void TestIfKeyExists(uint64_t key)
1118{
1119 struct Crypto1State *pcs;
1120 pcs = crypto1_create(key);
1121 crypto1_byte(pcs, (cuid >> 24) ^ best_first_bytes[0], true);
1122
1123 uint32_t state_odd = pcs->odd & 0x00ffffff;
1124 uint32_t state_even = pcs->even & 0x00ffffff;
f8ada309 1125 //printf("Tests: searching for key %llx after first byte 0x%02x (state_odd = 0x%06x, state_even = 0x%06x) ...\n", key, best_first_bytes[0], state_odd, state_even);
8ce3e4b4 1126
f8ada309 1127 uint64_t count = 0;
8ce3e4b4 1128 for (statelist_t *p = candidates; p != NULL; p = p->next) {
f8ada309 1129 bool found_odd = false;
1130 bool found_even = false;
8ce3e4b4 1131 uint32_t *p_odd = p->states[ODD_STATE];
1132 uint32_t *p_even = p->states[EVEN_STATE];
1133 while (*p_odd != 0xffffffff) {
f8ada309 1134 if ((*p_odd & 0x00ffffff) == state_odd) {
1135 found_odd = true;
1136 break;
1137 }
8ce3e4b4 1138 p_odd++;
1139 }
1140 while (*p_even != 0xffffffff) {
f8ada309 1141 if ((*p_even & 0x00ffffff) == state_even) {
1142 found_even = true;
1143 }
8ce3e4b4 1144 p_even++;
1145 }
f8ada309 1146 count += (p_odd - p->states[ODD_STATE]) * (p_even - p->states[EVEN_STATE]);
1147 if (found_odd && found_even) {
1148 PrintAndLog("Key Found after testing %lld (2^%1.1f) out of %lld (2^%1.1f) keys. A brute force would have taken approx %lld minutes.",
1149 count, log(count)/log(2),
1150 maximum_states, log(maximum_states)/log(2),
1151 (count>>22)/60);
1152 crypto1_destroy(pcs);
1153 return;
1154 }
8ce3e4b4 1155 }
f8ada309 1156
1157 printf("Key NOT found!\n");
8ce3e4b4 1158 crypto1_destroy(pcs);
1159}
1160
1161
1162static void generate_candidates(uint16_t sum_a0, uint16_t sum_a8)
1163{
1164 printf("Generating crypto1 state candidates... \n");
1165
1166 statelist_t *current_candidates = NULL;
1167 // estimate maximum candidate states
f8ada309 1168 maximum_states = 0;
8ce3e4b4 1169 for (uint16_t sum_odd = 0; sum_odd <= 16; sum_odd += 2) {
1170 for (uint16_t sum_even = 0; sum_even <= 16; sum_even += 2) {
1171 if (sum_odd*(16-sum_even) + (16-sum_odd)*sum_even == sum_a0) {
1172 maximum_states += (uint64_t)partial_statelist[sum_odd].len[ODD_STATE] * partial_statelist[sum_even].len[EVEN_STATE] * (1<<8);
1173 }
1174 }
1175 }
1176 printf("Number of possible keys with Sum(a0) = %d: %lld (2^%1.1f)\n", sum_a0, maximum_states, log(maximum_states)/log(2.0));
1177
a531720a 1178 init_statelist_cache();
1179
8ce3e4b4 1180 for (uint16_t p = 0; p <= 16; p += 2) {
1181 for (uint16_t q = 0; q <= 16; q += 2) {
1182 if (p*(16-q) + (16-p)*q == sum_a0) {
1183 printf("Reducing Partial Statelists (p,q) = (%d,%d) with lengths %d, %d\n",
1184 p, q, partial_statelist[p].len[ODD_STATE], partial_statelist[q].len[EVEN_STATE]);
1185 for (uint16_t r = 0; r <= 16; r += 2) {
1186 for (uint16_t s = 0; s <= 16; s += 2) {
1187 if (r*(16-s) + (16-r)*s == sum_a8) {
1188 current_candidates = add_more_candidates(current_candidates);
a531720a 1189 // check for the smallest partial statelist. Try this first - it might give 0 candidates
1190 // and eliminate the need to calculate the other part
1191 if (MIN(partial_statelist[p].len[ODD_STATE], partial_statelist[r].len[ODD_STATE])
1192 < MIN(partial_statelist[q].len[EVEN_STATE], partial_statelist[s].len[EVEN_STATE])) {
8ce3e4b4 1193 add_matching_states(current_candidates, p, r, ODD_STATE);
a531720a 1194 if(current_candidates->len[ODD_STATE]) {
8ce3e4b4 1195 add_matching_states(current_candidates, q, s, EVEN_STATE);
a531720a 1196 } else {
1197 current_candidates->len[EVEN_STATE] = 0;
1198 uint32_t *p = current_candidates->states[EVEN_STATE] = malloc(sizeof(uint32_t));
1199 *p = 0xffffffff;
1200 }
1201 } else {
1202 add_matching_states(current_candidates, q, s, EVEN_STATE);
1203 if(current_candidates->len[EVEN_STATE]) {
1204 add_matching_states(current_candidates, p, r, ODD_STATE);
1205 } else {
1206 current_candidates->len[ODD_STATE] = 0;
1207 uint32_t *p = current_candidates->states[ODD_STATE] = malloc(sizeof(uint32_t));
1208 *p = 0xffffffff;
1209 }
1210 }
1211 printf("Odd state candidates: %6d (2^%0.1f)\n", current_candidates->len[ODD_STATE], log(current_candidates->len[ODD_STATE])/log(2));
1212 printf("Even state candidates: %6d (2^%0.1f)\n", current_candidates->len[EVEN_STATE], log(current_candidates->len[EVEN_STATE])/log(2));
8ce3e4b4 1213 }
1214 }
1215 }
1216 }
1217 }
1218 }
1219
1220
1221 maximum_states = 0;
1222 for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) {
1223 maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE];
1224 }
1225 printf("Number of remaining possible keys: %lld (2^%1.1f)\n", maximum_states, log(maximum_states)/log(2.0));
1226
8ce3e4b4 1227}
1228
1229
f8ada309 1230static void brute_force(void)
8ce3e4b4 1231{
f8ada309 1232 if (known_target_key != -1) {
1233 PrintAndLog("Looking for known target key in remaining key space...");
1234 TestIfKeyExists(known_target_key);
1235 return;
1236 } else {
1237 PrintAndLog("Brute Force phase is not implemented.");
1238 return;
1239 }
1240
1241
1242}
1243
1244
1245int 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)
1246{
1247 if (trgkey != NULL) {
1248 known_target_key = bytes_to_num(trgkey, 6);
1249 } else {
1250 known_target_key = -1;
1251 }
8ce3e4b4 1252
1253 // initialize the list of nonces
1254 for (uint16_t i = 0; i < 256; i++) {
1255 nonces[i].num = 0;
1256 nonces[i].Sum = 0;
1257 nonces[i].Sum8_guess = 0;
1258 nonces[i].Sum8_prob = 0.0;
1259 nonces[i].updated = true;
1260 nonces[i].first = NULL;
1261 }
1262 first_byte_num = 0;
1263 first_byte_Sum = 0;
1264 num_good_first_bytes = 0;
1265
1266 init_partial_statelists();
1267 init_BitFlip_statelist();
1268
1269 if (nonce_file_read) { // use pre-acquired data from file nonces.bin
1270 if (read_nonce_file() != 0) {
1271 return 3;
1272 }
a531720a 1273 Check_for_FilterFlipProperties();
f8ada309 1274 num_good_first_bytes = MIN(estimate_second_byte_sum(), GOOD_BYTES_REQUIRED);
8ce3e4b4 1275 } else { // acquire nonces.
1276 uint16_t is_OK = acquire_nonces(blockNo, keyType, key, trgBlockNo, trgKeyType, nonce_file_write, slow);
1277 if (is_OK != 0) {
1278 return is_OK;
1279 }
1280 }
1281
8ce3e4b4 1282
1283 Tests();
1284
1285 PrintAndLog("");
1286 PrintAndLog("Sum(a0) = %d", first_byte_Sum);
1287 // PrintAndLog("Best 10 first bytes: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x",
1288 // best_first_bytes[0],
1289 // best_first_bytes[1],
1290 // best_first_bytes[2],
1291 // best_first_bytes[3],
1292 // best_first_bytes[4],
1293 // best_first_bytes[5],
1294 // best_first_bytes[6],
1295 // best_first_bytes[7],
1296 // best_first_bytes[8],
1297 // best_first_bytes[9] );
1298 PrintAndLog("Number of first bytes with confidence > %2.1f%%: %d", CONFIDENCE_THRESHOLD*100.0, num_good_first_bytes);
1299
a531720a 1300 time_t start_time = clock();
8ce3e4b4 1301 generate_candidates(first_byte_Sum, nonces[best_first_bytes[0]].Sum8_guess);
a531720a 1302 PrintAndLog("Time for generating key candidates list: %1.0f seconds", (float)(clock() - start_time)/CLOCKS_PER_SEC);
8ce3e4b4 1303
f8ada309 1304 brute_force();
8ce3e4b4 1305
1306 return 0;
1307}
1308
1309
Impressum, Datenschutz