forked from Proxmark/proxmark3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iso14443a.c
2597 lines (2196 loc) · 87.1 KB
/
iso14443a.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
//-----------------------------------------------------------------------------
// Merlok - June 2011, 2012
// Gerhard de Koning Gans - May 2008
// Hagen Fritsch - June 2010
//
// 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.
//-----------------------------------------------------------------------------
// Routines to support ISO 14443 type A.
//-----------------------------------------------------------------------------
#include "iso14443a.h"
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "proxmark3.h"
#include "apps.h"
#include "util.h"
#include "usb_cdc.h"
#include "iso14443crc.h"
#include "crapto1/crapto1.h"
#include "mifareutil.h"
#include "mifaresniff.h"
#include "BigBuf.h"
#include "protocols.h"
#include "parity.h"
#include "fpgaloader.h"
typedef struct {
enum {
DEMOD_UNSYNCD,
// DEMOD_HALF_SYNCD,
// DEMOD_MOD_FIRST_HALF,
// DEMOD_NOMOD_FIRST_HALF,
DEMOD_MANCHESTER_DATA
} state;
uint16_t twoBits;
uint16_t highCnt;
uint16_t bitCount;
uint16_t collisionPos;
uint16_t syncBit;
uint8_t parityBits;
uint8_t parityLen;
uint16_t shiftReg;
uint16_t samples;
uint16_t len;
uint32_t startTime, endTime;
uint8_t *output;
uint8_t *parity;
} tDemod;
typedef enum {
MOD_NOMOD = 0,
MOD_SECOND_HALF,
MOD_FIRST_HALF,
MOD_BOTH_HALVES
} Modulation_t;
typedef struct {
enum {
STATE_UNSYNCD,
STATE_START_OF_COMMUNICATION,
STATE_MILLER_X,
STATE_MILLER_Y,
STATE_MILLER_Z,
// DROP_NONE,
// DROP_FIRST_HALF,
} state;
uint16_t shiftReg;
int16_t bitCount;
uint16_t len;
uint16_t byteCntMax;
uint16_t posCnt;
uint16_t syncBit;
uint8_t parityBits;
uint8_t parityLen;
uint32_t fourBits;
uint32_t startTime, endTime;
uint8_t *output;
uint8_t *parity;
} tUart;
static uint32_t iso14a_timeout;
#define MAX_ISO14A_TIMEOUT 524288
int rsamples = 0;
uint8_t trigger = 0;
// the block number for the ISO14443-4 PCB
static uint8_t iso14_pcb_blocknum = 0;
//
// ISO14443 timing:
//
// minimum time between the start bits of consecutive transfers from reader to tag: 7000 carrier (13.56Mhz) cycles
#define REQUEST_GUARD_TIME (7000/16 + 1)
// minimum time between last modulation of tag and next start bit from reader to tag: 1172 carrier cycles
#define FRAME_DELAY_TIME_PICC_TO_PCD (1172/16 + 1)
// bool LastCommandWasRequest = false;
//
// Total delays including SSC-Transfers between ARM and FPGA. These are in carrier clock cycles (1/13,56MHz)
//
// When the PM acts as reader and is receiving tag data, it takes
// 3 ticks delay in the AD converter
// 16 ticks until the modulation detector completes and sets curbit
// 8 ticks until bit_to_arm is assigned from curbit
// 8*16 ticks for the transfer from FPGA to ARM
// 4*16 ticks until we measure the time
// - 8*16 ticks because we measure the time of the previous transfer
#define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16)
// When the PM acts as a reader and is sending, it takes
// 4*16 ticks until we can write data to the sending hold register
// 8*16 ticks until the SHR is transferred to the Sending Shift Register
// 8 ticks until the first transfer starts
// 8 ticks later the FPGA samples the data
// 1 tick to assign mod_sig_coil
#define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1)
// When the PM acts as tag and is receiving it takes
// 2 ticks delay in the RF part (for the first falling edge),
// 3 ticks for the A/D conversion,
// 8 ticks on average until the start of the SSC transfer,
// 8 ticks until the SSC samples the first data
// 7*16 ticks to complete the transfer from FPGA to ARM
// 8 ticks until the next ssp_clk rising edge
// 4*16 ticks until we measure the time
// - 8*16 ticks because we measure the time of the previous transfer
#define DELAY_AIR2ARM_AS_TAG (2 + 3 + 8 + 8 + 7*16 + 8 + 4*16 - 8*16)
// The FPGA will report its internal sending delay in
uint16_t FpgaSendQueueDelay;
// the 5 first bits are the number of bits buffered in mod_sig_buf
// the last three bits are the remaining ticks/2 after the mod_sig_buf shift
#define DELAY_FPGA_QUEUE (FpgaSendQueueDelay<<1)
// When the PM acts as tag and is sending, it takes
// 4*16 + 8 ticks until we can write data to the sending hold register
// 8*16 ticks until the SHR is transferred to the Sending Shift Register
// 8 ticks later the FPGA samples the first data
// + 16 ticks until assigned to mod_sig
// + 1 tick to assign mod_sig_coil
// + a varying number of ticks in the FPGA Delay Queue (mod_sig_buf)
#define DELAY_ARM2AIR_AS_TAG (4*16 + 8 + 8*16 + 8 + 16 + 1 + DELAY_FPGA_QUEUE)
// When the PM acts as sniffer and is receiving tag data, it takes
// 3 ticks A/D conversion
// 14 ticks to complete the modulation detection
// 8 ticks (on average) until the result is stored in to_arm
// + the delays in transferring data - which is the same for
// sniffing reader and tag data and therefore not relevant
#define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8)
// When the PM acts as sniffer and is receiving reader data, it takes
// 2 ticks delay in analogue RF receiver (for the falling edge of the
// start bit, which marks the start of the communication)
// 3 ticks A/D conversion
// 8 ticks on average until the data is stored in to_arm.
// + the delays in transferring data - which is the same for
// sniffing reader and tag data and therefore not relevant
#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8)
//variables used for timing purposes:
//these are in ssp_clk cycles:
static uint32_t NextTransferTime;
static uint32_t LastTimeProxToAirStart;
static uint32_t LastProxToAirDuration;
// CARD TO READER - manchester
// Sequence D: 11110000 modulation with subcarrier during first half
// Sequence E: 00001111 modulation with subcarrier during second half
// Sequence F: 00000000 no modulation with subcarrier
// READER TO CARD - miller
// Sequence X: 00001100 drop after half a period
// Sequence Y: 00000000 no drop
// Sequence Z: 11000000 drop at start
#define SEC_D 0xf0
#define SEC_E 0x0f
#define SEC_F 0x00
#define SEC_X 0x0c
#define SEC_Y 0x00
#define SEC_Z 0xc0
void iso14a_set_trigger(bool enable) {
trigger = enable;
}
void iso14a_set_timeout(uint32_t timeout) {
// adjust timeout by FPGA delays and 2 additional ssp_frames to detect SOF
iso14a_timeout = timeout + (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER)/(16*8) + 2;
if (MF_DBGLEVEL >= 3) Dbprintf("ISO14443A Timeout set to %" PRIu32 " (%dms)", timeout, timeout / 106);
}
uint32_t iso14a_get_timeout(void) {
return iso14a_timeout - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER)/(16*8) - 2;
}
//-----------------------------------------------------------------------------
// Generate the parity value for a byte sequence
//
//-----------------------------------------------------------------------------
void GetParity(const uint8_t *pbtCmd, uint16_t iLen, uint8_t *par)
{
uint16_t paritybit_cnt = 0;
uint16_t paritybyte_cnt = 0;
uint8_t parityBits = 0;
for (uint16_t i = 0; i < iLen; i++) {
// Generate the parity bits
parityBits |= ((oddparity8(pbtCmd[i])) << (7-paritybit_cnt));
if (paritybit_cnt == 7) {
par[paritybyte_cnt] = parityBits; // save 8 Bits parity
parityBits = 0; // and advance to next Parity Byte
paritybyte_cnt++;
paritybit_cnt = 0;
} else {
paritybit_cnt++;
}
}
// save remaining parity bits
par[paritybyte_cnt] = parityBits;
}
void AppendCrc14443a(uint8_t* data, int len)
{
ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
}
static void AppendCrc14443b(uint8_t* data, int len)
{
ComputeCrc14443(CRC_14443_B,data,len,data+len,data+len+1);
}
//=============================================================================
// ISO 14443 Type A - Miller decoder
//=============================================================================
// Basics:
// This decoder is used when the PM3 acts as a tag.
// The reader will generate "pauses" by temporarily switching of the field.
// At the PM3 antenna we will therefore measure a modulated antenna voltage.
// The FPGA does a comparison with a threshold and would deliver e.g.:
// ........ 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 .......
// The Miller decoder needs to identify the following sequences:
// 2 (or 3) ticks pause followed by 6 (or 5) ticks unmodulated: pause at beginning - Sequence Z ("start of communication" or a "0")
// 8 ticks without a modulation: no pause - Sequence Y (a "0" or "end of communication" or "no information")
// 4 ticks unmodulated followed by 2 (or 3) ticks pause: pause in second half - Sequence X (a "1")
// Note 1: the bitstream may start at any time. We therefore need to sync.
// Note 2: the interpretation of Sequence Y and Z depends on the preceding sequence.
//-----------------------------------------------------------------------------
static tUart Uart;
// Lookup-Table to decide if 4 raw bits are a modulation.
// We accept the following:
// 0001 - a 3 tick wide pause
// 0011 - a 2 tick wide pause, or a three tick wide pause shifted left
// 0111 - a 2 tick wide pause shifted left
// 1001 - a 2 tick wide pause shifted right
const bool Mod_Miller_LUT[] = {
false, true, false, true, false, false, false, true,
false, true, false, false, false, false, false, false
};
#define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4])
#define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)])
static void UartReset() {
Uart.state = STATE_UNSYNCD;
Uart.bitCount = 0;
Uart.len = 0; // number of decoded data bytes
Uart.parityLen = 0; // number of decoded parity bytes
Uart.shiftReg = 0; // shiftreg to hold decoded data bits
Uart.parityBits = 0; // holds 8 parity bits
}
static void UartInit(uint8_t *data, uint8_t *parity) {
Uart.output = data;
Uart.parity = parity;
Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits
Uart.startTime = 0;
Uart.endTime = 0;
UartReset();
}
// use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) {
Uart.fourBits = (Uart.fourBits << 8) | bit;
if (Uart.state == STATE_UNSYNCD) { // not yet synced
Uart.syncBit = 9999; // not set
// The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from
// Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111)
// we therefore look for a ...xx11111111111100x11111xxxxxx... pattern
// (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's)
#define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00000111 11111111 11101111 10000000
#define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00000111 11111111 10001111 10000000
if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 0)) == ISO14443A_STARTBIT_PATTERN >> 0) Uart.syncBit = 7;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 1)) == ISO14443A_STARTBIT_PATTERN >> 1) Uart.syncBit = 6;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 2)) == ISO14443A_STARTBIT_PATTERN >> 2) Uart.syncBit = 5;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 3)) == ISO14443A_STARTBIT_PATTERN >> 3) Uart.syncBit = 4;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 4)) == ISO14443A_STARTBIT_PATTERN >> 4) Uart.syncBit = 3;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 5)) == ISO14443A_STARTBIT_PATTERN >> 5) Uart.syncBit = 2;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 6)) == ISO14443A_STARTBIT_PATTERN >> 6) Uart.syncBit = 1;
else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 7)) == ISO14443A_STARTBIT_PATTERN >> 7) Uart.syncBit = 0;
if (Uart.syncBit != 9999) { // found a sync bit
Uart.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8);
Uart.startTime -= Uart.syncBit;
Uart.endTime = Uart.startTime;
Uart.state = STATE_START_OF_COMMUNICATION;
LED_B_ON();
}
} else {
if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) {
if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation in both halves - error
LED_B_OFF();
UartReset();
} else { // Modulation in first half = Sequence Z = logic "0"
if (Uart.state == STATE_MILLER_X) { // error - must not follow after X
LED_B_OFF();
UartReset();
} else {
Uart.bitCount++;
Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg
Uart.state = STATE_MILLER_Z;
Uart.endTime = Uart.startTime + 8*(9*Uart.len + Uart.bitCount + 1) - 6;
if(Uart.bitCount >= 9) { // if we decoded a full byte (including parity)
Uart.output[Uart.len++] = (Uart.shiftReg & 0xff);
Uart.parityBits <<= 1; // make room for the parity bit
Uart.parityBits |= ((Uart.shiftReg >> 8) & 0x01); // store parity bit
Uart.bitCount = 0;
Uart.shiftReg = 0;
if((Uart.len&0x0007) == 0) { // every 8 data bytes
Uart.parity[Uart.parityLen++] = Uart.parityBits; // store 8 parity bits
Uart.parityBits = 0;
}
}
}
}
} else {
if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation second half = Sequence X = logic "1"
Uart.bitCount++;
Uart.shiftReg = (Uart.shiftReg >> 1) | 0x100; // add a 1 to the shiftreg
Uart.state = STATE_MILLER_X;
Uart.endTime = Uart.startTime + 8*(9*Uart.len + Uart.bitCount + 1) - 2;
if(Uart.bitCount >= 9) { // if we decoded a full byte (including parity)
Uart.output[Uart.len++] = (Uart.shiftReg & 0xff);
Uart.parityBits <<= 1; // make room for the new parity bit
Uart.parityBits |= ((Uart.shiftReg >> 8) & 0x01); // store parity bit
Uart.bitCount = 0;
Uart.shiftReg = 0;
if ((Uart.len&0x0007) == 0) { // every 8 data bytes
Uart.parity[Uart.parityLen++] = Uart.parityBits; // store 8 parity bits
Uart.parityBits = 0;
}
}
} else { // no modulation in both halves - Sequence Y
if (Uart.state == STATE_MILLER_Z || Uart.state == STATE_MILLER_Y) { // Y after logic "0" - End of Communication
LED_B_OFF();
Uart.state = STATE_UNSYNCD;
Uart.bitCount--; // last "0" was part of EOC sequence
Uart.shiftReg <<= 1; // drop it
if(Uart.bitCount > 0) { // if we decoded some bits
Uart.shiftReg >>= (9 - Uart.bitCount); // right align them
Uart.output[Uart.len++] = (Uart.shiftReg & 0xff); // add last byte to the output
Uart.parityBits <<= 1; // add a (void) parity bit
Uart.parityBits <<= (8 - (Uart.len&0x0007)); // left align parity bits
Uart.parity[Uart.parityLen++] = Uart.parityBits; // and store it
return true;
} else if (Uart.len & 0x0007) { // there are some parity bits to store
Uart.parityBits <<= (8 - (Uart.len&0x0007)); // left align remaining parity bits
Uart.parity[Uart.parityLen++] = Uart.parityBits; // and store them
}
if (Uart.len) {
return true; // we are finished with decoding the raw data sequence
} else {
UartReset(); // Nothing received - start over
}
}
if (Uart.state == STATE_START_OF_COMMUNICATION) { // error - must not follow directly after SOC
LED_B_OFF();
UartReset();
} else { // a logic "0"
Uart.bitCount++;
Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg
Uart.state = STATE_MILLER_Y;
if(Uart.bitCount >= 9) { // if we decoded a full byte (including parity)
Uart.output[Uart.len++] = (Uart.shiftReg & 0xff);
Uart.parityBits <<= 1; // make room for the parity bit
Uart.parityBits |= ((Uart.shiftReg >> 8) & 0x01); // store parity bit
Uart.bitCount = 0;
Uart.shiftReg = 0;
if ((Uart.len&0x0007) == 0) { // every 8 data bytes
Uart.parity[Uart.parityLen++] = Uart.parityBits; // store 8 parity bits
Uart.parityBits = 0;
}
}
}
}
}
}
return false; // not finished yet, need more data
}
//=============================================================================
// ISO 14443 Type A - Manchester decoder
//=============================================================================
// Basics:
// This decoder is used when the PM3 acts as a reader.
// The tag will modulate the reader field by asserting different loads to it. As a consequence, the voltage
// at the reader antenna will be modulated as well. The FPGA detects the modulation for us and would deliver e.g. the following:
// ........ 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .......
// The Manchester decoder needs to identify the following sequences:
// 4 ticks modulated followed by 4 ticks unmodulated: Sequence D = 1 (also used as "start of communication")
// 4 ticks unmodulated followed by 4 ticks modulated: Sequence E = 0
// 8 ticks unmodulated: Sequence F = end of communication
// 8 ticks modulated: A collision. Save the collision position and treat as Sequence D
// Note 1: the bitstream may start at any time. We therefore need to sync.
// Note 2: parameter offset is used to determine the position of the parity bits (required for the anticollision command only)
static tDemod Demod;
// Lookup-Table to decide if 4 raw bits are a modulation.
// We accept three or four "1" in any position
const bool Mod_Manchester_LUT[] = {
false, false, false, false, false, false, false, true,
false, false, false, true, false, true, true, true
};
#define IsManchesterModulationNibble1(b) (Mod_Manchester_LUT[(b & 0x00F0) >> 4])
#define IsManchesterModulationNibble2(b) (Mod_Manchester_LUT[(b & 0x000F)])
static void DemodReset() {
Demod.state = DEMOD_UNSYNCD;
Demod.len = 0; // number of decoded data bytes
Demod.parityLen = 0;
Demod.shiftReg = 0; // shiftreg to hold decoded data bits
Demod.parityBits = 0; //
Demod.collisionPos = 0; // Position of collision bit
Demod.twoBits = 0xffff; // buffer for 2 Bits
Demod.highCnt = 0;
Demod.startTime = 0;
Demod.endTime = 0;
}
static void DemodInit(uint8_t *data, uint8_t *parity) {
Demod.output = data;
Demod.parity = parity;
DemodReset();
}
// use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
static RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time) {
Demod.twoBits = (Demod.twoBits << 8) | bit;
if (Demod.state == DEMOD_UNSYNCD) {
if (Demod.highCnt < 2) { // wait for a stable unmodulated signal
if (Demod.twoBits == 0x0000) {
Demod.highCnt++;
} else {
Demod.highCnt = 0;
}
} else {
Demod.syncBit = 0xFFFF; // not set
if ((Demod.twoBits & 0x7700) == 0x7000) Demod.syncBit = 7;
else if ((Demod.twoBits & 0x3B80) == 0x3800) Demod.syncBit = 6;
else if ((Demod.twoBits & 0x1DC0) == 0x1C00) Demod.syncBit = 5;
else if ((Demod.twoBits & 0x0EE0) == 0x0E00) Demod.syncBit = 4;
else if ((Demod.twoBits & 0x0770) == 0x0700) Demod.syncBit = 3;
else if ((Demod.twoBits & 0x03B8) == 0x0380) Demod.syncBit = 2;
else if ((Demod.twoBits & 0x01DC) == 0x01C0) Demod.syncBit = 1;
else if ((Demod.twoBits & 0x00EE) == 0x00E0) Demod.syncBit = 0;
if (Demod.syncBit != 0xFFFF) {
Demod.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8);
Demod.startTime -= Demod.syncBit;
Demod.bitCount = offset; // number of decoded data bits
Demod.state = DEMOD_MANCHESTER_DATA;
LED_C_ON();
}
}
} else {
if (IsManchesterModulationNibble1(Demod.twoBits >> Demod.syncBit)) { // modulation in first half
if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // ... and in second half = collision
if (!Demod.collisionPos) {
Demod.collisionPos = (Demod.len << 3) + Demod.bitCount;
}
} // modulation in first half only - Sequence D = 1
Demod.bitCount++;
Demod.shiftReg = (Demod.shiftReg >> 1) | 0x100; // in both cases, add a 1 to the shiftreg
if(Demod.bitCount == 9) { // if we decoded a full byte (including parity)
Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
Demod.parityBits <<= 1; // make room for the parity bit
Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
Demod.bitCount = 0;
Demod.shiftReg = 0;
if((Demod.len&0x0007) == 0) { // every 8 data bytes
Demod.parity[Demod.parityLen++] = Demod.parityBits; // store 8 parity bits
Demod.parityBits = 0;
}
}
Demod.endTime = Demod.startTime + 8*(9*Demod.len + Demod.bitCount + 1) - 4;
} else { // no modulation in first half
if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // and modulation in second half = Sequence E = 0
Demod.bitCount++;
Demod.shiftReg = (Demod.shiftReg >> 1); // add a 0 to the shiftreg
if(Demod.bitCount >= 9) { // if we decoded a full byte (including parity)
Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
Demod.parityBits <<= 1; // make room for the new parity bit
Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
Demod.bitCount = 0;
Demod.shiftReg = 0;
if ((Demod.len&0x0007) == 0) { // every 8 data bytes
Demod.parity[Demod.parityLen++] = Demod.parityBits; // store 8 parity bits1
Demod.parityBits = 0;
}
}
Demod.endTime = Demod.startTime + 8*(9*Demod.len + Demod.bitCount + 1);
} else { // no modulation in both halves - End of communication
LED_C_OFF();
if(Demod.bitCount > 0) { // there are some remaining data bits
Demod.shiftReg >>= (9 - Demod.bitCount); // right align the decoded bits
Demod.output[Demod.len++] = Demod.shiftReg & 0xff; // and add them to the output
Demod.parityBits <<= 1; // add a (void) parity bit
Demod.parityBits <<= (8 - (Demod.len&0x0007)); // left align remaining parity bits
Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them
return true;
} else if (Demod.len & 0x0007) { // there are some parity bits to store
Demod.parityBits <<= (8 - (Demod.len&0x0007)); // left align remaining parity bits
Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them
}
if (Demod.len) {
return true; // we are finished with decoding the raw data sequence
} else { // nothing received. Start over
DemodReset();
}
}
}
}
return false; // not finished yet, need more data
}
//=============================================================================
// Finally, a `sniffer' for ISO 14443 Type A
// Both sides of communication!
//=============================================================================
//-----------------------------------------------------------------------------
// Record the sequence of commands sent by the reader to the tag, with
// triggering so that we start recording at the point that the tag is moved
// near the reader.
//-----------------------------------------------------------------------------
void RAMFUNC SnoopIso14443a(uint8_t param) {
// param:
// bit 0 - trigger from first card answer
// bit 1 - trigger from first reader 7-bit request
LEDsoff();
LED_A_ON();
iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER);
// Allocate memory from BigBuf for some buffers
// free all previous allocations first
BigBuf_free();
// The command (reader -> tag) that we're receiving.
uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
uint8_t *receivedCmdPar = BigBuf_malloc(MAX_PARITY_SIZE);
// The response (tag -> reader) that we're receiving.
uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE);
uint8_t *receivedResponsePar = BigBuf_malloc(MAX_PARITY_SIZE);
// The DMA buffer, used to stream samples from the FPGA
uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
// init trace buffer
clear_trace();
set_tracing(true);
uint8_t *data = dmaBuf;
uint8_t previous_data = 0;
int maxDataLen = 0;
int dataLen = 0;
bool TagIsActive = false;
bool ReaderIsActive = false;
// Set up the demodulator for tag -> reader responses.
DemodInit(receivedResponse, receivedResponsePar);
// Set up the demodulator for the reader -> tag commands
UartInit(receivedCmd, receivedCmdPar);
// Setup and start DMA.
FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
// We won't start recording the frames that we acquire until we trigger;
// a good trigger condition to get started is probably when we see a
// response from the tag.
// triggered == false -- to wait first for card
bool triggered = !(param & 0x03);
// And now we loop, receiving samples.
for (uint32_t rsamples = 0; true; ) {
if (BUTTON_PRESS()) {
DbpString("cancelled by button");
break;
}
WDT_HIT();
int register readBufDataP = data - dmaBuf;
int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
if (readBufDataP <= dmaBufDataP){
dataLen = dmaBufDataP - readBufDataP;
} else {
dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP;
}
// test for length of buffer
if(dataLen > maxDataLen) {
maxDataLen = dataLen;
if(dataLen > (9 * DMA_BUFFER_SIZE / 10)) {
Dbprintf("blew circular buffer! dataLen=%d", dataLen);
break;
}
}
if(dataLen < 1) continue;
// primary buffer was stopped( <-- we lost data!
if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen); // temporary
}
// secondary buffer sets as primary, secondary buffer was stopped
if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
}
if (rsamples & 0x01) { // Need two samples to feed Miller and Manchester-Decoder
if(!TagIsActive) { // no need to try decoding reader data if the tag is sending
uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
if (MillerDecoding(readerdata, (rsamples-1)*4)) {
// check - if there is a short 7bit request from reader
if ((!triggered) && (param & 0x02) && (Uart.len == 1) && (Uart.bitCount == 7)) {
triggered = true;
}
if(triggered) {
if (!LogTrace(receivedCmd,
Uart.len,
Uart.startTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER,
Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER,
Uart.parity,
true)) break;
}
/* And ready to receive another command. */
UartReset();
/* And also reset the demod code, which might have been */
/* false-triggered by the commands from the reader. */
DemodReset();
}
ReaderIsActive = (Uart.state != STATE_UNSYNCD);
}
if (!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time
uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
if (ManchesterDecoding(tagdata, 0, (rsamples-1)*4)) {
if (!LogTrace(receivedResponse,
Demod.len,
Demod.startTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER,
Demod.endTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER,
Demod.parity,
false)) break;
if ((!triggered) && (param & 0x01)) triggered = true;
// And ready to receive another response.
DemodReset();
// And reset the Miller decoder including itS (now outdated) input buffer
UartInit(receivedCmd, receivedCmdPar);
}
TagIsActive = (Demod.state != DEMOD_UNSYNCD);
}
}
previous_data = *data;
rsamples++;
data++;
if(data == dmaBuf + DMA_BUFFER_SIZE) {
data = dmaBuf;
}
} // main cycle
FpgaDisableSscDma();
LEDsoff();
DbpString("COMMAND FINISHED");
Dbprintf("maxDataLen=%d, Uart.state=%x, Uart.len=%d", maxDataLen, Uart.state, Uart.len);
Dbprintf("traceLen=%d, Uart.output[0]=%08x", BigBuf_get_traceLen(), (uint32_t)Uart.output[0]);
}
//-----------------------------------------------------------------------------
// Prepare tag messages
//-----------------------------------------------------------------------------
static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *parity) {
ToSendReset();
// Correction bit, might be removed when not needed
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(1); // 1
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(0);
// Send startbit
ToSend[++ToSendMax] = SEC_D;
LastProxToAirDuration = 8 * ToSendMax - 4;
for (uint16_t i = 0; i < len; i++) {
uint8_t b = cmd[i];
// Data bits
for (uint16_t j = 0; j < 8; j++) {
if(b & 1) {
ToSend[++ToSendMax] = SEC_D;
} else {
ToSend[++ToSendMax] = SEC_E;
}
b >>= 1;
}
// Get the parity bit
if (parity[i>>3] & (0x80>>(i&0x0007))) {
ToSend[++ToSendMax] = SEC_D;
LastProxToAirDuration = 8 * ToSendMax - 4;
} else {
ToSend[++ToSendMax] = SEC_E;
LastProxToAirDuration = 8 * ToSendMax;
}
}
// Send stopbit
ToSend[++ToSendMax] = SEC_F;
// Convert from last byte pos to length
ToSendMax++;
}
static void Code4bitAnswerAsTag(uint8_t cmd) {
int i;
ToSendReset();
// Correction bit, might be removed when not needed
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(1); // 1
ToSendStuffBit(0);
ToSendStuffBit(0);
ToSendStuffBit(0);
// Send startbit
ToSend[++ToSendMax] = SEC_D;
uint8_t b = cmd;
for (i = 0; i < 4; i++) {
if(b & 1) {
ToSend[++ToSendMax] = SEC_D;
LastProxToAirDuration = 8 * ToSendMax - 4;
} else {
ToSend[++ToSendMax] = SEC_E;
LastProxToAirDuration = 8 * ToSendMax;
}
b >>= 1;
}
// Send stopbit
ToSend[++ToSendMax] = SEC_F;
// Convert from last byte pos to length
ToSendMax++;
}
static uint8_t *LastReaderTraceTime = NULL;
static void EmLogTraceReader(void) {
// remember last reader trace start to fix timing info later
LastReaderTraceTime = BigBuf_get_addr() + BigBuf_get_traceLen();
LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
}
static void FixLastReaderTraceTime(uint32_t tag_StartTime) {
uint32_t reader_EndTime = Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG;
uint32_t reader_StartTime = Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG;
uint16_t reader_modlen = reader_EndTime - reader_StartTime;
uint16_t approx_fdt = tag_StartTime - reader_EndTime;
uint16_t exact_fdt = (approx_fdt - 20 + 32)/64 * 64 + 20;
reader_StartTime = tag_StartTime - exact_fdt - reader_modlen;
LastReaderTraceTime[0] = (reader_StartTime >> 0) & 0xff;
LastReaderTraceTime[1] = (reader_StartTime >> 8) & 0xff;
LastReaderTraceTime[2] = (reader_StartTime >> 16) & 0xff;
LastReaderTraceTime[3] = (reader_StartTime >> 24) & 0xff;
}
static void EmLogTraceTag(uint8_t *tag_data, uint16_t tag_len, uint8_t *tag_Parity, uint32_t ProxToAirDuration) {
uint32_t tag_StartTime = LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG;
uint32_t tag_EndTime = (LastTimeProxToAirStart + ProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG;
LogTrace(tag_data, tag_len, tag_StartTime, tag_EndTime, tag_Parity, false);
FixLastReaderTraceTime(tag_StartTime);
}
//-----------------------------------------------------------------------------
// Wait for commands from reader
// Stop when button is pressed
// Or return true when command is captured
//-----------------------------------------------------------------------------
static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len) {
// Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
// only, since we are receiving, not transmitting).
// Signal field is off with the appropriate LED
LED_D_OFF();
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
// Now run a `software UART' on the stream of incoming samples.
UartInit(received, parity);
// clear RXRDY:
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
for (;;) {
WDT_HIT();
if(BUTTON_PRESS()) return false;
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if(MillerDecoding(b, 0)) {
*len = Uart.len;
EmLogTraceReader();
return true;
}
}
}
}
int EmSend4bit(uint8_t resp);
static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
int EmSendCmd(uint8_t *resp, uint16_t respLen);
int EmSendPrecompiledCmd(tag_response_info_t *response_info);
static bool prepare_tag_modulation(tag_response_info_t* response_info, size_t max_buffer_size) {
// Example response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
// This will need the following byte array for a modulation sequence
// 144 data bits (18 * 8)
// 18 parity bits
// 2 Start and stop
// 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
// 1 just for the case
// ----------- +
// 166 bytes, since every bit that needs to be send costs us a byte
//
// Prepare the tag modulation bits from the message
GetParity(response_info->response, response_info->response_n, &(response_info->par));
CodeIso14443aAsTagPar(response_info->response,response_info->response_n, &(response_info->par));
// Make sure we do not exceed the free buffer space
if (ToSendMax > max_buffer_size) {
Dbprintf("Out of memory, when modulating bits for tag answer:");
Dbhexdump(response_info->response_n, response_info->response, false);
return false;
}
// Copy the byte array, used for this modulation to the buffer position
memcpy(response_info->modulation, ToSend, ToSendMax);
// Store the number of bytes that were used for encoding/modulation and the time needed to transfer them
response_info->modulation_n = ToSendMax;
response_info->ProxToAirDuration = LastProxToAirDuration;
return true;
}
// "precompile" responses. There are 7 predefined responses with a total of 28 bytes data to transmit.
// Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
// 28 * 8 data bits, 28 * 1 parity bits, 7 start bits, 7 stop bits, 7 correction bits for the modulation
// -> need 273 bytes buffer
#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 273
bool prepare_allocated_tag_modulation(tag_response_info_t* response_info, uint8_t **buffer, size_t *max_buffer_size) {
// Retrieve and store the current buffer index
response_info->modulation = *buffer;
// Forward the prepare tag modulation function to the inner function
if (prepare_tag_modulation(response_info, *max_buffer_size)) {
// Update the free buffer offset and the remaining buffer size
*buffer += ToSendMax;
*max_buffer_size -= ToSendMax;
return true;
} else {
return false;
}
}
//-----------------------------------------------------------------------------
// Main loop of simulated tag: receive commands from reader, decide what
// response to send, and send it.
//-----------------------------------------------------------------------------
void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, uint8_t* data) {
uint8_t sak;
// The first response contains the ATQA (note: bytes are transmitted in reverse order).
uint8_t response1[2];
switch (tagType) {
case 1: { // MIFARE Classic
// Says: I am Mifare 1k - original line
response1[0] = 0x04;
response1[1] = 0x00;
sak = 0x08;
} break;
case 2: { // MIFARE Ultralight
// Says: I am a stupid memory tag, no crypto
response1[0] = 0x04;
response1[1] = 0x00;
sak = 0x00;
} break;
case 3: { // MIFARE DESFire
// Says: I am a DESFire tag, ph33r me
response1[0] = 0x04;
response1[1] = 0x03;
sak = 0x20;
} break;
case 4: { // ISO/IEC 14443-4
// Says: I am a javacard (JCOP)
response1[0] = 0x04;
response1[1] = 0x00;
sak = 0x28;
} break;
case 5: { // MIFARE TNP3XXX
// Says: I am a toy
response1[0] = 0x01;
response1[1] = 0x0f;
sak = 0x01;
} break;
default: {
Dbprintf("Error: unkown tagtype (%d)",tagType);
return;
} break;
}
// The second response contains the (mandatory) first 24 bits of the UID
uint8_t response2[5] = {0x00};
// Check if the uid uses the (optional) part
uint8_t response2a[5] = {0x00};
if (uid_2nd) {
response2[0] = 0x88;
num_to_bytes(uid_1st,3,response2+1);
num_to_bytes(uid_2nd,4,response2a);