forked from RfidResearchGroup/proxmark3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiso14443b.c
2259 lines (1909 loc) · 72.3 KB
/
iso14443b.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
//-----------------------------------------------------------------------------
// Jonathan Westhues, split Nov 2006
// piwi 2018
//
// 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 14443B. This includes both the reader software and
// the `fake tag' modes.
//-----------------------------------------------------------------------------
#include "iso14443b.h"
#include "proxmark3_arm.h"
#include "common.h" // access to global variable: g_dbglevel
#include "util.h"
#include "string.h"
#include "crc16.h"
#include "protocols.h"
#include "appmain.h"
#include "BigBuf.h"
#include "cmd.h"
#include "fpgaloader.h"
#include "commonutil.h"
#include "dbprint.h"
#include "ticks.h"
#include "iso14b.h" // defines for ETU conversions
/*
* Current timing issues with ISO14443-b implementation
* Proxmark3
* Carrier Frequency 13.56MHz
* SSP_CLK runs at 13.56MHz / 4 = 3,39MHz
*
*
* PROBLEM 1.
* ----------
* one way of calculating time, that relates both to PM3 ssp_clk 3.39MHz, ISO freq of 13.56Mhz and ETUs
* convert from µS -> our SSP_CLK units which is used in the DEFINES..
* convert from ms -> our SSP_CLK units...
* convert from ETU -> our SSP_CLK units...
* All ETU -> µS -> ms should be diveded by for to match Proxmark3 FPGA SSP_CLK :)
*
*
* PROBLEM 2.
* ----------
* all DEFINES is in SSP_CLK ticks
* all delays is in SSP_CLK ticks
*/
#ifndef RECEIVE_MASK
# define RECEIVE_MASK (DMA_BUFFER_SIZE - 1)
#endif
// SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
// All values should be multiples of 2 (?)
#define DELAY_READER_TO_ARM 8
#define DELAY_ARM_TO_READER 0
// SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader.
// All values should be multiples of 16
#define DELAY_ARM_TO_TAG 16
#define DELAY_TAG_TO_ARM 32
// SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when sniffing.
// All values should be multiples of 16
#define DELAY_TAG_TO_ARM_SNIFF 32
#define DELAY_READER_TO_ARM_SNIFF 32
/* ISO14443-4
*
* Frame Waiting Time Integer (FWI)
* can be between 0 and 14.
* FWI_default = 4
* FWI_max = 14
*
* Frame Waiting Time (FWT) formula
* --------------------------------
* FWT = (256 x 16 / fc) * 2 to the power for FWI
*
* sample:
* ------- 2 to the power of FWI(4)
* FWT = (256 x 16 / fc) * (2*2*2*2) == 4.833 ms
* FTW(default) == FWT(4) == 4.822ms
*
* FWI_max == 2^14 = 16384
* FWT(max) = (256 x 16 / fc) * 16384 == 4949
*
* Which gives a maximum Frame Waiting time of FWT(max) == 4949 ms
* FWT(max) in ETU 4949000 / 9.4395 µS = 524286 ETU
*
* Simple calc to convert to ETU or µS
* -----------------------------------
* uint32_t fwt_time_etu = (32 << fwt);
* uint32_t fwt_time_us = (302 << fwt);
*
*/
#ifndef MAX_14B_TIMEOUT
// FWT(max) = 4949 ms or 4.95 seconds.
// SSP_CLK = 4949000 * 3.39 = 16777120
# define MAX_14B_TIMEOUT (16777120U)
#endif
// Activation frame waiting time
// 512 ETU?
// 65536/fc == 4833 µS or 4.833ms
// SSP_CLK = 4833 µS * 3.39 = 16384
#ifndef FWT_TIMEOUT_14B
# define FWT_TIMEOUT_14B (16384)
#endif
// ETU 14 * 9.4395 µS = 132 µS == 0.132ms
// TR2, counting from start of PICC EOF 14 ETU.
#define DELAY_ISO14443B_PICC_TO_PCD_READER ETU_TO_SSP(14)
#define DELAY_ISO14443B_PCD_TO_PICC_READER ETU_TO_SSP(15)
/* Guard Time (per 14443-2) in ETU
*
* Transition time. TR0 - guard time
* TR0 - 8 ETU's minimum.
* TR0 - 32 ETU's maximum for ATQB only
* TR0 - FWT for all other commands
* 32,64,128,256,512, ... , 262144, 524288 ETU
* TR0 = FWT(1), FWT(2), FWT(3) .. FWT(14)
*
*
* TR0
*/
#ifndef ISO14B_TR0
# define ISO14B_TR0 ETU_TO_SSP(32)
#endif
#ifndef ISO14B_TR0_MAX
# define ISO14B_TR0_MAX ETU_TO_SSP(32)
// * TR0 - 32 ETU's maximum for ATQB only
// * TR0 - FWT for all other commands
// TR0 max is 151/fsc = 151/848kHz = 302us or 64 samples from FPGA
// 32 ETU * 9.4395 µS == 302 µS
// 32 * 8 = 256 sub carrier cycles,
// 256 / 4 = 64 I/Q pairs.
// since 1 I/Q pair after 4 subcarrier cycles at 848kHz subcarrier
#endif
// 8 ETU = 75 µS == 256 SSP_CLK
#ifndef ISO14B_TR0_MIN
# define ISO14B_TR0_MIN ETU_TO_SSP(8)
#endif
// Synchronization time (per 14443-2) in ETU
// 10 ETU = 94,39 µS == 320 SSP_CLK
#ifndef ISO14B_TR1_MIN
# define ISO14B_TR1_MIN ETU_TO_SSP(10)
#endif
// Synchronization time (per 14443-2) in ETU
// 25 ETU == 236 µS == 800 SSP_CLK
#ifndef ISO14B_TR1_MAX
# define ISO14B_TR1 ETU_TO_SSP(25)
#endif
// Frame Delay Time PICC to PCD (per 14443-3 Amendment 1) in ETU
// 14 ETU == 132 µS == 448 SSP_CLK
#ifndef ISO14B_TR2
# define ISO14B_TR2 ETU_TO_SSP(14)
#endif
// 4sample
#define SEND4STUFFBIT(x) tosend_stuffbit(x);tosend_stuffbit(x);tosend_stuffbit(x);tosend_stuffbit(x);
static void iso14b_set_timeout(uint32_t timeout_etu);
static void iso14b_set_maxframesize(uint16_t size);
static void iso14b_set_fwt(uint8_t fwt);
// the block number for the ISO14443-4 PCB (used with APDUs)
static uint8_t iso14b_pcb_blocknum = 0;
static uint8_t iso14b_fwt = 9;
static uint32_t iso14b_timeout = FWT_TIMEOUT_14B;
/*
* ISO 14443-B communications
* --------------------------
* Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
* Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
*
* It uses half duplex with a 106 kbit per second data rate in each direction.
* Data transmitted by the card is load modulated with a 847.5 kHz subcarrier.
*
* fc - carrier frequency 13.56 MHz
* TR0 - Guard Time per 14443-2
* TR1 - Synchronization Time per 14443-2
* TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
*
* Elementary Time Unit (ETU)
* --------------------------
* ETU is used to denotate 1 bit period i.e. how long one bit transfer takes.
*
* - 128 Carrier cycles / 13.56MHz = 8 Subcarrier units / 848kHz = 1/106kHz = 9.4395 µS
* - 16 Carrier cycles = 1 Subcarrier unit = 1.17 µS
*
* Definition
* ----------
* 1 ETU = 128 / ( D x fc )
* where
* D = divisor. Which inital is 1
* fc = carrier frequency
* gives
* 1 ETU = 128 / fc
* 1 ETU = 128 / 13 560 000 = 9.4395 µS
* 1 ETU = 9.4395 µS
*
* (note: It seems we are using the subcarrier as base for our time calculations rather than the field clock)
*
* - 1 ETU = 1/106 KHz
* - 1 ETU = 8 subcarrier units ( 8 / 848kHz )
* - 1 ETU = 1 bit period
*
*
* Card sends data at 848kHz subcarrier
* subcar |duration| FC division| I/Q pairs
* -------+--------+------------+--------
* 106kHz | 9.44µS | FC/128 | 16
* 212kHz | 4.72µS | FC/64 | 8
* 424kHz | 2.36µS | FC/32 | 4
* 848kHz | 1.18µS | FC/16 | 2
* -------+--------+------------+--------
*
*
* One Character consists of 1 start, 1 stop, 8 databit with a total length of 10bits.
* - 1 Character = 10 ETU = 1 startbit, 8 databits, 1 stopbit
* - startbit is a 0
* - stopbit is a 1
*
* Start of frame (SOF) is
* - [10-11] ETU of ZEROS, unmodulated time
* - [2-3] ETU of ONES,
*
* End of frame (EOF) is
* - [10-11] ETU of ZEROS, unmodulated time
*
* Reader data transmission
* ------------------------
* - no modulation ONES
* - SOF
* - Command, data and CRC_B (1 Character)
* - EOF
* - no modulation ONES
*
* Card data transmission
* ----------------------
* - TR1
* - SOF
* - data (1 Character)
* - CRC_B
* - EOF
*
* Transfer times
* --------------
* let calc how long it takes the reader to send a message
* SOF 10 ETU + 4 data bytes + 2 crc bytes + EOF 2 ETU
* 10 + (4+2 * 10) + 2 = 72 ETU
* 72 * 9.4395 = 680 µS or 0.68 ms
*
*
* -> TO VERIFY THIS BELOW <-
* --------------------------
* The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
* works like this:
* Simulation per definition is "inversed" effect on the reader antenna.
* - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (1.18µS / pulse) == 9.44us
* - A 0-bit input to the FPGA becomes an unmodulated time of 1.18µS or does it become 8 nonpulses for 9.44us
*
*
* FPGA implementation
* -------------------
* Piwi implemented a I/Q sampling mode for the FPGA, where...
*
* FPGA doesn't seem to work with ETU. It seems to work with pulse / duration instead.
*
* This means that we are using a bit rate of 106 kbit/s, or fc/128.
* Oversample by 4, which ought to make things practical for the ARM
* (fc/32, 423.8 kbits/s, ~52 kbytes/s)
*
* We are sampling the signal at FC/32, we are reporting over SSP to PM3 each
*
* Current I/Q pair sampling
* -------------------------
* Let us report a correlation every 64 samples. I.e.
* 1 I/Q pair after 4 subcarrier cycles for the 848kHz subcarrier,
* 1 I/Q pair after 2 subcarrier cycles for the 424kHz subcarrier,
*/
/*
* Formula to calculate FWT (in ETUs) by timeout (in ms):
*
* 1 tick is about 1.5µS
* 1000 ms/s
*
* FWT = 13560000 * 1000 / (8*16) * timeout
* FWT = 13560000 * 1000 / 128 * timeout
*
* sample: 3sec == 3000ms
*
* 13560000 * 1000 / 128 * 3000 == 13560000000 / 384000 ==
* 13560000 / 384 = 35312 FWT
*
* 35312 * 9.4395 ==
*
* @param timeout is in frame wait time, fwt, measured in ETUs
*
* However we need to compensate for SSP_CLK ...
*/
//=============================================================================
// An ISO 14443 Type B tag. We listen for commands from the reader, using
// a UART kind of thing that's implemented in software. When we get a
// frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
// If it's good, then we can do something appropriate with it, and send
// a response.
//=============================================================================
//-----------------------------------------------------------------------------
// Code up a string of octets at layer 2 (including CRC, we don't generate
// that here) so that they can be transmitted to the reader. Doesn't transmit
// them yet, just leaves them ready to send in ToSend[].
//-----------------------------------------------------------------------------
static void CodeIso14443bAsTag(const uint8_t *cmd, int len) {
int i;
tosend_reset();
// Transmit a burst of ones, as the initial thing that lets the
// reader get phase sync.
// This loop is TR1, per specification
// TR1 minimum must be > 80/fs
// TR1 maximum 200/fs
// 80/fs < TR1 < 200/fs
// 10 ETU < TR1 < 24 ETU
// Send TR1.
// 10-11 ETU * 4times samples ONES
for (i = 0; i < 10; i++) {
SEND4STUFFBIT(1);
}
// Send SOF.
// 10-11 ETU * 4times samples ZEROS
for (i = 0; i < 10; i++) {
SEND4STUFFBIT(0);
}
// 2-3 ETU * 4times samples ONES
for (i = 0; i < 2; i++) {
SEND4STUFFBIT(1);
}
// data
for (i = 0; i < len; i++) {
// Start bit
SEND4STUFFBIT(0);
// Data bits
uint8_t b = cmd[i];
for (int j = 0; j < 8; j++) {
SEND4STUFFBIT(b & 1);
b >>= 1;
}
// Stop bit
SEND4STUFFBIT(1);
// Extra Guard bit
// For PICC it ranges 0-18us (1etu = 9us)
//SEND4STUFFBIT(1);
}
// Send EOF.
// 10-11 ETU * 4 sample rate = ZEROS
for (i = 0; i < 10; i++) {
SEND4STUFFBIT(0);
}
// why this? push out transfers between arm and fpga?
//for (i = 0; i < 2; i++) {
// SEND4STUFFBIT(1);
//}
tosend_t *ts = get_tosend();
// Convert from last byte pos to length
ts->max++;
}
//-----------------------------------------------------------------------------
// The software UART that receives commands from the reader, and its state
// variables.
//-----------------------------------------------------------------------------
static struct {
enum {
STATE_14B_UNSYNCD,
STATE_14B_GOT_FALLING_EDGE_OF_SOF,
STATE_14B_AWAITING_START_BIT,
STATE_14B_RECEIVING_DATA
} state;
uint16_t shiftReg;
int bitCnt;
int byteCnt;
int byteCntMax;
int posCnt;
uint8_t *output;
} Uart;
static void Uart14bReset(void) {
Uart.state = STATE_14B_UNSYNCD;
Uart.shiftReg = 0;
Uart.bitCnt = 0;
Uart.byteCnt = 0;
Uart.byteCntMax = MAX_FRAME_SIZE;
Uart.posCnt = 0;
}
static void Uart14bInit(uint8_t *data) {
Uart.output = data;
Uart14bReset();
}
// param timeout accepts ETU
static void iso14b_set_timeout(uint32_t timeout_etu) {
uint32_t ssp = ETU_TO_SSP(timeout_etu);
if (ssp > MAX_14B_TIMEOUT)
ssp = MAX_14B_TIMEOUT;
iso14b_timeout = ssp;
if (g_dbglevel >= DBG_DEBUG) {
Dbprintf("ISO14443B Timeout set to %ld fwt", iso14b_timeout);
}
}
// keep track of FWT, also updates the timeout
static void iso14b_set_fwt(uint8_t fwt) {
iso14b_fwt = fwt;
iso14b_set_timeout(32 << fwt);
}
static void iso14b_set_maxframesize(uint16_t size) {
if (size > 256)
size = MAX_FRAME_SIZE;
Uart.byteCntMax = size;
if (g_dbglevel >= DBG_DEBUG) Dbprintf("ISO14443B Max frame size set to %d bytes", Uart.byteCntMax);
}
//-----------------------------------------------------------------------------
// The software Demod that receives commands from the tag, and its state variables.
//-----------------------------------------------------------------------------
#define NOISE_THRESHOLD 80 // don't try to correlate noise
#define MAX_PREVIOUS_AMPLITUDE (-1 - NOISE_THRESHOLD)
static struct {
enum {
DEMOD_UNSYNCD,
DEMOD_PHASE_REF_TRAINING,
WAIT_FOR_RISING_EDGE_OF_SOF,
DEMOD_AWAITING_START_BIT,
DEMOD_RECEIVING_DATA
} state;
uint16_t bitCount;
int posCount;
int thisBit;
uint16_t shiftReg;
uint16_t max_len;
uint8_t *output;
uint16_t len;
int sumI;
int sumQ;
} Demod;
// Clear out the state of the "UART" that receives from the tag.
static void Demod14bReset(void) {
Demod.state = DEMOD_UNSYNCD;
Demod.bitCount = 0;
Demod.posCount = 0;
Demod.thisBit = 0;
Demod.shiftReg = 0;
Demod.len = 0;
Demod.sumI = 0;
Demod.sumQ = 0;
}
static void Demod14bInit(uint8_t *data, uint16_t max_len) {
Demod.output = data;
Demod.max_len = max_len;
Demod14bReset();
}
/* Receive & handle a bit coming from the reader.
*
* This function is called 4 times per bit (every 2 subcarrier cycles).
* Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
*
* LED handling:
* LED A -> ON once we have received the SOF and are expecting the rest.
* LED A -> OFF once we have received EOF or are in error state or unsynced
*
* Returns: true if we received a EOF
* false if we are still waiting for some more
*/
static RAMFUNC int Handle14443bSampleFromReader(uint8_t bit) {
switch (Uart.state) {
case STATE_14B_UNSYNCD:
if (bit == false) {
// we went low, so this could be the beginning of an SOF
Uart.state = STATE_14B_GOT_FALLING_EDGE_OF_SOF;
Uart.posCnt = 0;
Uart.bitCnt = 0;
}
break;
case STATE_14B_GOT_FALLING_EDGE_OF_SOF:
Uart.posCnt++;
if (Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
if (bit) {
if (Uart.bitCnt > 9) {
// we've seen enough consecutive
// zeros that it's a valid SOF
Uart.posCnt = 0;
Uart.byteCnt = 0;
Uart.state = STATE_14B_AWAITING_START_BIT;
LED_A_ON(); // Indicate we got a valid SOF
} else {
// didn't stay down long enough before going high, error
Uart.state = STATE_14B_UNSYNCD;
}
} else {
// do nothing, keep waiting
}
Uart.bitCnt++;
}
if (Uart.posCnt >= 4) {
Uart.posCnt = 0;
}
if (Uart.bitCnt > 12) {
// Give up if we see too many zeros without a one, too.
LED_A_OFF();
Uart.state = STATE_14B_UNSYNCD;
}
break;
case STATE_14B_AWAITING_START_BIT:
Uart.posCnt++;
if (bit) {
// max 57us between characters = 49 1/fs,
// max 3 etus after low phase of SOF = 24 1/fs
if (Uart.posCnt > 50 / 2) {
// stayed high for too long between characters, error
Uart.state = STATE_14B_UNSYNCD;
}
} else {
// falling edge, this starts the data byte
Uart.posCnt = 0;
Uart.bitCnt = 0;
Uart.shiftReg = 0;
Uart.state = STATE_14B_RECEIVING_DATA;
}
break;
case STATE_14B_RECEIVING_DATA:
Uart.posCnt++;
if (Uart.posCnt == 2) {
// time to sample a bit
Uart.shiftReg >>= 1;
if (bit) {
Uart.shiftReg |= 0x200;
}
Uart.bitCnt++;
}
if (Uart.posCnt >= 4) {
Uart.posCnt = 0;
}
if (Uart.bitCnt == 10) {
if ((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001)) {
// this is a data byte, with correct
// start and stop bits
Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xFF;
Uart.byteCnt++;
if (Uart.byteCnt >= Uart.byteCntMax) {
// Buffer overflowed, give up
LED_A_OFF();
Uart.state = STATE_14B_UNSYNCD;
} else {
// so get the next byte now
Uart.posCnt = 0;
Uart.state = STATE_14B_AWAITING_START_BIT;
}
} else if (Uart.shiftReg == 0x000) {
// this is an EOF byte
LED_A_OFF(); // Finished receiving
Uart.state = STATE_14B_UNSYNCD;
if (Uart.byteCnt != 0)
return true;
} else {
// this is an error
LED_A_OFF();
Uart.state = STATE_14B_UNSYNCD;
}
}
break;
default:
LED_A_OFF();
Uart.state = STATE_14B_UNSYNCD;
break;
}
return false;
}
//-----------------------------------------------------------------------------
// Receive a command (from the reader to us, where we are the simulated tag),
// and store it in the given buffer, up to the given maximum length. Keeps
// spinning, waiting for a well-framed command, until either we get one
// (returns true) or someone presses the pushbutton on the board (false).
//
// Assume that we're called with the SSC (to the FPGA) and ADC path set
// correctly.
//-----------------------------------------------------------------------------
static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) {
// Set FPGA mode to "simulated ISO 14443B 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_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
// Now run a `software UART' on the stream of incoming samples.
Uart14bInit(received);
while (BUTTON_PRESS() == false) {
WDT_HIT();
if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
for (uint8_t mask = 0x80; mask != 0x00; mask >>= 1) {
if (Handle14443bSampleFromReader(b & mask)) {
*len = Uart.byteCnt;
return true;
}
}
}
}
return false;
}
static void TransmitFor14443b_AsTag(uint8_t *response, uint16_t len) {
// Signal field is off with the appropriate LED
LED_D_OFF();
// Modulate BPSK
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
AT91C_BASE_SSC->SSC_THR = 0xFF;
FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
// Transmit the response.
for (uint16_t i = 0; i < len;) {
// Put byte into tx holding register as soon as it is ready
if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
AT91C_BASE_SSC->SSC_THR = response[i++];
}
}
}
//-----------------------------------------------------------------------------
// Main loop of simulated tag: receive commands from reader, decide what
// response to send, and send it.
//-----------------------------------------------------------------------------
void SimulateIso14443bTag(uint8_t *pupi) {
LED_A_ON();
// the only commands we understand is WUPB, AFI=0, Select All, N=1:
// static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
// ... and REQB, AFI=0, Normal Request, N=1:
// static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
// ... and HLTB
// static const uint8_t cmdHLTB[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB
// ... and ATTRIB
// static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
// ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
// supports only 106kBit/s in both directions, max frame size = 32Bytes,
// supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
uint8_t respATQB[] = {
0x50,
0x82, 0x0d, 0xe1, 0x74,
0x20, 0x38, 0x19,
0x22, 0x00, 0x21, 0x85,
0x5e, 0xd7
};
// ...PUPI/UID supplied from user. Adjust ATQB response accordingly
if (memcmp("\x00\x00\x00\x00", pupi, 4) != 0) {
memcpy(respATQB + 1, pupi, 4);
AddCrc14B(respATQB, 12);
}
// response to HLTB and ATTRIB
static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
// setup device.
FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
// connect Demodulated Signal to ADC:
SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
// Set up the synchronous serial port
FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
// allocate command receive buffer
BigBuf_free();
BigBuf_Clear_ext(false);
clear_trace();
set_tracing(true);
uint16_t len, cmdsReceived = 0;
int cardSTATE = SIM_NOFIELD;
int vHf = 0; // in mV
tosend_t *ts = get_tosend();
uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
// prepare "ATQB" tag answer (encoded):
CodeIso14443bAsTag(respATQB, sizeof(respATQB));
uint8_t *encodedATQB = BigBuf_malloc(ts->max);
uint16_t encodedATQBLen = ts->max;
memcpy(encodedATQB, ts->buf, ts->max);
// prepare "OK" tag answer (encoded):
CodeIso14443bAsTag(respOK, sizeof(respOK));
uint8_t *encodedOK = BigBuf_malloc(ts->max);
uint16_t encodedOKLen = ts->max;
memcpy(encodedOK, ts->buf, ts->max);
// Simulation loop
while (BUTTON_PRESS() == false) {
WDT_HIT();
//iceman: limit with 2000 times..
if (data_available()) {
break;
}
// find reader field
if (cardSTATE == SIM_NOFIELD) {
vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
if (vHf > MF_MINFIELDV) {
cardSTATE = SIM_IDLE;
LED_A_ON();
}
}
if (cardSTATE == SIM_NOFIELD) continue;
// Get reader command
if (!GetIso14443bCommandFromReader(receivedCmd, &len)) {
Dbprintf("button pressed, received %d commands", cmdsReceived);
break;
}
// ISO14443-B protocol states:
// REQ or WUP request in ANY state
// WUP in HALTED state
if (len == 5) {
if ((receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8) == 0x8 && cardSTATE == SIM_HALTED) ||
receivedCmd[0] == ISO14443B_REQB) {
LogTrace(receivedCmd, len, 0, 0, NULL, true);
cardSTATE = SIM_SELECTING;
}
}
/*
* How should this flow go?
* REQB or WUPB
* send response ( waiting for Attrib)
* ATTRIB
* send response ( waiting for commands 7816)
* HALT
send halt response ( waiting for wupb )
*/
switch (cardSTATE) {
//case SIM_NOFIELD:
case SIM_HALTED:
case SIM_IDLE: {
LogTrace(receivedCmd, len, 0, 0, NULL, true);
break;
}
case SIM_SELECTING: {
TransmitFor14443b_AsTag(encodedATQB, encodedATQBLen);
LogTrace(respATQB, sizeof(respATQB), 0, 0, NULL, false);
cardSTATE = SIM_WORK;
break;
}
case SIM_HALTING: {
TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
cardSTATE = SIM_HALTED;
break;
}
case SIM_ACKNOWLEDGE: {
TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
cardSTATE = SIM_IDLE;
break;
}
case SIM_WORK: {
if (len == 7 && receivedCmd[0] == ISO14443B_HALT) {
cardSTATE = SIM_HALTED;
} else if (len == 11 && receivedCmd[0] == ISO14443B_ATTRIB) {
cardSTATE = SIM_ACKNOWLEDGE;
} else {
// Todo:
// - SLOT MARKER
// - ISO7816
// - emulate with a memory dump
if (g_dbglevel >= DBG_DEBUG)
Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsReceived);
// CRC Check
if (len >= 3) { // if crc exists
if (!check_crc(CRC_14443_B, receivedCmd, len)) {
if (g_dbglevel >= DBG_DEBUG) {
DbpString("CRC fail");
}
}
} else {
if (g_dbglevel >= DBG_DEBUG) {
DbpString("CRC passed");
}
}
cardSTATE = SIM_IDLE;
}
break;
}
default:
break;
}
++cmdsReceived;
}
if (g_dbglevel >= DBG_DEBUG)
Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
switch_off(); //simulate
}
/*
void Simulate_iso14443b_srx_tag(uint8_t *uid) {
LED_A_ON();
/ SRI512
> initiate 06 00 ISO14443B_INITIATE
< xx crc crc
> select 0e xx ISO14443B_SELECT
< xx nn nn
> readblock 08 blck_no ISO14443B_READ_BLK
< d0 d1 d2 d3 2byte crc
> get uid ISO14443B_GET_UID
< 81 93 99 20 92 11 02 (8byte UID in MSB D002 199220 999381)
#define ISO14443B_REQB 0x05
#define ISO14443B_ATTRIB 0x1D
#define ISO14443B_HALT 0x50
#define ISO14443B_INITIATE 0x06
#define ISO14443B_SELECT 0x0E
#define ISO14443B_GET_UID 0x0B
#define ISO14443B_READ_BLK 0x08
#define ISO14443B_WRITE_BLK 0x09
#define ISO14443B_RESET 0x0C
#define ISO14443B_COMPLETION 0x0F
#define ISO14443B_AUTHENTICATE 0x0A
#define ISO14443B_PING 0xBA
#define ISO14443B_PONG 0xAB
static const uint8_t resp_init_srx[] = { 0x73, 0x64, 0xb1 };
uint8_t resp_select_srx[] = { 0x73, 0x64, 0xb1 };
// a default uid, or user supplied
uint8_t resp_getuid_srx[10] = {
0x81, 0x93, 0x99, 0x20, 0x92, 0x11, 0x02, 0xD0, 0x00, 0x00
};
// ...UID supplied from user. Adjust ATQB response accordingly
if (memcmp("\x00\x00\x00\x00\x00\x00\x00\x00", uid, 8) != 0) {
memcpy(resp_getuid_srx, uid, 8);
AddCrc14B(resp_getuid_srx, 8);
}
// response to HLTB and ATTRIB
static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
// setup device.
FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
// connect Demodulated Signal to ADC:
SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
// Set up the synchronous serial port
FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
// allocate command receive buffer
BigBuf_free();
BigBuf_Clear_ext(false);
clear_trace();
set_tracing(true);
uint16_t len, cmdsReceived = 0;
int cardSTATE = SIM_NOFIELD;
int vHf = 0; // in mV
tosend_t *ts = get_tosend();
uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
// prepare "ATQB" tag answer (encoded):
CodeIso14443bAsTag(respATQB, sizeof(respATQB));
uint8_t *encodedATQB = BigBuf_malloc(ts->max);
uint16_t encodedATQBLen = ts->max;
memcpy(encodedATQB, ts->buf, ts->max);
// prepare "OK" tag answer (encoded):
CodeIso14443bAsTag(respOK, sizeof(respOK));
uint8_t *encodedOK = BigBuf_malloc(ts->max);
uint16_t encodedOKLen = ts->max;
memcpy(encodedOK, ts->buf, ts->max);
// Simulation loop
while (BUTTON_PRESS() == false) {
WDT_HIT();
//iceman: limit with 2000 times..
if (data_available()) {
break;
}
// find reader field
if (cardSTATE == SIM_NOFIELD) {
vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
if (vHf > MF_MINFIELDV) {
cardSTATE = SIM_IDLE;
LED_A_ON();
}
}
if (cardSTATE == SIM_NOFIELD) continue;
// Get reader command
if (!GetIso14443bCommandFromReader(receivedCmd, &len)) {
Dbprintf("button pressed, received %d commands", cmdsReceived);
break;
}
// ISO14443-B protocol states:
// REQ or WUP request in ANY state
// WUP in HALTED state
if (len == 5) {
if ((receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8) == 0x8 && cardSTATE == SIM_HALTED) ||
receivedCmd[0] == ISO14443B_REQB) {
LogTrace(receivedCmd, len, 0, 0, NULL, true);
cardSTATE = SIM_SELECTING;
}
}
/