-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
iso14443a.c
3715 lines (3184 loc) · 149 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
//-----------------------------------------------------------------------------
// Copyright (C) Jonathan Westhues, Nov 2006
// Copyright (C) Gerhard de Koning Gans - May 2008
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// Routines to support ISO 14443 type A.
//-----------------------------------------------------------------------------
#include "iso14443a.h"
#include "string.h"
#include "proxmark3_arm.h"
#include "cmd.h"
#include "appmain.h"
#include "BigBuf.h"
#include "fpgaloader.h"
#include "ticks.h"
#include "dbprint.h"
#include "util.h"
#include "util.h"
#include "parity.h"
#include "mifareutil.h"
#include "commonutil.h"
#include "crc16.h"
#include "protocols.h"
#include "generator.h"
#define MAX_ISO14A_TIMEOUT 524288
// this timeout is in MS
static uint32_t iso14a_timeout;
static uint8_t colpos = 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)
// The FPGA will report its internal sending delay in
static 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
// Sequence COLL: 11111111 load modulation over the full bitlength.
// Tricks the reader to think that multiple cards answer.
// (at least one card with 1 and at least one card with 0)
// 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_COLL 0xff
#define SEC_X 0x0c
#define SEC_Y 0x00
#define SEC_Z 0xc0
/*
Default HF 14a config is set to:
forceanticol = 0 (auto)
forcebcc = 0 (expect valid BCC)
forcecl2 = 0 (auto)
forcecl3 = 0 (auto)
forcerats = 0 (auto)
*/
static hf14a_config hf14aconfig = { 0, 0, 0, 0, 0 } ;
// Polling frames and configurations
static iso14a_polling_parameters_t WUPA_POLLING_PARAMETERS = {
.frames = { {{ 0x52 }, 1, 7, 0} },
.frame_count = 1,
.extra_timeout = 0,
};
void printHf14aConfig(void) {
DbpString(_CYAN_("HF 14a config"));
Dbprintf(" [a] Anticol override.... %s%s%s",
(hf14aconfig.forceanticol == 0) ? _GREEN_("std") " ( follow standard )" : "",
(hf14aconfig.forceanticol == 1) ? _RED_("force") " ( always do anticol )" : "",
(hf14aconfig.forceanticol == 2) ? _RED_("skip") " ( always skip anticol )" : ""
);
Dbprintf(" [b] BCC override........ %s%s%s",
(hf14aconfig.forcebcc == 0) ? _GREEN_("std") " ( follow standard )" : "",
(hf14aconfig.forcebcc == 1) ? _RED_("fix") " ( fix bad BCC )" : "",
(hf14aconfig.forcebcc == 2) ? _RED_("ignore") " ( ignore bad BCC, always use card BCC )" : ""
);
Dbprintf(" [2] CL2 override........ %s%s%s",
(hf14aconfig.forcecl2 == 0) ? _GREEN_("std") " ( follow standard )" : "",
(hf14aconfig.forcecl2 == 1) ? _RED_("force") " ( always do CL2 )" : "",
(hf14aconfig.forcecl2 == 2) ? _RED_("skip") " ( always skip CL2 )" : ""
);
Dbprintf(" [3] CL3 override........ %s%s%s",
(hf14aconfig.forcecl3 == 0) ? _GREEN_("std") " ( follow standard )" : "",
(hf14aconfig.forcecl3 == 1) ? _RED_("force") " ( always do CL3 )" : "",
(hf14aconfig.forcecl3 == 2) ? _RED_("skip") " ( always skip CL3 )" : ""
);
Dbprintf(" [r] RATS override....... %s%s%s",
(hf14aconfig.forcerats == 0) ? _GREEN_("std") " ( follow standard )" : "",
(hf14aconfig.forcerats == 1) ? _RED_("force") " ( always do RATS )" : "",
(hf14aconfig.forcerats == 2) ? _RED_("skip") " ( always skip RATS )" : ""
);
}
/**
* Called from the USB-handler to set the 14a configuration
* The 14a config is used for card selection sequence.
*
* Values set to '-1' implies no change
* @brief setSamplingConfig
* @param sc
*/
void setHf14aConfig(const hf14a_config *hc) {
if ((hc->forceanticol >= 0) && (hc->forceanticol <= 2))
hf14aconfig.forceanticol = hc->forceanticol;
if ((hc->forcebcc >= 0) && (hc->forcebcc <= 2))
hf14aconfig.forcebcc = hc->forcebcc;
if ((hc->forcecl2 >= 0) && (hc->forcecl2 <= 2))
hf14aconfig.forcecl2 = hc->forcecl2;
if ((hc->forcecl3 >= 0) && (hc->forcecl3 <= 2))
hf14aconfig.forcecl3 = hc->forcecl3;
if ((hc->forcerats >= 0) && (hc->forcerats <= 2))
hf14aconfig.forcerats = hc->forcerats;
}
hf14a_config *getHf14aConfig(void) {
return &hf14aconfig;
}
void iso14a_set_trigger(bool enable) {
g_trigger = enable;
}
void iso14a_set_timeout(uint32_t timeout) {
iso14a_timeout = timeout + (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER) / 128 + 2;
}
uint32_t iso14a_get_timeout(void) {
return iso14a_timeout - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER) / 128 - 2;
}
//-----------------------------------------------------------------------------
// Generate the parity value for a byte sequence
//-----------------------------------------------------------------------------
void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *par) {
uint16_t paritybit_cnt = 0;
uint16_t paritybyte_cnt = 0;
uint8_t parityBits = 0;
for (uint16_t i = 0; i < len; 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;
}
//=============================================================================
// 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 tUart14a 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
static 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)])
tUart14a *GetUart14a(void) {
return &Uart;
}
void Uart14aReset(void) {
Uart.state = STATE_14A_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
Uart.startTime = 0;
Uart.endTime = 0;
Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits
Uart.posCnt = 0;
Uart.syncBit = 9999;
}
void Uart14aInit(uint8_t *data, uint8_t *par) {
Uart.output = data;
Uart.parity = par;
Uart14aReset();
}
// use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) {
Uart.fourBits = (Uart.fourBits << 8) | bit;
if (Uart.state == STATE_14A_UNSYNCD) { // not yet synced
Uart.syncBit = 9999; // not set
// 00x11111 2|3 ticks pause followed by 6|5 ticks unmodulated Sequence Z (a "0" or "start of communication")
// 11111111 8 ticks unmodulation Sequence Y (a "0" or "end of communication" or "no information")
// 111100x1 4 ticks unmodulated followed by 2|3 ticks pause Sequence X (a "1")
// 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 ...xx1111 11111111 00x11111xxxxxx... 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_14A_START_OF_COMMUNICATION;
}
} else {
if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) {
if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation in both halves - error
Uart14aReset();
} else { // Modulation in first half = Sequence Z = logic "0"
if (Uart.state == STATE_14A_MILLER_X) { // error - must not follow after X
Uart14aReset();
} else {
Uart.bitCount++;
Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg
Uart.state = STATE_14A_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_14A_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_14A_MILLER_Z || Uart.state == STATE_14A_MILLER_Y) { // Y after logic "0" - End of Communication
Uart.state = STATE_14A_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 {
Uart14aReset(); // Nothing received - start over
return false;
}
}
if (Uart.state == STATE_14A_START_OF_COMMUNICATION) { // error - must not follow directly after SOC
Uart14aReset();
} else { // a logic "0"
Uart.bitCount++;
Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg
Uart.state = STATE_14A_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 tDemod14a Demod;
// Lookup-Table to decide if 4 raw bits are a modulation.
// We accept three or four "1" in any position
static 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)])
tDemod14a *GetDemod14a(void) {
return &Demod;
}
void Demod14aReset(void) {
Demod.state = DEMOD_14A_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;
Demod.bitCount = 0;
Demod.syncBit = 0xFFFF;
Demod.samples = 0;
}
void Demod14aInit(uint8_t *data, uint8_t *par) {
Demod.output = data;
Demod.parity = par;
Demod14aReset();
}
// use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time) {
Demod.twoBits = (Demod.twoBits << 8) | bit;
if (Demod.state == DEMOD_14A_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_14A_MANCHESTER_DATA;
}
}
} 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
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
Demod14aReset();
}
}
}
}
return false; // not finished yet, need more data
}
// Thinfilm, Kovio mangles ISO14443A in the way that they don't use start bit nor parity bits.
static RAMFUNC int ManchesterDecoding_Thinfilm(uint8_t bit) {
Demod.twoBits = (Demod.twoBits << 8) | bit;
if (Demod.state == DEMOD_14A_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 = (GetCountSspClk() & 0xfffffff8);
Demod.startTime -= Demod.syncBit;
Demod.bitCount = 1; // number of decoded data bits
Demod.shiftReg = 1;
Demod.state = DEMOD_14A_MANCHESTER_DATA;
}
}
} 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) | 0x1; // in both cases, add a 1 to the shiftreg
if (Demod.bitCount == 8) { // if we decoded a full byte
Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
Demod.bitCount = 0;
Demod.shiftReg = 0;
}
Demod.endTime = Demod.startTime + 8 * (8 * 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 >= 8) { // if we decoded a full byte
Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
Demod.bitCount = 0;
Demod.shiftReg = 0;
}
Demod.endTime = Demod.startTime + 8 * (8 * Demod.len + Demod.bitCount + 1);
} else { // no modulation in both halves - End of communication
if (Demod.bitCount > 0) { // there are some remaining data bits
Demod.shiftReg <<= (8 - Demod.bitCount); // left align the decoded bits
Demod.output[Demod.len++] = Demod.shiftReg & 0xff; // and add them to the output
return true;
}
if (Demod.len) {
return true; // we are finished with decoding the raw data sequence
} else { // nothing received. Start over
Demod14aReset();
}
}
}
}
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.
// "hf 14a sniff"
//-----------------------------------------------------------------------------
void RAMFUNC SniffIso14443a(uint8_t param) {
LEDsoff();
// param:
// bit 0 - trigger from first card answer
// bit 1 - trigger from first reader 7-bit request
iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER);
// Allocate memory from BigBuf for some buffers
// free all previous allocations first
BigBuf_free();
BigBuf_Clear_ext(false);
clear_trace();
set_tracing(true);
// 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 *receivedResp = BigBuf_malloc(MAX_FRAME_SIZE);
uint8_t *receivedRespPar = BigBuf_malloc(MAX_PARITY_SIZE);
uint8_t previous_data = 0;
int maxDataLen = 0, dataLen;
bool TagIsActive = false;
bool ReaderIsActive = false;
// Set up the demodulator for tag -> reader responses.
Demod14aInit(receivedResp, receivedRespPar);
// Set up the demodulator for the reader -> tag commands
Uart14aInit(receivedCmd, receivedCmdPar);
Dbprintf("Starting to sniff. Press PM3 Button to stop.");
// The DMA buffer, used to stream samples from the FPGA
dmabuf8_t *dma = get_dma8();
uint8_t *data = dma->buf;
// Setup and start DMA.
if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) {
if (g_dbglevel > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
return;
}
// 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);
uint32_t rx_samples = 0;
// loop and listen
while (BUTTON_PRESS() == false) {
WDT_HIT();
LED_A_ON();
register int readBufDataP = data - dma->buf;
register int 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 %u", 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) dma->buf;
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) dma->buf;
AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
}
LED_A_OFF();
// Need two samples to feed Miller and Manchester-Decoder
if (rx_samples & 0x01) {
if (TagIsActive == false) { // no need to try decoding reader data if the tag is sending
uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
if (MillerDecoding(readerdata, (rx_samples - 1) * 4)) {
LED_C_ON();
// 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;
}
/* ready to receive another command. */
Uart14aReset();
/* reset the demod code, which might have been */
/* false-triggered by the commands from the reader. */
Demod14aReset();
LED_B_OFF();
}
ReaderIsActive = (Uart.state != STATE_14A_UNSYNCD);
}
// no need to try decoding tag data if the reader is sending - and we cannot afford the time
if (ReaderIsActive == false) {
uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
if (ManchesterDecoding(tagdata, 0, (rx_samples - 1) * 4)) {
LED_B_ON();
if (!LogTrace(receivedResp,
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;
// ready to receive another response.
Demod14aReset();
// reset the Miller decoder including its (now outdated) input buffer
Uart14aReset();
//Uart14aInit(receivedCmd, receivedCmdPar);
LED_C_OFF();
}
TagIsActive = (Demod.state != DEMOD_14A_UNSYNCD);
}
}
previous_data = *data;
rx_samples++;
data++;
if (data == dma->buf + DMA_BUFFER_SIZE) {
data = dma->buf;
}
} // end main loop
FpgaDisableTracing();
if (g_dbglevel >= DBG_ERROR) {
Dbprintf("trace len = " _YELLOW_("%d"), BigBuf_get_traceLen());
}
switch_off();
}
//-----------------------------------------------------------------------------
// Prepare tag messages
//-----------------------------------------------------------------------------
static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, const uint8_t *par, bool collision) {
tosend_reset();
tosend_t *ts = get_tosend();
// Correction bit, might be removed when not needed
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(1); // <-----
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(0);
// Send startbit
ts->buf[++ts->max] = SEC_D;
LastProxToAirDuration = 8 * ts->max - 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 (collision) {
ts->buf[++ts->max] = SEC_COLL;
} else {
if (b & 1) {
ts->buf[++ts->max] = SEC_D;
} else {
ts->buf[++ts->max] = SEC_E;
}
b >>= 1;
}
}
if (collision) {
ts->buf[++ts->max] = SEC_COLL;
LastProxToAirDuration = 8 * ts->max;
} else {
// Get the parity bit
if (par[i >> 3] & (0x80 >> (i & 0x0007))) {
ts->buf[++ts->max] = SEC_D;
LastProxToAirDuration = 8 * ts->max - 4;
} else {
ts->buf[++ts->max] = SEC_E;
LastProxToAirDuration = 8 * ts->max;
}
}
}
// Send stopbit
ts->buf[++ts->max] = SEC_F;
// Convert from last byte pos to length
ts->max++;
}
static void CodeIso14443aAsTagEx(const uint8_t *cmd, uint16_t len, bool collision) {
uint8_t par[MAX_PARITY_SIZE] = {0};
GetParity(cmd, len, par);
CodeIso14443aAsTagPar(cmd, len, par, collision);
}
static void CodeIso14443aAsTag(const uint8_t *cmd, uint16_t len) {
CodeIso14443aAsTagEx(cmd, len, false);
}
static void Code4bitAnswerAsTag(uint8_t cmd) {
uint8_t b = cmd;
tosend_reset();
tosend_t *ts = get_tosend();
// Correction bit, might be removed when not needed
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(1); // 1
tosend_stuffbit(0);
tosend_stuffbit(0);
tosend_stuffbit(0);
// Send startbit
ts->buf[++ts->max] = SEC_D;
for (uint8_t i = 0; i < 4; i++) {
if (b & 1) {
ts->buf[++ts->max] = SEC_D;
LastProxToAirDuration = 8 * ts->max - 4;
} else {
ts->buf[++ts->max] = SEC_E;
LastProxToAirDuration = 8 * ts->max;
}
b >>= 1;
}
// Send stopbit
ts->buf[++ts->max] = SEC_F;
// Convert from last byte pos to length
ts->max++;
}
//-----------------------------------------------------------------------------
// Wait for commands from reader
// stop when button is pressed or client usb connection resets
// or return TRUE when command is captured
//-----------------------------------------------------------------------------
bool GetIso14443aCommandFromReader(uint8_t *received, uint8_t *par, 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.
Uart14aInit(received, par);
// clear RXRDY:
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
(void)b;
uint8_t flip = 0;
uint16_t checker = 4000;
for (;;) {
WDT_HIT();
// ever 3 * 4000, check if we got any data from client
// takes long time, usually messes with simualtion
if (flip == 3) {
if (data_available())
return false;
flip = 0;
}
// button press, takes a bit time, might mess with simualtion
if (checker-- == 0) {
if (BUTTON_PRESS())
return false;
flip++;
checker = 4000;
}
if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if (MillerDecoding(b, 0)) {
*len = Uart.len;
return true;
}
}
}
return false;
}
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
CodeIso14443aAsTag(response_info->response, response_info->response_n);
tosend_t *ts = get_tosend();
// Make sure we do not exceed the free buffer space
if (ts->max > max_buffer_size) {
Dbprintf("ToSend buffer, Out-of-bound, 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, ts->buf, ts->max);
// Store the number of bytes that were used for encoding/modulation and the time needed to transfer them