]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iso14443a.c
Fixed ISSUE 15 in iso14443a.c - Gerhard
[proxmark3-svn] / armsrc / iso14443a.c
1 //-----------------------------------------------------------------------------
2 // Gerhard de Koning Gans - May 2008
3 // Hagen Fritsch - June 2010
4 //
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
7 // the license.
8 //-----------------------------------------------------------------------------
9 // Routines to support ISO 14443 type A.
10 //-----------------------------------------------------------------------------
11
12 #include "proxmark3.h"
13 #include "apps.h"
14 #include "util.h"
15 #include "string.h"
16
17 #include "iso14443crc.h"
18 #include "iso14443a.h"
19
20 static uint8_t *trace = (uint8_t *) BigBuf;
21 static int traceLen = 0;
22 static int rsamples = 0;
23 static int tracing = TRUE;
24 static uint32_t iso14a_timeout;
25
26 // CARD TO READER
27 // Sequence D: 11110000 modulation with subcarrier during first half
28 // Sequence E: 00001111 modulation with subcarrier during second half
29 // Sequence F: 00000000 no modulation with subcarrier
30 // READER TO CARD
31 // Sequence X: 00001100 drop after half a period
32 // Sequence Y: 00000000 no drop
33 // Sequence Z: 11000000 drop at start
34 #define SEC_D 0xf0
35 #define SEC_E 0x0f
36 #define SEC_F 0x00
37 #define SEC_X 0x0c
38 #define SEC_Y 0x00
39 #define SEC_Z 0xc0
40
41 static const uint8_t OddByteParity[256] = {
42 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
43 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
44 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
45 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
46 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
47 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
48 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
49 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
50 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
51 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
52 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
56 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
57 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
58 };
59
60 // BIG CHANGE - UNDERSTAND THIS BEFORE WE COMMIT
61 #define RECV_CMD_OFFSET 3032
62 #define RECV_RES_OFFSET 3096
63 #define DMA_BUFFER_OFFSET 3160
64 #define DMA_BUFFER_SIZE 4096
65 #define TRACE_LENGTH 3000
66
67 uint8_t trigger = 0;
68 void iso14a_set_trigger(int enable) {
69 trigger = enable;
70 }
71
72 //-----------------------------------------------------------------------------
73 // Generate the parity value for a byte sequence
74 //
75 //-----------------------------------------------------------------------------
76 uint32_t GetParity(const uint8_t * pbtCmd, int iLen)
77 {
78 int i;
79 uint32_t dwPar = 0;
80
81 // Generate the encrypted data
82 for (i = 0; i < iLen; i++) {
83 // Save the encrypted parity bit
84 dwPar |= ((OddByteParity[pbtCmd[i]]) << i);
85 }
86 return dwPar;
87 }
88
89 void AppendCrc14443a(uint8_t* data, int len)
90 {
91 ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
92 }
93
94 int LogTrace(const uint8_t * btBytes, int iLen, int iSamples, uint32_t dwParity, int bReader)
95 {
96 // Return when trace is full
97 if (traceLen >= TRACE_LENGTH) return FALSE;
98
99 // Trace the random, i'm curious
100 rsamples += iSamples;
101 trace[traceLen++] = ((rsamples >> 0) & 0xff);
102 trace[traceLen++] = ((rsamples >> 8) & 0xff);
103 trace[traceLen++] = ((rsamples >> 16) & 0xff);
104 trace[traceLen++] = ((rsamples >> 24) & 0xff);
105 if (!bReader) {
106 trace[traceLen - 1] |= 0x80;
107 }
108 trace[traceLen++] = ((dwParity >> 0) & 0xff);
109 trace[traceLen++] = ((dwParity >> 8) & 0xff);
110 trace[traceLen++] = ((dwParity >> 16) & 0xff);
111 trace[traceLen++] = ((dwParity >> 24) & 0xff);
112 trace[traceLen++] = iLen;
113 memcpy(trace + traceLen, btBytes, iLen);
114 traceLen += iLen;
115 return TRUE;
116 }
117
118 //-----------------------------------------------------------------------------
119 // The software UART that receives commands from the reader, and its state
120 // variables.
121 //-----------------------------------------------------------------------------
122 static struct {
123 enum {
124 STATE_UNSYNCD,
125 STATE_START_OF_COMMUNICATION,
126 STATE_MILLER_X,
127 STATE_MILLER_Y,
128 STATE_MILLER_Z,
129 STATE_ERROR_WAIT
130 } state;
131 uint16_t shiftReg;
132 int bitCnt;
133 int byteCnt;
134 int byteCntMax;
135 int posCnt;
136 int syncBit;
137 int parityBits;
138 int samples;
139 int highCnt;
140 int bitBuffer;
141 enum {
142 DROP_NONE,
143 DROP_FIRST_HALF,
144 DROP_SECOND_HALF
145 } drop;
146 uint8_t *output;
147 } Uart;
148
149 static RAMFUNC int MillerDecoding(int bit)
150 {
151 int error = 0;
152 int bitright;
153
154 if(!Uart.bitBuffer) {
155 Uart.bitBuffer = bit ^ 0xFF0;
156 return FALSE;
157 }
158 else {
159 Uart.bitBuffer <<= 4;
160 Uart.bitBuffer ^= bit;
161 }
162
163 int EOC = FALSE;
164
165 if(Uart.state != STATE_UNSYNCD) {
166 Uart.posCnt++;
167
168 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
169 bit = 0x00;
170 }
171 else {
172 bit = 0x01;
173 }
174 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
175 bitright = 0x00;
176 }
177 else {
178 bitright = 0x01;
179 }
180 if(bit != bitright) { bit = bitright; }
181
182 if(Uart.posCnt == 1) {
183 // measurement first half bitperiod
184 if(!bit) {
185 Uart.drop = DROP_FIRST_HALF;
186 }
187 }
188 else {
189 // measurement second half bitperiod
190 if(!bit & (Uart.drop == DROP_NONE)) {
191 Uart.drop = DROP_SECOND_HALF;
192 }
193 else if(!bit) {
194 // measured a drop in first and second half
195 // which should not be possible
196 Uart.state = STATE_ERROR_WAIT;
197 error = 0x01;
198 }
199
200 Uart.posCnt = 0;
201
202 switch(Uart.state) {
203 case STATE_START_OF_COMMUNICATION:
204 Uart.shiftReg = 0;
205 if(Uart.drop == DROP_SECOND_HALF) {
206 // error, should not happen in SOC
207 Uart.state = STATE_ERROR_WAIT;
208 error = 0x02;
209 }
210 else {
211 // correct SOC
212 Uart.state = STATE_MILLER_Z;
213 }
214 break;
215
216 case STATE_MILLER_Z:
217 Uart.bitCnt++;
218 Uart.shiftReg >>= 1;
219 if(Uart.drop == DROP_NONE) {
220 // logic '0' followed by sequence Y
221 // end of communication
222 Uart.state = STATE_UNSYNCD;
223 EOC = TRUE;
224 }
225 // if(Uart.drop == DROP_FIRST_HALF) {
226 // Uart.state = STATE_MILLER_Z; stay the same
227 // we see a logic '0' }
228 if(Uart.drop == DROP_SECOND_HALF) {
229 // we see a logic '1'
230 Uart.shiftReg |= 0x100;
231 Uart.state = STATE_MILLER_X;
232 }
233 break;
234
235 case STATE_MILLER_X:
236 Uart.shiftReg >>= 1;
237 if(Uart.drop == DROP_NONE) {
238 // sequence Y, we see a '0'
239 Uart.state = STATE_MILLER_Y;
240 Uart.bitCnt++;
241 }
242 if(Uart.drop == DROP_FIRST_HALF) {
243 // Would be STATE_MILLER_Z
244 // but Z does not follow X, so error
245 Uart.state = STATE_ERROR_WAIT;
246 error = 0x03;
247 }
248 if(Uart.drop == DROP_SECOND_HALF) {
249 // We see a '1' and stay in state X
250 Uart.shiftReg |= 0x100;
251 Uart.bitCnt++;
252 }
253 break;
254
255 case STATE_MILLER_Y:
256 Uart.bitCnt++;
257 Uart.shiftReg >>= 1;
258 if(Uart.drop == DROP_NONE) {
259 // logic '0' followed by sequence Y
260 // end of communication
261 Uart.state = STATE_UNSYNCD;
262 EOC = TRUE;
263 }
264 if(Uart.drop == DROP_FIRST_HALF) {
265 // we see a '0'
266 Uart.state = STATE_MILLER_Z;
267 }
268 if(Uart.drop == DROP_SECOND_HALF) {
269 // We see a '1' and go to state X
270 Uart.shiftReg |= 0x100;
271 Uart.state = STATE_MILLER_X;
272 }
273 break;
274
275 case STATE_ERROR_WAIT:
276 // That went wrong. Now wait for at least two bit periods
277 // and try to sync again
278 if(Uart.drop == DROP_NONE) {
279 Uart.highCnt = 6;
280 Uart.state = STATE_UNSYNCD;
281 }
282 break;
283
284 default:
285 Uart.state = STATE_UNSYNCD;
286 Uart.highCnt = 0;
287 break;
288 }
289
290 Uart.drop = DROP_NONE;
291
292 // should have received at least one whole byte...
293 if((Uart.bitCnt == 2) && EOC && (Uart.byteCnt > 0)) {
294 return TRUE;
295 }
296
297 if(Uart.bitCnt == 9) {
298 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
299 Uart.byteCnt++;
300
301 Uart.parityBits <<= 1;
302 Uart.parityBits ^= ((Uart.shiftReg >> 8) & 0x01);
303
304 if(EOC) {
305 // when End of Communication received and
306 // all data bits processed..
307 return TRUE;
308 }
309 Uart.bitCnt = 0;
310 }
311
312 /*if(error) {
313 Uart.output[Uart.byteCnt] = 0xAA;
314 Uart.byteCnt++;
315 Uart.output[Uart.byteCnt] = error & 0xFF;
316 Uart.byteCnt++;
317 Uart.output[Uart.byteCnt] = 0xAA;
318 Uart.byteCnt++;
319 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
320 Uart.byteCnt++;
321 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
322 Uart.byteCnt++;
323 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
324 Uart.byteCnt++;
325 Uart.output[Uart.byteCnt] = 0xAA;
326 Uart.byteCnt++;
327 return TRUE;
328 }*/
329 }
330
331 }
332 else {
333 bit = Uart.bitBuffer & 0xf0;
334 bit >>= 4;
335 bit ^= 0x0F;
336 if(bit) {
337 // should have been high or at least (4 * 128) / fc
338 // according to ISO this should be at least (9 * 128 + 20) / fc
339 if(Uart.highCnt == 8) {
340 // we went low, so this could be start of communication
341 // it turns out to be safer to choose a less significant
342 // syncbit... so we check whether the neighbour also represents the drop
343 Uart.posCnt = 1; // apparently we are busy with our first half bit period
344 Uart.syncBit = bit & 8;
345 Uart.samples = 3;
346 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
347 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
348 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
349 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
350 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
351 if(Uart.syncBit & (Uart.bitBuffer & 8)) {
352 Uart.syncBit = 8;
353
354 // the first half bit period is expected in next sample
355 Uart.posCnt = 0;
356 Uart.samples = 3;
357 }
358 }
359 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
360
361 Uart.syncBit <<= 4;
362 Uart.state = STATE_START_OF_COMMUNICATION;
363 Uart.drop = DROP_FIRST_HALF;
364 Uart.bitCnt = 0;
365 Uart.byteCnt = 0;
366 Uart.parityBits = 0;
367 error = 0;
368 }
369 else {
370 Uart.highCnt = 0;
371 }
372 }
373 else {
374 if(Uart.highCnt < 8) {
375 Uart.highCnt++;
376 }
377 }
378 }
379
380 return FALSE;
381 }
382
383 //=============================================================================
384 // ISO 14443 Type A - Manchester
385 //=============================================================================
386
387 static struct {
388 enum {
389 DEMOD_UNSYNCD,
390 DEMOD_START_OF_COMMUNICATION,
391 DEMOD_MANCHESTER_D,
392 DEMOD_MANCHESTER_E,
393 DEMOD_MANCHESTER_F,
394 DEMOD_ERROR_WAIT
395 } state;
396 int bitCount;
397 int posCount;
398 int syncBit;
399 int parityBits;
400 uint16_t shiftReg;
401 int buffer;
402 int buff;
403 int samples;
404 int len;
405 enum {
406 SUB_NONE,
407 SUB_FIRST_HALF,
408 SUB_SECOND_HALF
409 } sub;
410 uint8_t *output;
411 } Demod;
412
413 static RAMFUNC int ManchesterDecoding(int v)
414 {
415 int bit;
416 int modulation;
417 int error = 0;
418
419 if(!Demod.buff) {
420 Demod.buff = 1;
421 Demod.buffer = v;
422 return FALSE;
423 }
424 else {
425 bit = Demod.buffer;
426 Demod.buffer = v;
427 }
428
429 if(Demod.state==DEMOD_UNSYNCD) {
430 Demod.output[Demod.len] = 0xfa;
431 Demod.syncBit = 0;
432 //Demod.samples = 0;
433 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
434 if(bit & 0x08) { Demod.syncBit = 0x08; }
435 if(!Demod.syncBit) {
436 if(bit & 0x04) { Demod.syncBit = 0x04; }
437 }
438 else if(bit & 0x04) { Demod.syncBit = 0x04; bit <<= 4; }
439 if(!Demod.syncBit) {
440 if(bit & 0x02) { Demod.syncBit = 0x02; }
441 }
442 else if(bit & 0x02) { Demod.syncBit = 0x02; bit <<= 4; }
443 if(!Demod.syncBit) {
444 if(bit & 0x01) { Demod.syncBit = 0x01; }
445
446 if(Demod.syncBit & (Demod.buffer & 0x08)) {
447 Demod.syncBit = 0x08;
448
449 // The first half bitperiod is expected in next sample
450 Demod.posCount = 0;
451 Demod.output[Demod.len] = 0xfb;
452 }
453 }
454 else if(bit & 0x01) { Demod.syncBit = 0x01; }
455
456 if(Demod.syncBit) {
457 Demod.len = 0;
458 Demod.state = DEMOD_START_OF_COMMUNICATION;
459 Demod.sub = SUB_FIRST_HALF;
460 Demod.bitCount = 0;
461 Demod.shiftReg = 0;
462 Demod.parityBits = 0;
463 Demod.samples = 0;
464 if(Demod.posCount) {
465 if(trigger) LED_A_OFF();
466 switch(Demod.syncBit) {
467 case 0x08: Demod.samples = 3; break;
468 case 0x04: Demod.samples = 2; break;
469 case 0x02: Demod.samples = 1; break;
470 case 0x01: Demod.samples = 0; break;
471 }
472 }
473 error = 0;
474 }
475 }
476 else {
477 //modulation = bit & Demod.syncBit;
478 modulation = ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
479
480 Demod.samples += 4;
481
482 if(Demod.posCount==0) {
483 Demod.posCount = 1;
484 if(modulation) {
485 Demod.sub = SUB_FIRST_HALF;
486 }
487 else {
488 Demod.sub = SUB_NONE;
489 }
490 }
491 else {
492 Demod.posCount = 0;
493 if(modulation && (Demod.sub == SUB_FIRST_HALF)) {
494 if(Demod.state!=DEMOD_ERROR_WAIT) {
495 Demod.state = DEMOD_ERROR_WAIT;
496 Demod.output[Demod.len] = 0xaa;
497 error = 0x01;
498 }
499 }
500 else if(modulation) {
501 Demod.sub = SUB_SECOND_HALF;
502 }
503
504 switch(Demod.state) {
505 case DEMOD_START_OF_COMMUNICATION:
506 if(Demod.sub == SUB_FIRST_HALF) {
507 Demod.state = DEMOD_MANCHESTER_D;
508 }
509 else {
510 Demod.output[Demod.len] = 0xab;
511 Demod.state = DEMOD_ERROR_WAIT;
512 error = 0x02;
513 }
514 break;
515
516 case DEMOD_MANCHESTER_D:
517 case DEMOD_MANCHESTER_E:
518 if(Demod.sub == SUB_FIRST_HALF) {
519 Demod.bitCount++;
520 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
521 Demod.state = DEMOD_MANCHESTER_D;
522 }
523 else if(Demod.sub == SUB_SECOND_HALF) {
524 Demod.bitCount++;
525 Demod.shiftReg >>= 1;
526 Demod.state = DEMOD_MANCHESTER_E;
527 }
528 else {
529 Demod.state = DEMOD_MANCHESTER_F;
530 }
531 break;
532
533 case DEMOD_MANCHESTER_F:
534 // Tag response does not need to be a complete byte!
535 if(Demod.len > 0 || Demod.bitCount > 0) {
536 if(Demod.bitCount > 0) {
537 Demod.shiftReg >>= (9 - Demod.bitCount);
538 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
539 Demod.len++;
540 // No parity bit, so just shift a 0
541 Demod.parityBits <<= 1;
542 }
543
544 Demod.state = DEMOD_UNSYNCD;
545 return TRUE;
546 }
547 else {
548 Demod.output[Demod.len] = 0xad;
549 Demod.state = DEMOD_ERROR_WAIT;
550 error = 0x03;
551 }
552 break;
553
554 case DEMOD_ERROR_WAIT:
555 Demod.state = DEMOD_UNSYNCD;
556 break;
557
558 default:
559 Demod.output[Demod.len] = 0xdd;
560 Demod.state = DEMOD_UNSYNCD;
561 break;
562 }
563
564 if(Demod.bitCount>=9) {
565 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
566 Demod.len++;
567
568 Demod.parityBits <<= 1;
569 Demod.parityBits ^= ((Demod.shiftReg >> 8) & 0x01);
570
571 Demod.bitCount = 0;
572 Demod.shiftReg = 0;
573 }
574
575 /*if(error) {
576 Demod.output[Demod.len] = 0xBB;
577 Demod.len++;
578 Demod.output[Demod.len] = error & 0xFF;
579 Demod.len++;
580 Demod.output[Demod.len] = 0xBB;
581 Demod.len++;
582 Demod.output[Demod.len] = bit & 0xFF;
583 Demod.len++;
584 Demod.output[Demod.len] = Demod.buffer & 0xFF;
585 Demod.len++;
586 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
587 Demod.len++;
588 Demod.output[Demod.len] = 0xBB;
589 Demod.len++;
590 return TRUE;
591 }*/
592
593 }
594
595 } // end (state != UNSYNCED)
596
597 return FALSE;
598 }
599
600 //=============================================================================
601 // Finally, a `sniffer' for ISO 14443 Type A
602 // Both sides of communication!
603 //=============================================================================
604
605 //-----------------------------------------------------------------------------
606 // Record the sequence of commands sent by the reader to the tag, with
607 // triggering so that we start recording at the point that the tag is moved
608 // near the reader.
609 //-----------------------------------------------------------------------------
610 void RAMFUNC SnoopIso14443a(void)
611 {
612 // #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
613 // #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
614 // #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
615 // #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
616 // #define TRACE_LENGTH 2000 // original (working as of 21/2/09) values
617
618 // We won't start recording the frames that we acquire until we trigger;
619 // a good trigger condition to get started is probably when we see a
620 // response from the tag.
621 int triggered = FALSE; // FALSE to wait first for card
622
623 // The command (reader -> tag) that we're receiving.
624 // The length of a received command will in most cases be no more than 18 bytes.
625 // So 32 should be enough!
626 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
627 // The response (tag -> reader) that we're receiving.
628 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
629
630 // As we receive stuff, we copy it from receivedCmd or receivedResponse
631 // into trace, along with its length and other annotations.
632 //uint8_t *trace = (uint8_t *)BigBuf;
633
634 traceLen = 0; // uncommented to fix ISSUE 15 - gerhard - jan2011
635
636 // The DMA buffer, used to stream samples from the FPGA
637 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
638 int lastRxCounter;
639 int8_t *upTo;
640 int smpl;
641 int maxBehindBy = 0;
642
643 // Count of samples received so far, so that we can include timing
644 // information in the trace buffer.
645 int samples = 0;
646 int rsamples = 0;
647
648 memset(trace, 0x44, RECV_CMD_OFFSET);
649
650 // Set up the demodulator for tag -> reader responses.
651 Demod.output = receivedResponse;
652 Demod.len = 0;
653 Demod.state = DEMOD_UNSYNCD;
654
655 // Setup for the DMA.
656 FpgaSetupSsc();
657 upTo = dmaBuf;
658 lastRxCounter = DMA_BUFFER_SIZE;
659 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
660
661 // And the reader -> tag commands
662 memset(&Uart, 0, sizeof(Uart));
663 Uart.output = receivedCmd;
664 Uart.byteCntMax = 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
665 Uart.state = STATE_UNSYNCD;
666
667 // And put the FPGA in the appropriate mode
668 // Signal field is off with the appropriate LED
669 LED_D_OFF();
670 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
671 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
672
673
674 // And now we loop, receiving samples.
675 for(;;) {
676 LED_A_ON();
677 WDT_HIT();
678 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
679 (DMA_BUFFER_SIZE-1);
680 if(behindBy > maxBehindBy) {
681 maxBehindBy = behindBy;
682 if(behindBy > 400) {
683 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
684 goto done;
685 }
686 }
687 if(behindBy < 1) continue;
688
689 LED_A_OFF();
690 smpl = upTo[0];
691 upTo++;
692 lastRxCounter -= 1;
693 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
694 upTo -= DMA_BUFFER_SIZE;
695 lastRxCounter += DMA_BUFFER_SIZE;
696 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
697 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
698 }
699
700 samples += 4;
701 if(MillerDecoding((smpl & 0xF0) >> 4)) {
702 rsamples = samples - Uart.samples;
703 LED_C_ON();
704 if(triggered) {
705 trace[traceLen++] = ((rsamples >> 0) & 0xff);
706 trace[traceLen++] = ((rsamples >> 8) & 0xff);
707 trace[traceLen++] = ((rsamples >> 16) & 0xff);
708 trace[traceLen++] = ((rsamples >> 24) & 0xff);
709 trace[traceLen++] = ((Uart.parityBits >> 0) & 0xff);
710 trace[traceLen++] = ((Uart.parityBits >> 8) & 0xff);
711 trace[traceLen++] = ((Uart.parityBits >> 16) & 0xff);
712 trace[traceLen++] = ((Uart.parityBits >> 24) & 0xff);
713 trace[traceLen++] = Uart.byteCnt;
714 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt);
715 traceLen += Uart.byteCnt;
716 if(traceLen > TRACE_LENGTH) break;
717 }
718 /* And ready to receive another command. */
719 Uart.state = STATE_UNSYNCD;
720 /* And also reset the demod code, which might have been */
721 /* false-triggered by the commands from the reader. */
722 Demod.state = DEMOD_UNSYNCD;
723 LED_B_OFF();
724 }
725
726 if(ManchesterDecoding(smpl & 0x0F)) {
727 rsamples = samples - Demod.samples;
728 LED_B_ON();
729
730 // timestamp, as a count of samples
731 trace[traceLen++] = ((rsamples >> 0) & 0xff);
732 trace[traceLen++] = ((rsamples >> 8) & 0xff);
733 trace[traceLen++] = ((rsamples >> 16) & 0xff);
734 trace[traceLen++] = 0x80 | ((rsamples >> 24) & 0xff);
735 trace[traceLen++] = ((Demod.parityBits >> 0) & 0xff);
736 trace[traceLen++] = ((Demod.parityBits >> 8) & 0xff);
737 trace[traceLen++] = ((Demod.parityBits >> 16) & 0xff);
738 trace[traceLen++] = ((Demod.parityBits >> 24) & 0xff);
739 // length
740 trace[traceLen++] = Demod.len;
741 memcpy(trace+traceLen, receivedResponse, Demod.len);
742 traceLen += Demod.len;
743 if(traceLen > TRACE_LENGTH) break;
744
745 triggered = TRUE;
746
747 // And ready to receive another response.
748 memset(&Demod, 0, sizeof(Demod));
749 Demod.output = receivedResponse;
750 Demod.state = DEMOD_UNSYNCD;
751 LED_C_OFF();
752 }
753
754 if(BUTTON_PRESS()) {
755 DbpString("cancelled_a");
756 goto done;
757 }
758 }
759
760 DbpString("COMMAND FINISHED");
761
762 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
763 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
764
765 done:
766 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
767 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
768 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
769 LED_A_OFF();
770 LED_B_OFF();
771 LED_C_OFF();
772 LED_D_OFF();
773 }
774
775 //-----------------------------------------------------------------------------
776 // Prepare tag messages
777 //-----------------------------------------------------------------------------
778 static void CodeIso14443aAsTag(const uint8_t *cmd, int len)
779 {
780 int i;
781 int oddparity;
782
783 ToSendReset();
784
785 // Correction bit, might be removed when not needed
786 ToSendStuffBit(0);
787 ToSendStuffBit(0);
788 ToSendStuffBit(0);
789 ToSendStuffBit(0);
790 ToSendStuffBit(1); // 1
791 ToSendStuffBit(0);
792 ToSendStuffBit(0);
793 ToSendStuffBit(0);
794
795 // Send startbit
796 ToSend[++ToSendMax] = SEC_D;
797
798 for(i = 0; i < len; i++) {
799 int j;
800 uint8_t b = cmd[i];
801
802 // Data bits
803 oddparity = 0x01;
804 for(j = 0; j < 8; j++) {
805 oddparity ^= (b & 1);
806 if(b & 1) {
807 ToSend[++ToSendMax] = SEC_D;
808 } else {
809 ToSend[++ToSendMax] = SEC_E;
810 }
811 b >>= 1;
812 }
813
814 // Parity bit
815 if(oddparity) {
816 ToSend[++ToSendMax] = SEC_D;
817 } else {
818 ToSend[++ToSendMax] = SEC_E;
819 }
820 }
821
822 // Send stopbit
823 ToSend[++ToSendMax] = SEC_F;
824
825 // Flush the buffer in FPGA!!
826 for(i = 0; i < 5; i++) {
827 ToSend[++ToSendMax] = SEC_F;
828 }
829
830 // Convert from last byte pos to length
831 ToSendMax++;
832
833 // Add a few more for slop
834 ToSend[ToSendMax++] = 0x00;
835 ToSend[ToSendMax++] = 0x00;
836 //ToSendMax += 2;
837 }
838
839 //-----------------------------------------------------------------------------
840 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
841 //-----------------------------------------------------------------------------
842 static void CodeStrangeAnswer()
843 {
844 int i;
845
846 ToSendReset();
847
848 // Correction bit, might be removed when not needed
849 ToSendStuffBit(0);
850 ToSendStuffBit(0);
851 ToSendStuffBit(0);
852 ToSendStuffBit(0);
853 ToSendStuffBit(1); // 1
854 ToSendStuffBit(0);
855 ToSendStuffBit(0);
856 ToSendStuffBit(0);
857
858 // Send startbit
859 ToSend[++ToSendMax] = SEC_D;
860
861 // 0
862 ToSend[++ToSendMax] = SEC_E;
863
864 // 0
865 ToSend[++ToSendMax] = SEC_E;
866
867 // 1
868 ToSend[++ToSendMax] = SEC_D;
869
870 // Send stopbit
871 ToSend[++ToSendMax] = SEC_F;
872
873 // Flush the buffer in FPGA!!
874 for(i = 0; i < 5; i++) {
875 ToSend[++ToSendMax] = SEC_F;
876 }
877
878 // Convert from last byte pos to length
879 ToSendMax++;
880
881 // Add a few more for slop
882 ToSend[ToSendMax++] = 0x00;
883 ToSend[ToSendMax++] = 0x00;
884 //ToSendMax += 2;
885 }
886
887 //-----------------------------------------------------------------------------
888 // Wait for commands from reader
889 // Stop when button is pressed
890 // Or return TRUE when command is captured
891 //-----------------------------------------------------------------------------
892 static int GetIso14443aCommandFromReader(uint8_t *received, int *len, int maxLen)
893 {
894 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
895 // only, since we are receiving, not transmitting).
896 // Signal field is off with the appropriate LED
897 LED_D_OFF();
898 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
899
900 // Now run a `software UART' on the stream of incoming samples.
901 Uart.output = received;
902 Uart.byteCntMax = maxLen;
903 Uart.state = STATE_UNSYNCD;
904
905 for(;;) {
906 WDT_HIT();
907
908 if(BUTTON_PRESS()) return FALSE;
909
910 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
911 AT91C_BASE_SSC->SSC_THR = 0x00;
912 }
913 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
914 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
915 if(MillerDecoding((b & 0xf0) >> 4)) {
916 *len = Uart.byteCnt;
917 return TRUE;
918 }
919 if(MillerDecoding(b & 0x0f)) {
920 *len = Uart.byteCnt;
921 return TRUE;
922 }
923 }
924 }
925 }
926
927 //-----------------------------------------------------------------------------
928 // Main loop of simulated tag: receive commands from reader, decide what
929 // response to send, and send it.
930 //-----------------------------------------------------------------------------
931 void SimulateIso14443aTag(int tagType, int TagUid)
932 {
933 // This function contains the tag emulation
934
935 // Prepare protocol messages
936 // static const uint8_t cmd1[] = { 0x26 };
937 // static const uint8_t response1[] = { 0x02, 0x00 }; // Says: I am Mifare 4k - original line - greg
938 //
939 static const uint8_t response1[] = { 0x44, 0x03 }; // Says: I am a DESFire Tag, ph33r me
940 // static const uint8_t response1[] = { 0x44, 0x00 }; // Says: I am a ULTRALITE Tag, 0wn me
941
942 // UID response
943 // static const uint8_t cmd2[] = { 0x93, 0x20 };
944 //static const uint8_t response2[] = { 0x9a, 0xe5, 0xe4, 0x43, 0xd8 }; // original value - greg
945
946 // my desfire
947 static const uint8_t response2[] = { 0x88, 0x04, 0x21, 0x3f, 0x4d }; // known uid - note cascade (0x88), 2nd byte (0x04) = NXP/Phillips
948
949
950 // When reader selects us during cascade1 it will send cmd3
951 //uint8_t response3[] = { 0x04, 0x00, 0x00 }; // SAK Select (cascade1) successful response (ULTRALITE)
952 uint8_t response3[] = { 0x24, 0x00, 0x00 }; // SAK Select (cascade1) successful response (DESFire)
953 ComputeCrc14443(CRC_14443_A, response3, 1, &response3[1], &response3[2]);
954
955 // send cascade2 2nd half of UID
956 static const uint8_t response2a[] = { 0x51, 0x48, 0x1d, 0x80, 0x84 }; // uid - cascade2 - 2nd half (4 bytes) of UID+ BCCheck
957 // NOTE : THE CRC on the above may be wrong as I have obfuscated the actual UID
958
959 // When reader selects us during cascade2 it will send cmd3a
960 //uint8_t response3a[] = { 0x00, 0x00, 0x00 }; // SAK Select (cascade2) successful response (ULTRALITE)
961 uint8_t response3a[] = { 0x20, 0x00, 0x00 }; // SAK Select (cascade2) successful response (DESFire)
962 ComputeCrc14443(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]);
963
964 static const uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
965
966 uint8_t *resp;
967 int respLen;
968
969 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
970 // This will need
971 // 144 data bits (18 * 8)
972 // 18 parity bits
973 // 2 Start and stop
974 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
975 // 1 just for the case
976 // ----------- +
977 // 166
978 //
979 // 166 bytes, since every bit that needs to be send costs us a byte
980 //
981
982 // Respond with card type
983 uint8_t *resp1 = (((uint8_t *)BigBuf) + 800);
984 int resp1Len;
985
986 // Anticollision cascade1 - respond with uid
987 uint8_t *resp2 = (((uint8_t *)BigBuf) + 970);
988 int resp2Len;
989
990 // Anticollision cascade2 - respond with 2nd half of uid if asked
991 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
992 uint8_t *resp2a = (((uint8_t *)BigBuf) + 1140);
993 int resp2aLen;
994
995 // Acknowledge select - cascade 1
996 uint8_t *resp3 = (((uint8_t *)BigBuf) + 1310);
997 int resp3Len;
998
999 // Acknowledge select - cascade 2
1000 uint8_t *resp3a = (((uint8_t *)BigBuf) + 1480);
1001 int resp3aLen;
1002
1003 // Response to a read request - not implemented atm
1004 uint8_t *resp4 = (((uint8_t *)BigBuf) + 1550);
1005 int resp4Len;
1006
1007 // Authenticate response - nonce
1008 uint8_t *resp5 = (((uint8_t *)BigBuf) + 1720);
1009 int resp5Len;
1010
1011 uint8_t *receivedCmd = (uint8_t *)BigBuf;
1012 int len;
1013
1014 int i;
1015 int u;
1016 uint8_t b;
1017
1018 // To control where we are in the protocol
1019 int order = 0;
1020 int lastorder;
1021
1022 // Just to allow some checks
1023 int happened = 0;
1024 int happened2 = 0;
1025
1026 int cmdsRecvd = 0;
1027
1028 int fdt_indicator;
1029
1030 memset(receivedCmd, 0x44, 400);
1031
1032 // Prepare the responses of the anticollision phase
1033 // there will be not enough time to do this at the moment the reader sends it REQA
1034
1035 // Answer to request
1036 CodeIso14443aAsTag(response1, sizeof(response1));
1037 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
1038
1039 // Send our UID (cascade 1)
1040 CodeIso14443aAsTag(response2, sizeof(response2));
1041 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
1042
1043 // Answer to select (cascade1)
1044 CodeIso14443aAsTag(response3, sizeof(response3));
1045 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
1046
1047 // Send the cascade 2 2nd part of the uid
1048 CodeIso14443aAsTag(response2a, sizeof(response2a));
1049 memcpy(resp2a, ToSend, ToSendMax); resp2aLen = ToSendMax;
1050
1051 // Answer to select (cascade 2)
1052 CodeIso14443aAsTag(response3a, sizeof(response3a));
1053 memcpy(resp3a, ToSend, ToSendMax); resp3aLen = ToSendMax;
1054
1055 // Strange answer is an example of rare message size (3 bits)
1056 CodeStrangeAnswer();
1057 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1058
1059 // Authentication answer (random nonce)
1060 CodeIso14443aAsTag(response5, sizeof(response5));
1061 memcpy(resp5, ToSend, ToSendMax); resp5Len = ToSendMax;
1062
1063 // We need to listen to the high-frequency, peak-detected path.
1064 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1065 FpgaSetupSsc();
1066
1067 cmdsRecvd = 0;
1068
1069 LED_A_ON();
1070 for(;;) {
1071
1072 if(!GetIso14443aCommandFromReader(receivedCmd, &len, 100)) {
1073 DbpString("button press");
1074 break;
1075 }
1076 // doob - added loads of debug strings so we can see what the reader is saying to us during the sim as hi14alist is not populated
1077 // Okay, look at the command now.
1078 lastorder = order;
1079 i = 1; // first byte transmitted
1080 if(receivedCmd[0] == 0x26) {
1081 // Received a REQUEST
1082 resp = resp1; respLen = resp1Len; order = 1;
1083 //DbpString("Hello request from reader:");
1084 } else if(receivedCmd[0] == 0x52) {
1085 // Received a WAKEUP
1086 resp = resp1; respLen = resp1Len; order = 6;
1087 // //DbpString("Wakeup request from reader:");
1088
1089 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // greg - cascade 1 anti-collision
1090 // Received request for UID (cascade 1)
1091 resp = resp2; respLen = resp2Len; order = 2;
1092 // DbpString("UID (cascade 1) request from reader:");
1093 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1094
1095
1096 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] ==0x95) { // greg - cascade 2 anti-collision
1097 // Received request for UID (cascade 2)
1098 resp = resp2a; respLen = resp2aLen; order = 20;
1099 // DbpString("UID (cascade 2) request from reader:");
1100 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1101
1102
1103 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] ==0x93) { // greg - cascade 1 select
1104 // Received a SELECT
1105 resp = resp3; respLen = resp3Len; order = 3;
1106 // DbpString("Select (cascade 1) request from reader:");
1107 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1108
1109
1110 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] ==0x95) { // greg - cascade 2 select
1111 // Received a SELECT
1112 resp = resp3a; respLen = resp3aLen; order = 30;
1113 // DbpString("Select (cascade 2) request from reader:");
1114 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1115
1116
1117 } else if(receivedCmd[0] == 0x30) {
1118 // Received a READ
1119 resp = resp4; respLen = resp4Len; order = 4; // Do nothing
1120 Dbprintf("Read request from reader: %x %x %x",
1121 receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1122
1123
1124 } else if(receivedCmd[0] == 0x50) {
1125 // Received a HALT
1126 resp = resp1; respLen = 0; order = 5; // Do nothing
1127 DbpString("Reader requested we HALT!:");
1128
1129 } else if(receivedCmd[0] == 0x60) {
1130 // Received an authentication request
1131 resp = resp5; respLen = resp5Len; order = 7;
1132 Dbprintf("Authenticate request from reader: %x %x %x",
1133 receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1134
1135 } else if(receivedCmd[0] == 0xE0) {
1136 // Received a RATS request
1137 resp = resp1; respLen = 0;order = 70;
1138 Dbprintf("RATS request from reader: %x %x %x",
1139 receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1140 } else {
1141 // Never seen this command before
1142 Dbprintf("Unknown command received from reader: %x %x %x %x %x %x %x %x %x",
1143 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1144 receivedCmd[3], receivedCmd[3], receivedCmd[4],
1145 receivedCmd[5], receivedCmd[6], receivedCmd[7]);
1146 // Do not respond
1147 resp = resp1; respLen = 0; order = 0;
1148 }
1149
1150 // Count number of wakeups received after a halt
1151 if(order == 6 && lastorder == 5) { happened++; }
1152
1153 // Count number of other messages after a halt
1154 if(order != 6 && lastorder == 5) { happened2++; }
1155
1156 // Look at last parity bit to determine timing of answer
1157 if((Uart.parityBits & 0x01) || receivedCmd[0] == 0x52) {
1158 // 1236, so correction bit needed
1159 i = 0;
1160 }
1161
1162 memset(receivedCmd, 0x44, 32);
1163
1164 if(cmdsRecvd > 999) {
1165 DbpString("1000 commands later...");
1166 break;
1167 }
1168 else {
1169 cmdsRecvd++;
1170 }
1171
1172 if(respLen <= 0) continue;
1173
1174 // Modulate Manchester
1175 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1176 AT91C_BASE_SSC->SSC_THR = 0x00;
1177 FpgaSetupSsc();
1178
1179 // ### Transmit the response ###
1180 u = 0;
1181 b = 0x00;
1182 fdt_indicator = FALSE;
1183 for(;;) {
1184 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1185 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1186 (void)b;
1187 }
1188 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1189 if(i > respLen) {
1190 b = 0x00;
1191 u++;
1192 } else {
1193 b = resp[i];
1194 i++;
1195 }
1196 AT91C_BASE_SSC->SSC_THR = b;
1197
1198 if(u > 4) {
1199 break;
1200 }
1201 }
1202 if(BUTTON_PRESS()) {
1203 break;
1204 }
1205 }
1206
1207 }
1208
1209 Dbprintf("%x %x %x", happened, happened2, cmdsRecvd);
1210 LED_A_OFF();
1211 }
1212
1213 //-----------------------------------------------------------------------------
1214 // Transmit the command (to the tag) that was placed in ToSend[].
1215 //-----------------------------------------------------------------------------
1216 static void TransmitFor14443a(const uint8_t *cmd, int len, int *samples, int *wait)
1217 {
1218 int c;
1219
1220 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1221
1222 if (wait)
1223 if(*wait < 10)
1224 *wait = 10;
1225
1226 for(c = 0; c < *wait;) {
1227 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1228 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1229 c++;
1230 }
1231 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1232 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1233 (void)r;
1234 }
1235 WDT_HIT();
1236 }
1237
1238 c = 0;
1239 for(;;) {
1240 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1241 AT91C_BASE_SSC->SSC_THR = cmd[c];
1242 c++;
1243 if(c >= len) {
1244 break;
1245 }
1246 }
1247 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1248 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1249 (void)r;
1250 }
1251 WDT_HIT();
1252 }
1253 if (samples) *samples = (c + *wait) << 3;
1254 }
1255
1256 //-----------------------------------------------------------------------------
1257 // Code a 7-bit command without parity bit
1258 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1259 //-----------------------------------------------------------------------------
1260 void ShortFrameFromReader(const uint8_t bt)
1261 {
1262 int j;
1263 int last;
1264 uint8_t b;
1265
1266 ToSendReset();
1267
1268 // Start of Communication (Seq. Z)
1269 ToSend[++ToSendMax] = SEC_Z;
1270 last = 0;
1271
1272 b = bt;
1273 for(j = 0; j < 7; j++) {
1274 if(b & 1) {
1275 // Sequence X
1276 ToSend[++ToSendMax] = SEC_X;
1277 last = 1;
1278 } else {
1279 if(last == 0) {
1280 // Sequence Z
1281 ToSend[++ToSendMax] = SEC_Z;
1282 }
1283 else {
1284 // Sequence Y
1285 ToSend[++ToSendMax] = SEC_Y;
1286 last = 0;
1287 }
1288 }
1289 b >>= 1;
1290 }
1291
1292 // End of Communication
1293 if(last == 0) {
1294 // Sequence Z
1295 ToSend[++ToSendMax] = SEC_Z;
1296 }
1297 else {
1298 // Sequence Y
1299 ToSend[++ToSendMax] = SEC_Y;
1300 last = 0;
1301 }
1302 // Sequence Y
1303 ToSend[++ToSendMax] = SEC_Y;
1304
1305 // Just to be sure!
1306 ToSend[++ToSendMax] = SEC_Y;
1307 ToSend[++ToSendMax] = SEC_Y;
1308 ToSend[++ToSendMax] = SEC_Y;
1309
1310 // Convert from last character reference to length
1311 ToSendMax++;
1312 }
1313
1314 //-----------------------------------------------------------------------------
1315 // Prepare reader command to send to FPGA
1316 //
1317 //-----------------------------------------------------------------------------
1318 void CodeIso14443aAsReaderPar(const uint8_t * cmd, int len, uint32_t dwParity)
1319 {
1320 int i, j;
1321 int last;
1322 uint8_t b;
1323
1324 ToSendReset();
1325
1326 // Start of Communication (Seq. Z)
1327 ToSend[++ToSendMax] = SEC_Z;
1328 last = 0;
1329
1330 // Generate send structure for the data bits
1331 for (i = 0; i < len; i++) {
1332 // Get the current byte to send
1333 b = cmd[i];
1334
1335 for (j = 0; j < 8; j++) {
1336 if (b & 1) {
1337 // Sequence X
1338 ToSend[++ToSendMax] = SEC_X;
1339 last = 1;
1340 } else {
1341 if (last == 0) {
1342 // Sequence Z
1343 ToSend[++ToSendMax] = SEC_Z;
1344 } else {
1345 // Sequence Y
1346 ToSend[++ToSendMax] = SEC_Y;
1347 last = 0;
1348 }
1349 }
1350 b >>= 1;
1351 }
1352
1353 // Get the parity bit
1354 if ((dwParity >> i) & 0x01) {
1355 // Sequence X
1356 ToSend[++ToSendMax] = SEC_X;
1357 last = 1;
1358 } else {
1359 if (last == 0) {
1360 // Sequence Z
1361 ToSend[++ToSendMax] = SEC_Z;
1362 } else {
1363 // Sequence Y
1364 ToSend[++ToSendMax] = SEC_Y;
1365 last = 0;
1366 }
1367 }
1368 }
1369
1370 // End of Communication
1371 if (last == 0) {
1372 // Sequence Z
1373 ToSend[++ToSendMax] = SEC_Z;
1374 } else {
1375 // Sequence Y
1376 ToSend[++ToSendMax] = SEC_Y;
1377 last = 0;
1378 }
1379 // Sequence Y
1380 ToSend[++ToSendMax] = SEC_Y;
1381
1382 // Just to be sure!
1383 ToSend[++ToSendMax] = SEC_Y;
1384 ToSend[++ToSendMax] = SEC_Y;
1385 ToSend[++ToSendMax] = SEC_Y;
1386
1387 // Convert from last character reference to length
1388 ToSendMax++;
1389 }
1390
1391 //-----------------------------------------------------------------------------
1392 // Wait a certain time for tag response
1393 // If a response is captured return TRUE
1394 // If it takes to long return FALSE
1395 //-----------------------------------------------------------------------------
1396 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
1397 {
1398 // buffer needs to be 512 bytes
1399 int c;
1400
1401 // Set FPGA mode to "reader listen mode", no modulation (listen
1402 // only, since we are receiving, not transmitting).
1403 // Signal field is on with the appropriate LED
1404 LED_D_ON();
1405 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1406
1407 // Now get the answer from the card
1408 Demod.output = receivedResponse;
1409 Demod.len = 0;
1410 Demod.state = DEMOD_UNSYNCD;
1411
1412 uint8_t b;
1413 if (elapsed) *elapsed = 0;
1414
1415 c = 0;
1416 for(;;) {
1417 WDT_HIT();
1418
1419 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1420 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1421 if (elapsed) (*elapsed)++;
1422 }
1423 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1424 if(c < iso14a_timeout) { c++; } else { return FALSE; }
1425 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1426 if(ManchesterDecoding((b>>4) & 0xf)) {
1427 *samples = ((c - 1) << 3) + 4;
1428 return TRUE;
1429 }
1430 if(ManchesterDecoding(b & 0x0f)) {
1431 *samples = c << 3;
1432 return TRUE;
1433 }
1434 }
1435 }
1436 }
1437
1438 void ReaderTransmitShort(const uint8_t* bt)
1439 {
1440 int wait = 0;
1441 int samples = 0;
1442
1443 ShortFrameFromReader(*bt);
1444
1445 // Select the card
1446 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
1447
1448 // Store reader command in buffer
1449 if (tracing) LogTrace(bt,1,0,GetParity(bt,1),TRUE);
1450 }
1451
1452 void ReaderTransmitPar(uint8_t* frame, int len, uint32_t par)
1453 {
1454 int wait = 0;
1455 int samples = 0;
1456
1457 // This is tied to other size changes
1458 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1459 CodeIso14443aAsReaderPar(frame,len,par);
1460
1461 // Select the card
1462 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
1463 if(trigger)
1464 LED_A_ON();
1465
1466 // Store reader command in buffer
1467 if (tracing) LogTrace(frame,len,0,par,TRUE);
1468 }
1469
1470
1471 void ReaderTransmit(uint8_t* frame, int len)
1472 {
1473 // Generate parity and redirect
1474 ReaderTransmitPar(frame,len,GetParity(frame,len));
1475 }
1476
1477 int ReaderReceive(uint8_t* receivedAnswer)
1478 {
1479 int samples = 0;
1480 if (!GetIso14443aAnswerFromTag(receivedAnswer,100,&samples,0)) return FALSE;
1481 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1482 if(samples == 0) return FALSE;
1483 return Demod.len;
1484 }
1485
1486 /* performs iso14443a anticolision procedure
1487 * fills the uid pointer unless NULL
1488 * fills resp_data unless NULL */
1489 int iso14443a_select_card(uint8_t * uid_ptr, iso14a_card_select_t * resp_data) {
1490 uint8_t wupa[] = { 0x52 };
1491 uint8_t sel_all[] = { 0x93,0x20 };
1492 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1493 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1494
1495 uint8_t* resp = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1496 uint8_t* uid = resp + 7;
1497
1498 uint8_t sak = 0x04; // cascade uid
1499 int cascade_level = 0;
1500
1501 int len;
1502
1503 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1504 ReaderTransmitShort(wupa);
1505 // Receive the ATQA
1506 if(!ReaderReceive(resp)) return 0;
1507
1508 if(resp_data)
1509 memcpy(resp_data->atqa, resp, 2);
1510
1511 ReaderTransmit(sel_all,sizeof(sel_all));
1512 if(!ReaderReceive(uid)) return 0;
1513
1514 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1515 // which case we need to make a cascade 2 request and select - this is a long UID
1516 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1517 for(; sak & 0x04; cascade_level++)
1518 {
1519 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1520 sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
1521
1522 // SELECT_ALL
1523 ReaderTransmit(sel_all,sizeof(sel_all));
1524 if (!ReaderReceive(resp)) return 0;
1525 if(uid_ptr) memcpy(uid_ptr + cascade_level*4, resp, 4);
1526
1527 // Construct SELECT UID command
1528 memcpy(sel_uid+2,resp,5);
1529 AppendCrc14443a(sel_uid,7);
1530 ReaderTransmit(sel_uid,sizeof(sel_uid));
1531
1532 // Receive the SAK
1533 if (!ReaderReceive(resp)) return 0;
1534 sak = resp[0];
1535 }
1536 if(resp_data) {
1537 resp_data->sak = sak;
1538 resp_data->ats_len = 0;
1539 }
1540
1541 if( (sak & 0x20) == 0)
1542 return 2; // non iso14443a compliant tag
1543
1544 // Request for answer to select
1545 AppendCrc14443a(rats, 2);
1546 ReaderTransmit(rats, sizeof(rats));
1547 if (!(len = ReaderReceive(resp))) return 0;
1548 if(resp_data) {
1549 memcpy(resp_data->ats, resp, sizeof(resp_data->ats));
1550 resp_data->ats_len = len;
1551 }
1552
1553 return 1;
1554 }
1555
1556 void iso14443a_setup() {
1557 // Setup SSC
1558 FpgaSetupSsc();
1559 // Start from off (no field generated)
1560 // Signal field is off with the appropriate LED
1561 LED_D_OFF();
1562 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1563 SpinDelay(200);
1564
1565 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1566
1567 // Now give it time to spin up.
1568 // Signal field is on with the appropriate LED
1569 LED_D_ON();
1570 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1571 SpinDelay(200);
1572
1573 iso14a_timeout = 2048; //default
1574 }
1575
1576 int iso14_apdu(uint8_t * cmd, size_t cmd_len, void * data) {
1577 uint8_t real_cmd[cmd_len+4];
1578 real_cmd[0] = 0x0a; //I-Block
1579 real_cmd[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1580 memcpy(real_cmd+2, cmd, cmd_len);
1581 AppendCrc14443a(real_cmd,cmd_len+2);
1582
1583 ReaderTransmit(real_cmd, cmd_len+4);
1584 size_t len = ReaderReceive(data);
1585 if(!len)
1586 return -1; //DATA LINK ERROR
1587
1588 return len;
1589 }
1590
1591
1592 //-----------------------------------------------------------------------------
1593 // Read an ISO 14443a tag. Send out commands and store answers.
1594 //
1595 //-----------------------------------------------------------------------------
1596 void ReaderIso14443a(UsbCommand * c, UsbCommand * ack)
1597 {
1598 iso14a_command_t param = c->arg[0];
1599 uint8_t * cmd = c->d.asBytes;
1600 size_t len = c->arg[1];
1601
1602 if(param & ISO14A_REQUEST_TRIGGER) iso14a_set_trigger(1);
1603
1604 if(param & ISO14A_CONNECT) {
1605 iso14443a_setup();
1606 ack->arg[0] = iso14443a_select_card(ack->d.asBytes, (iso14a_card_select_t *) (ack->d.asBytes+12));
1607 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1608 }
1609
1610 if(param & ISO14A_SET_TIMEOUT) {
1611 iso14a_timeout = c->arg[2];
1612 }
1613
1614 if(param & ISO14A_SET_TIMEOUT) {
1615 iso14a_timeout = c->arg[2];
1616 }
1617
1618 if(param & ISO14A_APDU) {
1619 ack->arg[0] = iso14_apdu(cmd, len, ack->d.asBytes);
1620 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1621 }
1622
1623 if(param & ISO14A_RAW) {
1624 if(param & ISO14A_APPEND_CRC) {
1625 AppendCrc14443a(cmd,len);
1626 len += 2;
1627 }
1628 ReaderTransmit(cmd,len);
1629 ack->arg[0] = ReaderReceive(ack->d.asBytes);
1630 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1631 }
1632
1633 if(param & ISO14A_REQUEST_TRIGGER) iso14a_set_trigger(0);
1634
1635 if(param & ISO14A_NO_DISCONNECT)
1636 return;
1637
1638 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1639 LEDsoff();
1640 }
1641 //-----------------------------------------------------------------------------
1642 // Read an ISO 14443a tag. Send out commands and store answers.
1643 //
1644 //-----------------------------------------------------------------------------
1645 void ReaderMifare(uint32_t parameter)
1646 {
1647 // Mifare AUTH
1648 uint8_t mf_auth[] = { 0x60,0x00,0xf5,0x7b };
1649 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1650
1651 uint8_t* receivedAnswer = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1652 traceLen = 0;
1653 tracing = false;
1654
1655 iso14443a_setup();
1656
1657 LED_A_ON();
1658 LED_B_OFF();
1659 LED_C_OFF();
1660
1661 byte_t nt_diff = 0;
1662 LED_A_OFF();
1663 byte_t par = 0;
1664 byte_t par_mask = 0xff;
1665 byte_t par_low = 0;
1666 int led_on = TRUE;
1667
1668 tracing = FALSE;
1669 byte_t nt[4];
1670 byte_t nt_attacked[4];
1671 byte_t par_list[8];
1672 byte_t ks_list[8];
1673 num_to_bytes(parameter,4,nt_attacked);
1674
1675 while(TRUE)
1676 {
1677 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1678 SpinDelay(200);
1679 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1680
1681 // Test if the action was cancelled
1682 if(BUTTON_PRESS()) {
1683 break;
1684 }
1685
1686 if(!iso14443a_select_card(NULL, NULL)) continue;
1687
1688 // Transmit MIFARE_CLASSIC_AUTH
1689 ReaderTransmit(mf_auth,sizeof(mf_auth));
1690
1691 // Receive the (16 bit) "random" nonce
1692 if (!ReaderReceive(receivedAnswer)) continue;
1693 memcpy(nt,receivedAnswer,4);
1694
1695 // Transmit reader nonce and reader answer
1696 ReaderTransmitPar(mf_nr_ar,sizeof(mf_nr_ar),par);
1697
1698 // Receive 4 bit answer
1699 if (ReaderReceive(receivedAnswer))
1700 {
1701 if (nt_diff == 0)
1702 {
1703 LED_A_ON();
1704 memcpy(nt_attacked,nt,4);
1705 par_mask = 0xf8;
1706 par_low = par & 0x07;
1707 }
1708
1709 if (memcmp(nt,nt_attacked,4) != 0) continue;
1710
1711 led_on = !led_on;
1712 if(led_on) LED_B_ON(); else LED_B_OFF();
1713 par_list[nt_diff] = par;
1714 ks_list[nt_diff] = receivedAnswer[0]^0x05;
1715
1716 // Test if the information is complete
1717 if (nt_diff == 0x07) break;
1718
1719 nt_diff = (nt_diff+1) & 0x07;
1720 mf_nr_ar[3] = nt_diff << 5;
1721 par = par_low;
1722 } else {
1723 if (nt_diff == 0)
1724 {
1725 par++;
1726 } else {
1727 par = (((par>>3)+1) << 3) | par_low;
1728 }
1729 }
1730 }
1731
1732 LogTrace(nt,4,0,GetParity(nt,4),TRUE);
1733 LogTrace(par_list,8,0,GetParity(par_list,8),TRUE);
1734 LogTrace(ks_list,8,0,GetParity(ks_list,8),TRUE);
1735
1736 // Thats it...
1737 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1738 LEDsoff();
1739 tracing = TRUE;
1740 }
Impressum, Datenschutz