forked from Proxmark/proxmark3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hitag2.c
1845 lines (1614 loc) · 52.7 KB
/
hitag2.c
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
//-----------------------------------------------------------------------------
// This code is licensed to you under the terms of the GNU GPL, version 2 or,
// at your option, any later version. See the LICENSE.txt file for the text of
// the license.
//-----------------------------------------------------------------------------
// Hitag2 emulation (preliminary test version)
//
// (c) 2009 Henryk Plötz <[email protected]>
//-----------------------------------------------------------------------------
// Hitag2 complete rewrite of the code
// - Fixed modulation/encoding issues
// - Rewrote code for transponder emulation
// - Added snooping of transponder communication
// - Added reader functionality
//
// (c) 2012 Roel Verdult
//-----------------------------------------------------------------------------
#include "hitag2.h"
#include "proxmark3.h"
#include "usb_cdc.h"
#include "apps.h"
#include "util.h"
#include "hitag.h"
#include "string.h"
#include "BigBuf.h"
#include "fpgaloader.h"
#include "protocols.h"
static bool bQuiet;
static bool bCrypto;
static bool bAuthenticating;
static bool bPwd;
static bool bSuccessful;
struct hitag2_tag {
uint32_t uid;
enum {
TAG_STATE_RESET = 0x01, // Just powered up, awaiting GetSnr
TAG_STATE_ACTIVATING = 0x02 , // In activation phase (password mode), sent UID, awaiting reader password
TAG_STATE_ACTIVATED = 0x03, // Activation complete, awaiting read/write commands
TAG_STATE_WRITING = 0x04, // In write command, awaiting sector contents to be written
} state;
unsigned int active_sector;
uint8_t crypto_active;
uint64_t cs;
uint8_t sectors[12][4];
};
static struct hitag2_tag tag = {
.state = TAG_STATE_RESET,
.sectors = { // Password mode: | Crypto mode:
[0] = { 0x02, 0x4e, 0x02, 0x20}, // UID | UID
[1] = { 0x4d, 0x49, 0x4b, 0x52}, // Password RWD | 32 bit LSB key
[2] = { 0x20, 0xf0, 0x4f, 0x4e}, // Reserved | 16 bit MSB key, 16 bit reserved
[3] = { 0x0e, 0xaa, 0x48, 0x54}, // Configuration, password TAG | Configuration, password TAG
[4] = { 0x46, 0x5f, 0x4f, 0x4b}, // Data: F_OK
[5] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
[6] = { 0xaa, 0xaa, 0xaa, 0xaa}, // Data: ....
[7] = { 0x55, 0x55, 0x55, 0x55}, // Data: UUUU
[8] = { 0x00, 0x00, 0x00, 0x00}, // RSK Low
[9] = { 0x00, 0x00, 0x00, 0x00}, // RSK High
[10] = { 0x00, 0x00, 0x00, 0x00}, // RCF
[11] = { 0x00, 0x00, 0x00, 0x00}, // SYNC
},
};
static enum {
WRITE_STATE_START = 0x0,
WRITE_STATE_PAGENUM_WRITTEN,
WRITE_STATE_PROG
} writestate;
// ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
// Historically it used to be FREE_BUFFER_SIZE, which was 2744.
#define AUTH_TABLE_LENGTH 2744
static uint8_t *auth_table;
static size_t auth_table_pos = 0;
static size_t auth_table_len = AUTH_TABLE_LENGTH;
static uint8_t password[4];
static uint8_t NrAr[8];
static uint8_t key[8];
static uint8_t writedata[4];
static uint64_t cipher_state;
/* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
// Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
// For educational purposes only.
// No warranties or guarantees of any kind.
// This code is released into the public domain by its author.
// Single bit Hitag2 functions:
#define i4(x,a,b,c,d) ((uint32_t)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8))
static const uint32_t ht2_f4a = 0x2C79; // 0010 1100 0111 1001
static const uint32_t ht2_f4b = 0x6671; // 0110 0110 0111 0001
static const uint32_t ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011
static uint32_t _f20(const uint64_t x) {
uint32_t i5;
i5 = ((ht2_f4a >> i4(x, 1, 2, 4, 5)) & 1) * 1
+ ((ht2_f4b >> i4(x, 7,11,13,14)) & 1) * 2
+ ((ht2_f4b >> i4(x,16,20,22,25)) & 1) * 4
+ ((ht2_f4b >> i4(x,27,28,30,32)) & 1) * 8
+ ((ht2_f4a >> i4(x,33,42,43,45)) & 1) * 16;
return (ht2_f5c >> i5) & 1;
}
static uint64_t _hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV) {
uint32_t i;
uint64_t x = ((key & 0xFFFF) << 32) + serial;
for (i = 0; i < 32; i++) {
x >>= 1;
x += (uint64_t)(_f20(x) ^ (((IV >> i) ^ (key >> (i+16))) & 1)) << 47;
}
return x;
}
static uint64_t _hitag2_round(uint64_t *state) {
uint64_t x = *state;
x = (x >> 1) +
((((x >> 0) ^ (x >> 2) ^ (x >> 3) ^ (x >> 6)
^ (x >> 7) ^ (x >> 8) ^ (x >> 16) ^ (x >> 22)
^ (x >> 23) ^ (x >> 26) ^ (x >> 30) ^ (x >> 41)
^ (x >> 42) ^ (x >> 43) ^ (x >> 46) ^ (x >> 47)) & 1) << 47);
*state = x;
return _f20(x);
}
static uint32_t _hitag2_byte(uint64_t *x) {
uint32_t i, c;
for (i = 0, c = 0; i < 8; i++) {
c += (uint32_t) _hitag2_round(x) << (i^7);
}
return c;
}
static int hitag2_reset(void) {
tag.state = TAG_STATE_RESET;
tag.crypto_active = 0;
return 0;
}
static int hitag2_init(void) {
hitag2_reset();
return 0;
}
static void hitag2_cipher_reset(struct hitag2_tag *tag, const uint8_t *iv) {
uint64_t key = ((uint64_t)tag->sectors[2][2]) |
((uint64_t)tag->sectors[2][3] << 8) |
((uint64_t)tag->sectors[1][0] << 16) |
((uint64_t)tag->sectors[1][1] << 24) |
((uint64_t)tag->sectors[1][2] << 32) |
((uint64_t)tag->sectors[1][3] << 40);
uint32_t uid = ((uint32_t)tag->sectors[0][0]) |
((uint32_t)tag->sectors[0][1] << 8) |
((uint32_t)tag->sectors[0][2] << 16) |
((uint32_t)tag->sectors[0][3] << 24);
uint32_t iv_ = (((uint32_t)(iv[0]))) |
(((uint32_t)(iv[1])) << 8) |
(((uint32_t)(iv[2])) << 16) |
(((uint32_t)(iv[3])) << 24);
tag->cs = _hitag2_init(REV64(key), REV32(uid), REV32(iv_));
}
static int hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is) {
uint8_t authenticator_should[4];
authenticator_should[0] = ~_hitag2_byte(cs);
authenticator_should[1] = ~_hitag2_byte(cs);
authenticator_should[2] = ~_hitag2_byte(cs);
authenticator_should[3] = ~_hitag2_byte(cs);
return (memcmp(authenticator_should, authenticator_is, 4) == 0);
}
static int hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, unsigned int bytes, unsigned int bits) {
int i;
for (i = 0; i < bytes; i++) data[i] ^= _hitag2_byte(cs);
for (i = 0; i < bits; i++) data[bytes] ^= _hitag2_round(cs) << (7-i);
return 0;
}
// Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
// TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
// Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
// T0 = TIMER_CLOCK1 / 125000 = 192
#define T0 192
#define HITAG_FRAME_LEN 20
#define HITAG_T_STOP 36 /* T_EOF should be > 36 */
#define HITAG_T_LOW 8 /* T_LOW should be 4..10 */
#define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
#define HITAG_T_1_MIN 25 /* T[1] should be 26..30 */
//#define HITAG_T_EOF 40 /* T_EOF should be > 36 */
#define HITAG_T_EOF 80 /* T_EOF should be > 36 */
#define HITAG_T_WAIT_1 200 /* T_wresp should be 199..206 */
#define HITAG_T_WAIT_2 90 /* T_wresp should be 199..206 */
#define HITAG_T_WAIT_MAX 300 /* bit more than HITAG_T_WAIT_1 + HITAG_T_WAIT_2 */
#define HITAG_T_PROG 614
#define HITAG_T_TAG_ONE_HALF_PERIOD 10
#define HITAG_T_TAG_TWO_HALF_PERIOD 25
#define HITAG_T_TAG_THREE_HALF_PERIOD 41
#define HITAG_T_TAG_FOUR_HALF_PERIOD 57
#define HITAG_T_TAG_HALF_PERIOD 16
#define HITAG_T_TAG_FULL_PERIOD 32
#define HITAG_T_TAG_CAPTURE_ONE_HALF 13
#define HITAG_T_TAG_CAPTURE_TWO_HALF 25
#define HITAG_T_TAG_CAPTURE_THREE_HALF 41
#define HITAG_T_TAG_CAPTURE_FOUR_HALF 57
static void hitag_send_bit(int bit) {
LED_A_ON();
// Reset clock for the next bit
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
// Fixed modulation, earlier proxmark version used inverted signal
if (bit == 0) {
// Manchester: Unloaded, then loaded |__--|
LOW(GPIO_SSC_DOUT);
while (AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
HIGH(GPIO_SSC_DOUT);
while (AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
} else {
// Manchester: Loaded, then unloaded |--__|
HIGH(GPIO_SSC_DOUT);
while (AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_HALF_PERIOD);
LOW(GPIO_SSC_DOUT);
while (AT91C_BASE_TC0->TC_CV < T0*HITAG_T_TAG_FULL_PERIOD);
}
LED_A_OFF();
}
static void hitag_send_frame(const uint8_t *frame, size_t frame_len)
{
// Send start of frame
for(size_t i = 0; i < 5; i++) {
hitag_send_bit(1);
}
// Send the content of the frame
for (size_t i = 0; i < frame_len; i++) {
hitag_send_bit((frame[i/8] >> (7-(i%8))) & 0x01);
}
// Drop the modulation
LOW(GPIO_SSC_DOUT);
}
static void hitag2_handle_reader_command(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
uint8_t rx_air[HITAG_FRAME_LEN];
// Copy the (original) received frame how it is send over the air
memcpy(rx_air, rx, nbytes(rxlen));
if (tag.crypto_active) {
hitag2_cipher_transcrypt(&(tag.cs), rx, rxlen/8, rxlen%8);
}
// Reset the transmission frame length
*txlen = 0;
// Try to find out which command was send by selecting on length (in bits)
switch (rxlen) {
// Received 11000 from the reader, request for UID, send UID
case 05: {
// Always send over the air in the clear plaintext mode
if (rx_air[0] != HITAG2_START_AUTH) {
// Unknown frame ?
return;
}
*txlen = 32;
memcpy(tx, tag.sectors[0], 4);
tag.crypto_active = 0;
}
break;
// Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number
case 10: {
unsigned int sector = (~( ((rx[0]<<2) & 0x04) | ((rx[1]>>6) & 0x03) ) & 0x07);
// Verify complement of sector index
if (sector != ((rx[0]>>3) & 0x07)) {
//DbpString("Transmission error (read/write)");
return;
}
switch (rx[0] & 0xC6) {
// Read command: 11xx x00y
case HITAG2_READ_PAGE:
memcpy(tx, tag.sectors[sector], 4);
*txlen = 32;
break;
// Inverted Read command: 01xx x10y
case HITAG2_READ_PAGE_INVERTED:
for (size_t i = 0; i < 4; i++) {
tx[i] = tag.sectors[sector][i] ^ 0xff;
}
*txlen = 32;
break;
// Write command: 10xx x01y
case HITAG2_WRITE_PAGE:
// Prepare write, acknowledge by repeating command
memcpy(tx, rx, nbytes(rxlen));
*txlen = rxlen;
tag.active_sector = sector;
tag.state = TAG_STATE_WRITING;
break;
// Unknown command
default:
Dbprintf("Unknown command: %02x %02x", rx[0], rx[1]);
return;
break;
}
}
break;
// Writing data or Reader password
case 32: {
if (tag.state == TAG_STATE_WRITING) {
// These are the sector contents to be written. We don't have to do anything else.
memcpy(tag.sectors[tag.active_sector], rx, nbytes(rxlen));
tag.state = TAG_STATE_RESET;
return;
} else {
// Received RWD password, respond with configuration and our password
if (memcmp(rx, tag.sectors[1], 4) != 0) {
DbpString("Reader password is wrong");
return;
}
*txlen = 32;
memcpy(tx, tag.sectors[3], 4);
}
}
break;
// Received RWD authentication challenge and respnse
case 64: {
// Store the authentication attempt
if (auth_table_len < (AUTH_TABLE_LENGTH-8)) {
memcpy(auth_table+auth_table_len, rx, 8);
auth_table_len += 8;
}
// Reset the cipher state
hitag2_cipher_reset(&tag, rx);
// Check if the authentication was correct
if (!hitag2_cipher_authenticate(&(tag.cs), rx+4)) {
// The reader failed to authenticate, do nothing
Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed!", rx[0], rx[1], rx[2], rx[3], rx[4], rx[5], rx[6], rx[7]);
return;
}
// Succesful, but commented out reporting back to the Host, this may delay to much.
// Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x OK!",rx[0],rx[1],rx[2],rx[3],rx[4],rx[5],rx[6],rx[7]);
// Activate encryption algorithm for all further communication
tag.crypto_active = 1;
// Use the tag password as response
memcpy(tx, tag.sectors[3], 4);
*txlen = 32;
}
break;
}
// LogTraceHitag(rx, rxlen, 0, 0, false);
// LogTraceHitag(tx, *txlen, 0, 0, true);
if (tag.crypto_active) {
hitag2_cipher_transcrypt(&(tag.cs), tx, *txlen/8, *txlen%8);
}
}
static void hitag_reader_send_bit(int bit) {
LED_A_ON();
// Reset clock for the next bit
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
// Binary puls length modulation (BPLM) is used to encode the data stream
// This means that a transmission of a one takes longer than that of a zero
// Enable modulation, which means, drop the field
HIGH(GPIO_SSC_DOUT);
// t_low = 4...10 carrier periods
while (AT91C_BASE_TC0->TC_CV < T0*6);
// Disable modulation, just activates the field again
LOW(GPIO_SSC_DOUT);
if (bit == 0) {
// Zero bit: |_-|, T[0] = 18...22 carrier periods
while (AT91C_BASE_TC0->TC_CV < T0*22);
} else {
// One bit: |_--|, T[1] = 26...32 carrier periods
while (AT91C_BASE_TC0->TC_CV < T0*28);
}
LED_A_OFF();
}
static void hitag_reader_send_frame(const uint8_t *frame, size_t frame_len)
{
// Send the content of the frame
for(size_t i = 0; i < frame_len; i++) {
hitag_reader_send_bit((frame[i/8] >> (7-(i%8))) & 0x01);
}
// Send EOF
AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG;
// Enable modulation, which means, drop the field
HIGH(GPIO_SSC_DOUT);
// t_low = 4...10 carrier periods
while (AT91C_BASE_TC0->TC_CV < T0*6);
// Disable modulation, just activates the field again
LOW(GPIO_SSC_DOUT);
// t_stop > 36 carrier periods
while (AT91C_BASE_TC0->TC_CV < T0*36);
}
size_t blocknr;
//-----------------------------------------------------------------------------
// Hitag2 operations
//-----------------------------------------------------------------------------
static bool hitag2_write_page(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
switch (writestate) {
case WRITE_STATE_START:
tx[0] = HITAG2_WRITE_PAGE | (blocknr << 3) | ((blocknr^7) >> 2);
tx[1] = ((blocknr^7) << 6);
*txlen = 10;
writestate = WRITE_STATE_PAGENUM_WRITTEN;
break;
case WRITE_STATE_PAGENUM_WRITTEN:
// Check if page number was received correctly
if ((rxlen == 10)
&& (rx[0] == (HITAG2_WRITE_PAGE | (blocknr << 3) | ((blocknr^7) >> 2)))
&& (rx[1] == (((blocknr & 0x3) ^ 0x3) << 6))) {
*txlen = 32;
memset(tx, 0, HITAG_FRAME_LEN);
memcpy(tx, writedata, 4);
writestate = WRITE_STATE_PROG;
} else {
Dbprintf("hitag2_write_page: Page number was not received correctly: rxlen=%d rx=%02x%02x%02x%02x",
rxlen, rx[0], rx[1], rx[2], rx[3]);
bSuccessful = false;
return false;
}
break;
case WRITE_STATE_PROG:
if (rxlen == 0) {
bSuccessful = true;
} else {
bSuccessful = false;
Dbprintf("hitag2_write_page: unexpected rx data (%d) after page write", rxlen);
}
return false;
default:
DbpString("hitag2_write_page: Unknown state %d");
bSuccessful = false;
return false;
}
return true;
}
static bool hitag2_password(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen, bool write) {
// Reset the transmission frame length
*txlen = 0;
if (bPwd && !bAuthenticating && write) {
if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
return false;
}
} else {
// Try to find out which command was send by selecting on length (in bits)
switch (rxlen) {
// No answer, try to resurrect
case 0: {
// Stop if there is no answer (after sending password)
if (bPwd) {
DbpString("Password failed!");
return false;
}
tx[0] = HITAG2_START_AUTH;
*txlen = 5;
}
break;
// Received UID, tag password
case 32: {
if (!bPwd) {
bPwd = true;
bAuthenticating = true;
memcpy(tx, password, 4);
*txlen = 32;
} else {
if (bAuthenticating) {
bAuthenticating = false;
if (write) {
if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
return false;
}
break;
}
} else {
memcpy(tag.sectors[blocknr], rx, 4);
blocknr++;
}
if (blocknr > 7) {
DbpString("Read successful!");
bSuccessful = true;
return false;
}
tx[0] = HITAG2_READ_PAGE | (blocknr << 3) | ((blocknr^7) >> 2);
tx[1] = ((blocknr^7) << 6);
*txlen = 10;
}
}
break;
// Unexpected response
default: {
Dbprintf("Unknown frame length: %d", rxlen);
return false;
}
break;
}
}
return true;
}
static bool hitag2_crypto(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen, bool write) {
// Reset the transmission frame length
*txlen = 0;
if (bCrypto) {
hitag2_cipher_transcrypt(&cipher_state, rx, rxlen/8, rxlen%8);
}
if (bCrypto && !bAuthenticating && write) {
if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
return false;
}
} else {
// Try to find out which command was send by selecting on length (in bits)
switch (rxlen) {
// No answer, try to resurrect
case 0: {
// Stop if there is no answer while we are in crypto mode (after sending NrAr)
if (bCrypto) {
// Failed during authentication
if (bAuthenticating) {
DbpString("Authentication failed!");
return false;
} else {
// Failed reading a block, could be (read/write) locked, skip block and re-authenticate
if (blocknr == 1) {
// Write the low part of the key in memory
memcpy(tag.sectors[1], key+2, 4);
} else if (blocknr == 2) {
// Write the high part of the key in memory
tag.sectors[2][0] = 0x00;
tag.sectors[2][1] = 0x00;
tag.sectors[2][2] = key[0];
tag.sectors[2][3] = key[1];
} else {
// Just put zero's in the memory (of the unreadable block)
memset(tag.sectors[blocknr], 0x00, 4);
}
blocknr++;
bCrypto = false;
}
} else {
tx[0] = HITAG2_START_AUTH;
*txlen = 5;
}
break;
}
// Received UID, crypto tag answer
case 32: {
if (!bCrypto) {
uint64_t ui64key = key[0] | ((uint64_t)key[1]) << 8 | ((uint64_t)key[2]) << 16 | ((uint64_t)key[3]) << 24 | ((uint64_t)key[4]) << 32 | ((uint64_t)key[5]) << 40;
uint32_t ui32uid = rx[0] | ((uint32_t)rx[1]) << 8 | ((uint32_t)rx[2]) << 16 | ((uint32_t)rx[3]) << 24;
Dbprintf("hitag2_crypto: key=0x%x%x uid=0x%x", (uint32_t) ((REV64(ui64key)) >> 32), (uint32_t) ((REV64(ui64key)) & 0xffffffff), REV32(ui32uid));
cipher_state = _hitag2_init(REV64(ui64key), REV32(ui32uid), 0);
memset(tx, 0x00, 4);
memset(tx+4, 0xff, 4);
hitag2_cipher_transcrypt(&cipher_state, tx+4, 4, 0);
*txlen = 64;
bCrypto = true;
bAuthenticating = true;
} else {
// Check if we received answer tag (at)
if (bAuthenticating) {
bAuthenticating = false;
if (write) {
if (!hitag2_write_page(rx, rxlen, tx, txlen)) {
return false;
}
break;
}
}
// stage 2+, got data block
else {
// Store the received block
memcpy(tag.sectors[blocknr], rx, 4);
blocknr++;
}
if (blocknr > 7) {
DbpString("Read successful!");
bSuccessful = true;
return false;
} else {
tx[0] = HITAG2_READ_PAGE | (blocknr << 3) | ((blocknr ^ 7) >> 2);
tx[1] = ((blocknr ^ 7) << 6);
*txlen = 10;
}
}
}
break;
// Unexpected response
default: {
Dbprintf("Unknown frame length: %d",rxlen);
return false;
}
break;
}
}
if (bCrypto) {
// We have to return now to avoid double encryption
if (!bAuthenticating) {
hitag2_cipher_transcrypt(&cipher_state, tx, *txlen/8, *txlen%8);
}
}
return true;
}
static bool hitag2_authenticate(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
// Reset the transmission frame length
*txlen = 0;
// Try to find out which command was send by selecting on length (in bits)
switch (rxlen) {
// No answer, try to resurrect
case 0: {
// Stop if there is no answer while we are in crypto mode (after sending NrAr)
if (bCrypto) {
DbpString("Authentication failed!");
return false;
}
tx[0] = HITAG2_START_AUTH;
*txlen = 5;
}
break;
// Received UID, crypto tag answer
case 32: {
if (!bCrypto) {
memcpy(tx, NrAr, 8);
*txlen = 64;
bCrypto = true;
} else {
DbpString("Authentication successful!");
// We are done... for now
return false;
}
}
break;
// Unexpected response
default: {
Dbprintf("Unknown frame length: %d",rxlen);
return false;
}
break;
}
return true;
}
static bool hitag2_test_auth_attempts(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
// Reset the transmission frame length
*txlen = 0;
// Try to find out which command was send by selecting on length (in bits)
switch (rxlen) {
// No answer, try to resurrect
case 0: {
// Stop if there is no answer while we are in crypto mode (after sending NrAr)
if (bCrypto) {
Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed, removed entry!", NrAr[0], NrAr[1], NrAr[2], NrAr[3], NrAr[4], NrAr[5], NrAr[6], NrAr[7]);
// Removing failed entry from authentiations table
memcpy(auth_table+auth_table_pos, auth_table+auth_table_pos+8, 8);
auth_table_len -= 8;
// Return if we reached the end of the authentications table
bCrypto = false;
if (auth_table_pos == auth_table_len) {
return false;
}
// Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
memcpy(NrAr, auth_table+auth_table_pos, 8);
}
tx[0] = HITAG2_START_AUTH;
*txlen = 5;
}
break;
// Received UID, crypto tag answer, or read block response
case 32: {
if (!bCrypto) {
*txlen = 64;
memcpy(tx, NrAr, 8);
bCrypto = true;
} else {
Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x OK", NrAr[0], NrAr[1], NrAr[2], NrAr[3], NrAr[4], NrAr[5], NrAr[6], NrAr[7]);
bCrypto = false;
if ((auth_table_pos+8) == auth_table_len) {
return false;
}
auth_table_pos += 8;
memcpy(NrAr, auth_table+auth_table_pos, 8);
}
}
break;
default: {
Dbprintf("Unknown frame length: %d",rxlen);
return false;
}
break;
}
return true;
}
static bool hitag2_read_uid(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) {
// Reset the transmission frame length
*txlen = 0;
// Try to find out which command was send by selecting on length (in bits)
switch (rxlen) {
// No answer, try to resurrect
case 0: {
// Just starting or if there is no answer
tx[0] = HITAG2_START_AUTH;
*txlen = 5;
}
break;
// Received UID
case 32: {
// Check if we received answer tag (at)
if (bAuthenticating) {
bAuthenticating = false;
} else {
// Store the received block
memcpy(tag.sectors[blocknr], rx, 4);
blocknr++;
}
if (blocknr > 0) {
//DbpString("Read successful!");
bSuccessful = true;
return false;
}
}
break;
// Unexpected response
default: {
Dbprintf("Unknown frame length: %d",rxlen);
return false;
}
break;
}
return true;
}
void SnoopHitag(uint32_t type) {
// int frame_count;
int response;
int overflow;
bool rising_edge;
bool reader_frame;
int lastbit;
bool bSkip;
int tag_sof;
uint8_t rx[HITAG_FRAME_LEN] = {0};
size_t rxlen = 0;
FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
// Clean up trace and prepare it for storing frames
set_tracing(true);
clear_trace();
auth_table_len = 0;
auth_table_pos = 0;
BigBuf_free();
auth_table = (uint8_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
DbpString("Starting Hitag2 snoop");
LED_D_ON();
// Set up eavesdropping mode, frequency divisor which will drive the FPGA
// and analog mux selection.
FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE);
FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
// Configure output pin that is connected to the FPGA (for modulating)
AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
// Disable modulation, we are going to eavesdrop, not modulate ;)
LOW(GPIO_SSC_DOUT);
// Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames
AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
// Disable timer during configuration
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
// TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
// external trigger rising edge, load RA on rising edge of TIOA.
AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_BOTH | AT91C_TC_ABETRG | AT91C_TC_LDRA_BOTH;
// Enable and reset counter
AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
// Reset the received frame, frame count and timing info
// frame_count = 0;
response = 0;
overflow = 0;
reader_frame = false;
lastbit = 1;
bSkip = true;
tag_sof = 4;
while (!BUTTON_PRESS()) {
// Watchdog hit
WDT_HIT();
// Receive frame, watch for at most T0*EOF periods
while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) {
// Check if rising edge in modulation is detected
if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
// Retrieve the new timing values
int ra = (AT91C_BASE_TC1->TC_RA/T0);
// Find out if we are dealing with a rising or falling edge
rising_edge = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME) > 0;
// Shorter periods will only happen with reader frames
if (!reader_frame && rising_edge && ra < HITAG_T_TAG_CAPTURE_ONE_HALF) {
// Switch from tag to reader capture
LED_C_OFF();
reader_frame = true;
memset(rx, 0x00, sizeof(rx));
rxlen = 0;
}
// Only handle if reader frame and rising edge, or tag frame and falling edge
if (reader_frame != rising_edge) {
overflow += ra;
continue;
}
// Add the buffered timing values of earlier captured edges which were skipped
ra += overflow;
overflow = 0;
if (reader_frame) {
LED_B_ON();
// Capture reader frame
if (ra >= HITAG_T_STOP) {
if (rxlen != 0) {
//DbpString("wierd0?");
}
// Capture the T0 periods that have passed since last communication or field drop (reset)
response = (ra - HITAG_T_LOW);
} else if (ra >= HITAG_T_1_MIN) {
// '1' bit
rx[rxlen / 8] |= 1 << (7-(rxlen%8));
rxlen++;
} else if (ra >= HITAG_T_0_MIN) {
// '0' bit
rx[rxlen / 8] |= 0 << (7-(rxlen%8));
rxlen++;
} else {
// Ignore wierd value, is to small to mean anything
}
} else {
LED_C_ON();
// Capture tag frame (manchester decoding using only falling edges)
if (ra >= HITAG_T_EOF) {
if (rxlen != 0) {
//DbpString("wierd1?");
}
// Capture the T0 periods that have passed since last communication or field drop (reset)
// We always recieve a 'one' first, which has the falling edge after a half period |-_|
response = ra - HITAG_T_TAG_HALF_PERIOD;
} else if (ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) {
// Manchester coding example |-_|_-|-_| (101)
rx[rxlen / 8] |= 0 << (7-(rxlen%8));
rxlen++;
rx[rxlen / 8] |= 1 << (7-(rxlen%8));
rxlen++;
} else if (ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) {
// Manchester coding example |_-|...|_-|-_| (0...01)
rx[rxlen / 8] |= 0 << (7-(rxlen%8));
rxlen++;
// We have to skip this half period at start and add the 'one' the second time
if (!bSkip) {
rx[rxlen / 8] |= 1 << (7-(rxlen%8));
rxlen++;
}
lastbit = !lastbit;
bSkip = !bSkip;
} else if (ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) {
// Manchester coding example |_-|_-| (00) or |-_|-_| (11)
if (tag_sof) {
// Ignore bits that are transmitted during SOF
tag_sof--;
} else {
// bit is same as last bit
rx[rxlen / 8] |= lastbit << (7-(rxlen%8));
rxlen++;
}
} else {
// Ignore wierd value, is to small to mean anything
}
}
}
}
// Check if frame was captured
if (rxlen > 0) {
// frame_count++;
if (!LogTraceHitag(rx, rxlen, response, 0, reader_frame)) {
DbpString("Trace full");
break;
}
// Check if we recognize a valid authentication attempt
if (nbytes(rxlen) == 8) {
// Store the authentication attempt
if (auth_table_len < (AUTH_TABLE_LENGTH-8)) {
memcpy(auth_table+auth_table_len,rx,8);
auth_table_len += 8;
}
}
// Reset the received frame and response timing info
memset(rx, 0x00, sizeof(rx));
response = 0;
reader_frame = false;
lastbit = 1;
bSkip = true;
tag_sof = 4;
overflow = 0;
LED_B_OFF();
LED_C_OFF();
} else {
// Save the timer overflow, will be 0 when frame was received
overflow += (AT91C_BASE_TC1->TC_CV/T0);
}
// Reset the frame length
rxlen = 0;
// Reset the timer to restart while-loop that receives frames
AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG;
}