]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iclass.c
Add: simple Application enum.
[proxmark3-svn] / armsrc / iclass.c
1 //-----------------------------------------------------------------------------
2 // Gerhard de Koning Gans - May 2008
3 // Hagen Fritsch - June 2010
4 // Gerhard de Koning Gans - May 2011
5 // Gerhard de Koning Gans - June 2012 - Added iClass card and reader emulation
6 //
7 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
8 // at your option, any later version. See the LICENSE.txt file for the text of
9 // the license.
10 //-----------------------------------------------------------------------------
11 // Routines to support iClass.
12 //-----------------------------------------------------------------------------
13 // Based on ISO14443a implementation. Still in experimental phase.
14 // Contribution made during a security research at Radboud University Nijmegen
15 //
16 // Please feel free to contribute and extend iClass support!!
17 //-----------------------------------------------------------------------------
18 //
19 // FIX:
20 // ====
21 // We still have sometimes a demodulation error when snooping iClass communication.
22 // The resulting trace of a read-block-03 command may look something like this:
23 //
24 // + 22279: : 0c 03 e8 01
25 //
26 // ...with an incorrect answer...
27 //
28 // + 85: 0: TAG ff! ff! ff! ff! ff! ff! ff! ff! bb 33 bb 00 01! 0e! 04! bb !crc
29 //
30 // We still left the error signalling bytes in the traces like 0xbb
31 //
32 // A correct trace should look like this:
33 //
34 // + 21112: : 0c 03 e8 01
35 // + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5
36 //
37 //-----------------------------------------------------------------------------
38
39 #include "../include/proxmark3.h"
40 #include "apps.h"
41 #include "util.h"
42 #include "string.h"
43 #include "common.h"
44 #include "cmd.h"
45 // Needed for CRC in emulation mode;
46 // same construction as in ISO 14443;
47 // different initial value (CRC_ICLASS)
48 #include "../common/iso14443crc.h"
49 #include "../common/iso15693tools.h"
50
51
52 static int timeout = 4096;
53
54
55 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay);
56
57 //-----------------------------------------------------------------------------
58 // The software UART that receives commands from the reader, and its state
59 // variables.
60 //-----------------------------------------------------------------------------
61 static struct {
62 enum {
63 STATE_UNSYNCD,
64 STATE_START_OF_COMMUNICATION,
65 STATE_RECEIVING
66 } state;
67 uint16_t shiftReg;
68 int bitCnt;
69 int byteCnt;
70 int byteCntMax;
71 int posCnt;
72 int nOutOfCnt;
73 int OutOfCnt;
74 int syncBit;
75 int parityBits;
76 int samples;
77 int highCnt;
78 int swapper;
79 int counter;
80 int bitBuffer;
81 int dropPosition;
82 uint8_t *output;
83 } Uart;
84
85 static RAMFUNC int OutOfNDecoding(int bit)
86 {
87 //int error = 0;
88 int bitright;
89
90 if(!Uart.bitBuffer) {
91 Uart.bitBuffer = bit ^ 0xFF0;
92 return FALSE;
93 }
94 else {
95 Uart.bitBuffer <<= 4;
96 Uart.bitBuffer ^= bit;
97 }
98
99 /*if(Uart.swapper) {
100 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
101 Uart.byteCnt++;
102 Uart.swapper = 0;
103 if(Uart.byteCnt > 15) { return TRUE; }
104 }
105 else {
106 Uart.swapper = 1;
107 }*/
108
109 if(Uart.state != STATE_UNSYNCD) {
110 Uart.posCnt++;
111
112 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
113 bit = 0x00;
114 }
115 else {
116 bit = 0x01;
117 }
118 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
119 bitright = 0x00;
120 }
121 else {
122 bitright = 0x01;
123 }
124 if(bit != bitright) { bit = bitright; }
125
126
127 // So, now we only have to deal with *bit*, lets see...
128 if(Uart.posCnt == 1) {
129 // measurement first half bitperiod
130 if(!bit) {
131 // Drop in first half means that we are either seeing
132 // an SOF or an EOF.
133
134 if(Uart.nOutOfCnt == 1) {
135 // End of Communication
136 Uart.state = STATE_UNSYNCD;
137 Uart.highCnt = 0;
138 if(Uart.byteCnt == 0) {
139 // Its not straightforward to show single EOFs
140 // So just leave it and do not return TRUE
141 Uart.output[Uart.byteCnt] = 0xf0;
142 Uart.byteCnt++;
143
144 // Calculate the parity bit for the client...
145 Uart.parityBits = 1;
146 }
147 else {
148 return TRUE;
149 }
150 }
151 else if(Uart.state != STATE_START_OF_COMMUNICATION) {
152 // When not part of SOF or EOF, it is an error
153 Uart.state = STATE_UNSYNCD;
154 Uart.highCnt = 0;
155 //error = 4;
156 }
157 }
158 }
159 else {
160 // measurement second half bitperiod
161 // Count the bitslot we are in... (ISO 15693)
162 Uart.nOutOfCnt++;
163
164 if(!bit) {
165 if(Uart.dropPosition) {
166 if(Uart.state == STATE_START_OF_COMMUNICATION) {
167 //error = 1;
168 }
169 else {
170 //error = 7;
171 }
172 // It is an error if we already have seen a drop in current frame
173 Uart.state = STATE_UNSYNCD;
174 Uart.highCnt = 0;
175 }
176 else {
177 Uart.dropPosition = Uart.nOutOfCnt;
178 }
179 }
180
181 Uart.posCnt = 0;
182
183
184 if(Uart.nOutOfCnt == Uart.OutOfCnt && Uart.OutOfCnt == 4) {
185 Uart.nOutOfCnt = 0;
186
187 if(Uart.state == STATE_START_OF_COMMUNICATION) {
188 if(Uart.dropPosition == 4) {
189 Uart.state = STATE_RECEIVING;
190 Uart.OutOfCnt = 256;
191 }
192 else if(Uart.dropPosition == 3) {
193 Uart.state = STATE_RECEIVING;
194 Uart.OutOfCnt = 4;
195 //Uart.output[Uart.byteCnt] = 0xdd;
196 //Uart.byteCnt++;
197 }
198 else {
199 Uart.state = STATE_UNSYNCD;
200 Uart.highCnt = 0;
201 }
202 Uart.dropPosition = 0;
203 }
204 else {
205 // RECEIVING DATA
206 // 1 out of 4
207 if(!Uart.dropPosition) {
208 Uart.state = STATE_UNSYNCD;
209 Uart.highCnt = 0;
210 //error = 9;
211 }
212 else {
213 Uart.shiftReg >>= 2;
214
215 // Swap bit order
216 Uart.dropPosition--;
217 //if(Uart.dropPosition == 1) { Uart.dropPosition = 2; }
218 //else if(Uart.dropPosition == 2) { Uart.dropPosition = 1; }
219
220 Uart.shiftReg ^= ((Uart.dropPosition & 0x03) << 6);
221 Uart.bitCnt += 2;
222 Uart.dropPosition = 0;
223
224 if(Uart.bitCnt == 8) {
225 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
226 Uart.byteCnt++;
227
228 // Calculate the parity bit for the client...
229 Uart.parityBits <<= 1;
230 Uart.parityBits ^= OddByteParity[(Uart.shiftReg & 0xff)];
231
232 Uart.bitCnt = 0;
233 Uart.shiftReg = 0;
234 }
235 }
236 }
237 }
238 else if(Uart.nOutOfCnt == Uart.OutOfCnt) {
239 // RECEIVING DATA
240 // 1 out of 256
241 if(!Uart.dropPosition) {
242 Uart.state = STATE_UNSYNCD;
243 Uart.highCnt = 0;
244 //error = 3;
245 }
246 else {
247 Uart.dropPosition--;
248 Uart.output[Uart.byteCnt] = (Uart.dropPosition & 0xff);
249 Uart.byteCnt++;
250
251 // Calculate the parity bit for the client...
252 Uart.parityBits <<= 1;
253 Uart.parityBits ^= OddByteParity[(Uart.dropPosition & 0xff)];
254
255 Uart.bitCnt = 0;
256 Uart.shiftReg = 0;
257 Uart.nOutOfCnt = 0;
258 Uart.dropPosition = 0;
259 }
260 }
261
262 /*if(error) {
263 Uart.output[Uart.byteCnt] = 0xAA;
264 Uart.byteCnt++;
265 Uart.output[Uart.byteCnt] = error & 0xFF;
266 Uart.byteCnt++;
267 Uart.output[Uart.byteCnt] = 0xAA;
268 Uart.byteCnt++;
269 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
270 Uart.byteCnt++;
271 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
272 Uart.byteCnt++;
273 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
274 Uart.byteCnt++;
275 Uart.output[Uart.byteCnt] = 0xAA;
276 Uart.byteCnt++;
277 return TRUE;
278 }*/
279 }
280
281 }
282 else {
283 bit = Uart.bitBuffer & 0xf0;
284 bit >>= 4;
285 bit ^= 0x0F; // drops become 1s ;-)
286 if(bit) {
287 // should have been high or at least (4 * 128) / fc
288 // according to ISO this should be at least (9 * 128 + 20) / fc
289 if(Uart.highCnt == 8) {
290 // we went low, so this could be start of communication
291 // it turns out to be safer to choose a less significant
292 // syncbit... so we check whether the neighbour also represents the drop
293 Uart.posCnt = 1; // apparently we are busy with our first half bit period
294 Uart.syncBit = bit & 8;
295 Uart.samples = 3;
296 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
297 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
298 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
299 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
300 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
301 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
302 Uart.syncBit = 8;
303
304 // the first half bit period is expected in next sample
305 Uart.posCnt = 0;
306 Uart.samples = 3;
307 }
308 }
309 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
310
311 Uart.syncBit <<= 4;
312 Uart.state = STATE_START_OF_COMMUNICATION;
313 Uart.bitCnt = 0;
314 Uart.byteCnt = 0;
315 Uart.parityBits = 0;
316 Uart.nOutOfCnt = 0;
317 Uart.OutOfCnt = 4; // Start at 1/4, could switch to 1/256
318 Uart.dropPosition = 0;
319 Uart.shiftReg = 0;
320 //error = 0;
321 }
322 else {
323 Uart.highCnt = 0;
324 }
325 }
326 else {
327 if(Uart.highCnt < 8) {
328 Uart.highCnt++;
329 }
330 }
331 }
332
333 return FALSE;
334 }
335
336 //=============================================================================
337 // Manchester
338 //=============================================================================
339
340 static struct {
341 enum {
342 DEMOD_UNSYNCD,
343 DEMOD_START_OF_COMMUNICATION,
344 DEMOD_START_OF_COMMUNICATION2,
345 DEMOD_START_OF_COMMUNICATION3,
346 DEMOD_SOF_COMPLETE,
347 DEMOD_MANCHESTER_D,
348 DEMOD_MANCHESTER_E,
349 DEMOD_END_OF_COMMUNICATION,
350 DEMOD_END_OF_COMMUNICATION2,
351 DEMOD_MANCHESTER_F,
352 DEMOD_ERROR_WAIT
353 } state;
354 int bitCount;
355 int posCount;
356 int syncBit;
357 int parityBits;
358 uint16_t shiftReg;
359 int buffer;
360 int buffer2;
361 int buffer3;
362 int buff;
363 int samples;
364 int len;
365 enum {
366 SUB_NONE,
367 SUB_FIRST_HALF,
368 SUB_SECOND_HALF,
369 SUB_BOTH
370 } sub;
371 uint8_t *output;
372 } Demod;
373
374 static RAMFUNC int ManchesterDecoding(int v)
375 {
376 int bit;
377 int modulation;
378 int error = 0;
379
380 bit = Demod.buffer;
381 Demod.buffer = Demod.buffer2;
382 Demod.buffer2 = Demod.buffer3;
383 Demod.buffer3 = v;
384
385 if(Demod.buff < 3) {
386 Demod.buff++;
387 return FALSE;
388 }
389
390 if(Demod.state==DEMOD_UNSYNCD) {
391 Demod.output[Demod.len] = 0xfa;
392 Demod.syncBit = 0;
393 //Demod.samples = 0;
394 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
395
396 if(bit & 0x08) {
397 Demod.syncBit = 0x08;
398 }
399
400 if(bit & 0x04) {
401 if(Demod.syncBit) {
402 bit <<= 4;
403 }
404 Demod.syncBit = 0x04;
405 }
406
407 if(bit & 0x02) {
408 if(Demod.syncBit) {
409 bit <<= 2;
410 }
411 Demod.syncBit = 0x02;
412 }
413
414 if(bit & 0x01 && Demod.syncBit) {
415 Demod.syncBit = 0x01;
416 }
417
418 if(Demod.syncBit) {
419 Demod.len = 0;
420 Demod.state = DEMOD_START_OF_COMMUNICATION;
421 Demod.sub = SUB_FIRST_HALF;
422 Demod.bitCount = 0;
423 Demod.shiftReg = 0;
424 Demod.parityBits = 0;
425 Demod.samples = 0;
426 if(Demod.posCount) {
427 //if(trigger) LED_A_OFF(); // Not useful in this case...
428 switch(Demod.syncBit) {
429 case 0x08: Demod.samples = 3; break;
430 case 0x04: Demod.samples = 2; break;
431 case 0x02: Demod.samples = 1; break;
432 case 0x01: Demod.samples = 0; break;
433 }
434 // SOF must be long burst... otherwise stay unsynced!!!
435 if(!(Demod.buffer & Demod.syncBit) || !(Demod.buffer2 & Demod.syncBit)) {
436 Demod.state = DEMOD_UNSYNCD;
437 }
438 }
439 else {
440 // SOF must be long burst... otherwise stay unsynced!!!
441 if(!(Demod.buffer2 & Demod.syncBit) || !(Demod.buffer3 & Demod.syncBit)) {
442 Demod.state = DEMOD_UNSYNCD;
443 error = 0x88;
444 }
445
446 }
447 error = 0;
448
449 }
450 }
451 else {
452 modulation = bit & Demod.syncBit;
453 modulation |= ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
454 //modulation = ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
455
456 Demod.samples += 4;
457
458 if(Demod.posCount==0) {
459 Demod.posCount = 1;
460 if(modulation) {
461 Demod.sub = SUB_FIRST_HALF;
462 }
463 else {
464 Demod.sub = SUB_NONE;
465 }
466 }
467 else {
468 Demod.posCount = 0;
469 /*(modulation && (Demod.sub == SUB_FIRST_HALF)) {
470 if(Demod.state!=DEMOD_ERROR_WAIT) {
471 Demod.state = DEMOD_ERROR_WAIT;
472 Demod.output[Demod.len] = 0xaa;
473 error = 0x01;
474 }
475 }*/
476 //else if(modulation) {
477 if(modulation) {
478 if(Demod.sub == SUB_FIRST_HALF) {
479 Demod.sub = SUB_BOTH;
480 }
481 else {
482 Demod.sub = SUB_SECOND_HALF;
483 }
484 }
485 else if(Demod.sub == SUB_NONE) {
486 if(Demod.state == DEMOD_SOF_COMPLETE) {
487 Demod.output[Demod.len] = 0x0f;
488 Demod.len++;
489 Demod.parityBits <<= 1;
490 Demod.parityBits ^= OddByteParity[0x0f];
491 Demod.state = DEMOD_UNSYNCD;
492 // error = 0x0f;
493 return TRUE;
494 }
495 else {
496 Demod.state = DEMOD_ERROR_WAIT;
497 error = 0x33;
498 }
499 /*if(Demod.state!=DEMOD_ERROR_WAIT) {
500 Demod.state = DEMOD_ERROR_WAIT;
501 Demod.output[Demod.len] = 0xaa;
502 error = 0x01;
503 }*/
504 }
505
506 switch(Demod.state) {
507 case DEMOD_START_OF_COMMUNICATION:
508 if(Demod.sub == SUB_BOTH) {
509 //Demod.state = DEMOD_MANCHESTER_D;
510 Demod.state = DEMOD_START_OF_COMMUNICATION2;
511 Demod.posCount = 1;
512 Demod.sub = SUB_NONE;
513 }
514 else {
515 Demod.output[Demod.len] = 0xab;
516 Demod.state = DEMOD_ERROR_WAIT;
517 error = 0xd2;
518 }
519 break;
520 case DEMOD_START_OF_COMMUNICATION2:
521 if(Demod.sub == SUB_SECOND_HALF) {
522 Demod.state = DEMOD_START_OF_COMMUNICATION3;
523 }
524 else {
525 Demod.output[Demod.len] = 0xab;
526 Demod.state = DEMOD_ERROR_WAIT;
527 error = 0xd3;
528 }
529 break;
530 case DEMOD_START_OF_COMMUNICATION3:
531 if(Demod.sub == SUB_SECOND_HALF) {
532 // Demod.state = DEMOD_MANCHESTER_D;
533 Demod.state = DEMOD_SOF_COMPLETE;
534 //Demod.output[Demod.len] = Demod.syncBit & 0xFF;
535 //Demod.len++;
536 }
537 else {
538 Demod.output[Demod.len] = 0xab;
539 Demod.state = DEMOD_ERROR_WAIT;
540 error = 0xd4;
541 }
542 break;
543 case DEMOD_SOF_COMPLETE:
544 case DEMOD_MANCHESTER_D:
545 case DEMOD_MANCHESTER_E:
546 // OPPOSITE FROM ISO14443 - 11110000 = 0 (1 in 14443)
547 // 00001111 = 1 (0 in 14443)
548 if(Demod.sub == SUB_SECOND_HALF) { // SUB_FIRST_HALF
549 Demod.bitCount++;
550 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
551 Demod.state = DEMOD_MANCHESTER_D;
552 }
553 else if(Demod.sub == SUB_FIRST_HALF) { // SUB_SECOND_HALF
554 Demod.bitCount++;
555 Demod.shiftReg >>= 1;
556 Demod.state = DEMOD_MANCHESTER_E;
557 }
558 else if(Demod.sub == SUB_BOTH) {
559 Demod.state = DEMOD_MANCHESTER_F;
560 }
561 else {
562 Demod.state = DEMOD_ERROR_WAIT;
563 error = 0x55;
564 }
565 break;
566
567 case DEMOD_MANCHESTER_F:
568 // Tag response does not need to be a complete byte!
569 if(Demod.len > 0 || Demod.bitCount > 0) {
570 if(Demod.bitCount > 1) { // was > 0, do not interpret last closing bit, is part of EOF
571 Demod.shiftReg >>= (9 - Demod.bitCount);
572 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
573 Demod.len++;
574 // No parity bit, so just shift a 0
575 Demod.parityBits <<= 1;
576 }
577
578 Demod.state = DEMOD_UNSYNCD;
579 return TRUE;
580 }
581 else {
582 Demod.output[Demod.len] = 0xad;
583 Demod.state = DEMOD_ERROR_WAIT;
584 error = 0x03;
585 }
586 break;
587
588 case DEMOD_ERROR_WAIT:
589 Demod.state = DEMOD_UNSYNCD;
590 break;
591
592 default:
593 Demod.output[Demod.len] = 0xdd;
594 Demod.state = DEMOD_UNSYNCD;
595 break;
596 }
597
598 /*if(Demod.bitCount>=9) {
599 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
600 Demod.len++;
601
602 Demod.parityBits <<= 1;
603 Demod.parityBits ^= ((Demod.shiftReg >> 8) & 0x01);
604
605 Demod.bitCount = 0;
606 Demod.shiftReg = 0;
607 }*/
608 if(Demod.bitCount>=8) {
609 Demod.shiftReg >>= 1;
610 Demod.output[Demod.len] = (Demod.shiftReg & 0xff);
611 Demod.len++;
612
613 // FOR ISO15639 PARITY NOT SEND OTA, JUST CALCULATE IT FOR THE CLIENT
614 Demod.parityBits <<= 1;
615 Demod.parityBits ^= OddByteParity[(Demod.shiftReg & 0xff)];
616
617 Demod.bitCount = 0;
618 Demod.shiftReg = 0;
619 }
620
621 if(error) {
622 Demod.output[Demod.len] = 0xBB;
623 Demod.len++;
624 Demod.output[Demod.len] = error & 0xFF;
625 Demod.len++;
626 Demod.output[Demod.len] = 0xBB;
627 Demod.len++;
628 Demod.output[Demod.len] = bit & 0xFF;
629 Demod.len++;
630 Demod.output[Demod.len] = Demod.buffer & 0xFF;
631 Demod.len++;
632 // Look harder ;-)
633 Demod.output[Demod.len] = Demod.buffer2 & 0xFF;
634 Demod.len++;
635 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
636 Demod.len++;
637 Demod.output[Demod.len] = 0xBB;
638 Demod.len++;
639 return TRUE;
640 }
641
642 }
643
644 } // end (state != UNSYNCED)
645
646 return FALSE;
647 }
648
649 //=============================================================================
650 // Finally, a `sniffer' for iClass communication
651 // Both sides of communication!
652 //=============================================================================
653
654 //-----------------------------------------------------------------------------
655 // Record the sequence of commands sent by the reader to the tag, with
656 // triggering so that we start recording at the point that the tag is moved
657 // near the reader.
658 //-----------------------------------------------------------------------------
659 void RAMFUNC SnoopIClass(void)
660 {
661
662
663 // We won't start recording the frames that we acquire until we trigger;
664 // a good trigger condition to get started is probably when we see a
665 // response from the tag.
666 //int triggered = FALSE; // FALSE to wait first for card
667
668 // The command (reader -> tag) that we're receiving.
669 // The length of a received command will in most cases be no more than 18 bytes.
670 // So 32 should be enough!
671 uint8_t *readerToTagCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
672 // The response (tag -> reader) that we're receiving.
673 uint8_t *tagToReaderResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
674
675 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
676
677 // reset traceLen to 0
678 iso14a_set_tracing(TRUE);
679 iso14a_clear_trace();
680 iso14a_set_trigger(FALSE);
681
682 // The DMA buffer, used to stream samples from the FPGA
683 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
684 int lastRxCounter;
685 int8_t *upTo;
686 int smpl;
687 int maxBehindBy = 0;
688
689 // Count of samples received so far, so that we can include timing
690 // information in the trace buffer.
691 int samples = 0;
692 rsamples = 0;
693
694 // Set up the demodulator for tag -> reader responses.
695 Demod.output = tagToReaderResponse;
696 Demod.len = 0;
697 Demod.state = DEMOD_UNSYNCD;
698
699 // Setup for the DMA.
700 FpgaSetupSsc();
701 upTo = dmaBuf;
702 lastRxCounter = DMA_BUFFER_SIZE;
703 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
704
705 // And the reader -> tag commands
706 memset(&Uart, 0, sizeof(Uart));
707 Uart.output = readerToTagCmd;
708 Uart.byteCntMax = 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
709 Uart.state = STATE_UNSYNCD;
710
711 // And put the FPGA in the appropriate mode
712 // Signal field is off with the appropriate LED
713 LED_D_OFF();
714 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
715 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
716
717 uint32_t time_0 = GetCountSspClk();
718
719
720 int div = 0;
721 //int div2 = 0;
722 int decbyte = 0;
723 int decbyter = 0;
724
725 // And now we loop, receiving samples.
726 for(;;) {
727 LED_A_ON();
728 WDT_HIT();
729 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
730 (DMA_BUFFER_SIZE-1);
731 if(behindBy > maxBehindBy) {
732 maxBehindBy = behindBy;
733 if(behindBy > 400) {
734 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
735 goto done;
736 }
737 }
738 if(behindBy < 1) continue;
739
740 LED_A_OFF();
741 smpl = upTo[0];
742 upTo++;
743 lastRxCounter -= 1;
744 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
745 upTo -= DMA_BUFFER_SIZE;
746 lastRxCounter += DMA_BUFFER_SIZE;
747 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
748 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
749 }
750
751 //samples += 4;
752 samples += 1;
753
754 if(smpl & 0xF) {
755 decbyte ^= (1 << (3 - div));
756 }
757
758 // FOR READER SIDE COMMUMICATION...
759
760 decbyter <<= 2;
761 decbyter ^= (smpl & 0x30);
762
763 div++;
764
765 if((div + 1) % 2 == 0) {
766 smpl = decbyter;
767 if(OutOfNDecoding((smpl & 0xF0) >> 4)) {
768 rsamples = samples - Uart.samples;
769 LED_C_ON();
770
771 //if(!LogTrace(Uart.output,Uart.byteCnt, rsamples, Uart.parityBits,TRUE)) break;
772 //if(!LogTrace(NULL, 0, Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, 0, TRUE)) break;
773 if(tracing)
774 {
775 LogTrace(Uart.output,Uart.byteCnt, (GetCountSspClk()-time_0) << 4, Uart.parityBits,TRUE);
776 LogTrace(NULL, 0, (GetCountSspClk()-time_0) << 4, 0, TRUE);
777 }
778
779
780 /* And ready to receive another command. */
781 Uart.state = STATE_UNSYNCD;
782 /* And also reset the demod code, which might have been */
783 /* false-triggered by the commands from the reader. */
784 Demod.state = DEMOD_UNSYNCD;
785 LED_B_OFF();
786 Uart.byteCnt = 0;
787 }
788 decbyter = 0;
789 }
790
791 if(div > 3) {
792 smpl = decbyte;
793 if(ManchesterDecoding(smpl & 0x0F)) {
794 rsamples = samples - Demod.samples;
795 LED_B_ON();
796
797 if(tracing)
798 {
799 LogTrace(Demod.output,Demod.len, (GetCountSspClk()-time_0) << 4 , Demod.parityBits,FALSE);
800 LogTrace(NULL, 0, (GetCountSspClk()-time_0) << 4, 0, FALSE);
801 }
802
803
804 // And ready to receive another response.
805 memset(&Demod, 0, sizeof(Demod));
806 Demod.output = tagToReaderResponse;
807 Demod.state = DEMOD_UNSYNCD;
808 LED_C_OFF();
809 }
810
811 div = 0;
812 decbyte = 0x00;
813 }
814 //}
815
816 if(BUTTON_PRESS()) {
817 DbpString("cancelled_a");
818 goto done;
819 }
820 }
821
822 DbpString("COMMAND FINISHED");
823
824 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
825 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
826
827 done:
828 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
829 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
830 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
831 LED_A_OFF();
832 LED_B_OFF();
833 LED_C_OFF();
834 LED_D_OFF();
835 }
836
837 void rotateCSN(uint8_t* originalCSN, uint8_t* rotatedCSN) {
838 int i;
839 for(i = 0; i < 8; i++) {
840 rotatedCSN[i] = (originalCSN[i] >> 3) | (originalCSN[(i+1)%8] << 5);
841 }
842 }
843
844 //-----------------------------------------------------------------------------
845 // Wait for commands from reader
846 // Stop when button is pressed
847 // Or return TRUE when command is captured
848 //-----------------------------------------------------------------------------
849 static int GetIClassCommandFromReader(uint8_t *received, int *len, int maxLen)
850 {
851 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
852 // only, since we are receiving, not transmitting).
853 // Signal field is off with the appropriate LED
854 LED_D_OFF();
855 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
856
857 // Now run a `software UART' on the stream of incoming samples.
858 Uart.output = received;
859 Uart.byteCntMax = maxLen;
860 Uart.state = STATE_UNSYNCD;
861
862 for(;;) {
863 WDT_HIT();
864
865 if(BUTTON_PRESS()) return FALSE;
866
867 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
868 AT91C_BASE_SSC->SSC_THR = 0x00;
869 }
870 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
871 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
872 /*if(OutOfNDecoding((b & 0xf0) >> 4)) {
873 *len = Uart.byteCnt;
874 return TRUE;
875 }*/
876 if(OutOfNDecoding(b & 0x0f)) {
877 *len = Uart.byteCnt;
878 return TRUE;
879 }
880 }
881 }
882 }
883
884
885 //-----------------------------------------------------------------------------
886 // Prepare tag messages
887 //-----------------------------------------------------------------------------
888 static void CodeIClassTagAnswer(const uint8_t *cmd, int len)
889 {
890 //So far a dummy implementation, not used
891 //int lastProxToAirDuration =0;
892 int i;
893
894 ToSendReset();
895
896 // Send SOF
897 ToSend[++ToSendMax] = 0x00;
898 ToSend[++ToSendMax] = 0x00;
899 ToSend[++ToSendMax] = 0x00;
900 ToSend[++ToSendMax] = 0xff;//Proxtoair duration starts here
901 ToSend[++ToSendMax] = 0xff;
902 ToSend[++ToSendMax] = 0xff;
903 ToSend[++ToSendMax] = 0x00;
904 ToSend[++ToSendMax] = 0xff;
905
906 for(i = 0; i < len; i++) {
907 int j;
908 uint8_t b = cmd[i];
909
910 // Data bits
911 for(j = 0; j < 8; j++) {
912 if(b & 1) {
913 ToSend[++ToSendMax] = 0x00;
914 ToSend[++ToSendMax] = 0xff;
915 } else {
916 ToSend[++ToSendMax] = 0xff;
917 ToSend[++ToSendMax] = 0x00;
918 }
919 b >>= 1;
920 }
921 }
922
923 // Send EOF
924 ToSend[++ToSendMax] = 0xff;
925 ToSend[++ToSendMax] = 0x00;
926 ToSend[++ToSendMax] = 0xff;
927 ToSend[++ToSendMax] = 0xff;
928 ToSend[++ToSendMax] = 0xff;
929 ToSend[++ToSendMax] = 0x00;
930 ToSend[++ToSendMax] = 0x00;
931 ToSend[++ToSendMax] = 0x00;
932
933 //lastProxToAirDuration = 8*ToSendMax - 3*8 - 3*8;//Not counting zeroes in the beginning or end
934
935 // Convert from last byte pos to length
936 ToSendMax++;
937 }
938
939 // Only SOF
940 static void CodeIClassTagSOF()
941 {
942 //So far a dummy implementation, not used
943 //int lastProxToAirDuration =0;
944
945 ToSendReset();
946 // Send SOF
947 ToSend[++ToSendMax] = 0x00;
948 ToSend[++ToSendMax] = 0x00;
949 ToSend[++ToSendMax] = 0x00;
950 ToSend[++ToSendMax] = 0xff;
951 ToSend[++ToSendMax] = 0xff;
952 ToSend[++ToSendMax] = 0xff;
953 ToSend[++ToSendMax] = 0x00;
954 ToSend[++ToSendMax] = 0xff;
955
956 // lastProxToAirDuration = 8*ToSendMax - 3*8;//Not counting zeroes in the beginning
957
958
959 // Convert from last byte pos to length
960 ToSendMax++;
961 }
962 int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf);
963 /**
964 * @brief SimulateIClass simulates an iClass card.
965 * @param arg0 type of simulation
966 * - 0 uses the first 8 bytes in usb data as CSN
967 * - 2 "dismantling iclass"-attack. This mode iterates through all CSN's specified
968 * in the usb data. This mode collects MAC from the reader, in order to do an offline
969 * attack on the keys. For more info, see "dismantling iclass" and proxclone.com.
970 * - Other : Uses the default CSN (031fec8af7ff12e0)
971 * @param arg1 - number of CSN's contained in datain (applicable for mode 2 only)
972 * @param arg2
973 * @param datain
974 */
975 void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
976 {
977 uint32_t simType = arg0;
978 uint32_t numberOfCSNS = arg1;
979 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
980
981 // Enable and clear the trace
982 iso14a_set_tracing(TRUE);
983 iso14a_clear_trace();
984
985 uint8_t csn_crc[] = { 0x03, 0x1f, 0xec, 0x8a, 0xf7, 0xff, 0x12, 0xe0, 0x00, 0x00 };
986 if(simType == 0) {
987 // Use the CSN from commandline
988 memcpy(csn_crc, datain, 8);
989 doIClassSimulation(csn_crc,0,NULL);
990 }else if(simType == 1)
991 {
992 doIClassSimulation(csn_crc,0,NULL);
993 }
994 else if(simType == 2)
995 {
996
997 uint8_t mac_responses[64] = { 0 };
998 Dbprintf("Going into attack mode");
999 // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
1000 // in order to collect MAC's from the reader. This can later be used in an offlne-attack
1001 // in order to obtain the keys, as in the "dismantling iclass"-paper.
1002 int i = 0;
1003 for( ; i < numberOfCSNS && i*8+8 < USB_CMD_DATA_SIZE; i++)
1004 {
1005 // The usb data is 512 bytes, fitting 65 8-byte CSNs in there.
1006
1007 memcpy(csn_crc, datain+(i*8), 8);
1008 if(doIClassSimulation(csn_crc,1,mac_responses))
1009 {
1010 return; // Button pressed
1011 }
1012 }
1013 cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
1014
1015 }
1016 else{
1017 // We may want a mode here where we hardcode the csns to use (from proxclone).
1018 // That will speed things up a little, but not required just yet.
1019 Dbprintf("The mode is not implemented, reserved for future use");
1020 }
1021 Dbprintf("Done...");
1022
1023 }
1024 /**
1025 * @brief Does the actual simulation
1026 * @param csn - csn to use
1027 * @param breakAfterMacReceived if true, returns after reader MAC has been received.
1028 */
1029 int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf)
1030 {
1031
1032
1033 // CSN followed by two CRC bytes
1034 uint8_t response2[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1035 uint8_t response3[] = { 0,0,0,0,0,0,0,0,0,0};
1036 memcpy(response3,csn,sizeof(response3));
1037 Dbprintf("Simulating CSN %02x%02x%02x%02x%02x%02x%02x%02x",csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]);
1038 // e-Purse
1039 uint8_t response4[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1040
1041 // Construct anticollision-CSN
1042 rotateCSN(response3,response2);
1043
1044 // Compute CRC on both CSNs
1045 ComputeCrc14443(CRC_ICLASS, response2, 8, &response2[8], &response2[9]);
1046 ComputeCrc14443(CRC_ICLASS, response3, 8, &response3[8], &response3[9]);
1047
1048 int exitLoop = 0;
1049 // Reader 0a
1050 // Tag 0f
1051 // Reader 0c
1052 // Tag anticoll. CSN
1053 // Reader 81 anticoll. CSN
1054 // Tag CSN
1055
1056 uint8_t *resp;
1057 int respLen;
1058 uint8_t* respdata = NULL;
1059 int respsize = 0;
1060 uint8_t sof = 0x0f;
1061
1062 // Respond SOF -- takes 8 bytes
1063 uint8_t *resp1 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
1064 int resp1Len;
1065
1066 // Anticollision CSN (rotated CSN)
1067 // 176: Takes 16 bytes for SOF/EOF and 10 * 16 = 160 bytes (2 bytes/bit)
1068 uint8_t *resp2 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 10);
1069 int resp2Len;
1070
1071 // CSN
1072 // 176: Takes 16 bytes for SOF/EOF and 10 * 16 = 160 bytes (2 bytes/bit)
1073 uint8_t *resp3 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 190);
1074 int resp3Len;
1075
1076 // e-Purse
1077 // 144: Takes 16 bytes for SOF/EOF and 8 * 16 = 128 bytes (2 bytes/bit)
1078 uint8_t *resp4 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 370);
1079 int resp4Len;
1080
1081 // + 1720..
1082 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
1083 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
1084 int len;
1085
1086 // Prepare card messages
1087 ToSendMax = 0;
1088
1089 // First card answer: SOF
1090 CodeIClassTagSOF();
1091 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
1092
1093 // Anticollision CSN
1094 CodeIClassTagAnswer(response2, sizeof(response2));
1095 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
1096
1097 // CSN
1098 CodeIClassTagAnswer(response3, sizeof(response3));
1099 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
1100
1101 // e-Purse
1102 CodeIClassTagAnswer(response4, sizeof(response4));
1103 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1104
1105
1106 // Start from off (no field generated)
1107 //FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1108 //SpinDelay(200);
1109 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1110 SpinDelay(100);
1111 StartCountSspClk();
1112 // We need to listen to the high-frequency, peak-detected path.
1113 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1114 FpgaSetupSsc();
1115
1116 // To control where we are in the protocol
1117 int cmdsRecvd = 0;
1118 uint32_t time_0 = GetCountSspClk();
1119 uint32_t t2r_time =0;
1120 uint32_t r2t_time =0;
1121
1122 LED_A_ON();
1123 bool buttonPressed = false;
1124
1125 /** Hack for testing
1126 memcpy(reader_mac_buf,csn,8);
1127 exitLoop = true;
1128 end hack **/
1129
1130 while(!exitLoop) {
1131
1132 LED_B_OFF();
1133 //Signal tracer
1134 // Can be used to get a trigger for an oscilloscope..
1135 LED_C_OFF();
1136
1137 if(!GetIClassCommandFromReader(receivedCmd, &len, 100)) {
1138 buttonPressed = true;
1139 break;
1140 }
1141 r2t_time = GetCountSspClk();
1142 //Signal tracer
1143 LED_C_ON();
1144
1145 // Okay, look at the command now.
1146 if(receivedCmd[0] == 0x0a ) {
1147 // Reader in anticollission phase
1148 resp = resp1; respLen = resp1Len; //order = 1;
1149 respdata = &sof;
1150 respsize = sizeof(sof);
1151 } else if(receivedCmd[0] == 0x0c) {
1152 // Reader asks for anticollission CSN
1153 resp = resp2; respLen = resp2Len; //order = 2;
1154 respdata = response2;
1155 respsize = sizeof(response2);
1156 //DbpString("Reader requests anticollission CSN:");
1157 } else if(receivedCmd[0] == 0x81) {
1158 // Reader selects anticollission CSN.
1159 // Tag sends the corresponding real CSN
1160 resp = resp3; respLen = resp3Len; //order = 3;
1161 respdata = response3;
1162 respsize = sizeof(response3);
1163 //DbpString("Reader selects anticollission CSN:");
1164 } else if(receivedCmd[0] == 0x88) {
1165 // Read e-purse (88 02)
1166 resp = resp4; respLen = resp4Len; //order = 4;
1167 respdata = response4;
1168 respsize = sizeof(response4);
1169 LED_B_ON();
1170 } else if(receivedCmd[0] == 0x05) {
1171 // Reader random and reader MAC!!!
1172 // Do not respond
1173 // We do not know what to answer, so lets keep quiet
1174 resp = resp1; respLen = 0; //order = 5;
1175 respdata = NULL;
1176 respsize = 0;
1177 if (breakAfterMacReceived){
1178 // dbprintf:ing ...
1179 Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x",csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]);
1180 Dbprintf("RDR: (len=%02d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",len,
1181 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1182 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1183 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1184 if (reader_mac_buf != NULL)
1185 {
1186 memcpy(reader_mac_buf,receivedCmd+1,8);
1187 }
1188 exitLoop = true;
1189 }
1190 } else if(receivedCmd[0] == 0x00 && len == 1) {
1191 // Reader ends the session
1192 resp = resp1; respLen = 0; //order = 0;
1193 respdata = NULL;
1194 respsize = 0;
1195 } else {
1196 //#db# Unknown command received from reader (len=5): 26 1 0 f6 a 44 44 44 44
1197 // Never seen this command before
1198 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1199 len,
1200 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1201 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1202 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1203 // Do not respond
1204 resp = resp1; respLen = 0; //order = 0;
1205 respdata = NULL;
1206 respsize = 0;
1207 }
1208
1209 if(cmdsRecvd > 100) {
1210 //DbpString("100 commands later...");
1211 //break;
1212 }
1213 else {
1214 cmdsRecvd++;
1215 }
1216
1217 if(respLen > 0) {
1218 SendIClassAnswer(resp, respLen, 21);
1219 t2r_time = GetCountSspClk();
1220 }
1221
1222 if (tracing) {
1223 LogTrace(receivedCmd,len, (r2t_time-time_0)<< 4, Uart.parityBits,TRUE);
1224 LogTrace(NULL,0, (r2t_time-time_0) << 4, 0,TRUE);
1225
1226 if (respdata != NULL) {
1227 LogTrace(respdata,respsize, (t2r_time-time_0) << 4,SwapBits(GetParity(respdata,respsize),respsize),FALSE);
1228 LogTrace(NULL,0, (t2r_time-time_0) << 4,0,FALSE);
1229
1230
1231 }
1232 if(!tracing) {
1233 DbpString("Trace full");
1234 //break;
1235 }
1236
1237 }
1238 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
1239 }
1240
1241 //Dbprintf("%x", cmdsRecvd);
1242 LED_A_OFF();
1243 LED_B_OFF();
1244 if(buttonPressed)
1245 {
1246 DbpString("Button pressed");
1247 }
1248 return buttonPressed;
1249 }
1250
1251 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay)
1252 {
1253 int i = 0, d=0;//, u = 0, d = 0;
1254 uint8_t b = 0;
1255
1256 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K);
1257
1258 AT91C_BASE_SSC->SSC_THR = 0x00;
1259 FpgaSetupSsc();
1260 while(!BUTTON_PRESS()) {
1261 if((AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)){
1262 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
1263 }
1264 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)){
1265 b = 0x00;
1266 if(d < delay) {
1267 d++;
1268 }
1269 else {
1270 if( i < respLen){
1271 b = resp[i];
1272 //Hack
1273 //b = 0xAC;
1274 }
1275 i++;
1276 }
1277 AT91C_BASE_SSC->SSC_THR = b;
1278 }
1279
1280 if (i > respLen +4) break;
1281 }
1282
1283 return 0;
1284 }
1285
1286 /// THE READER CODE
1287
1288 //-----------------------------------------------------------------------------
1289 // Transmit the command (to the tag) that was placed in ToSend[].
1290 //-----------------------------------------------------------------------------
1291 static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait)
1292 {
1293 int c;
1294 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1295 AT91C_BASE_SSC->SSC_THR = 0x00;
1296 FpgaSetupSsc();
1297
1298 if (wait)
1299 if(*wait < 10)
1300 *wait = 10;
1301
1302 for(c = 0; c < *wait;) {
1303 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1304 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1305 c++;
1306 }
1307 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1308 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1309 (void)r;
1310 }
1311 WDT_HIT();
1312 }
1313
1314 uint8_t sendbyte;
1315 bool firstpart = TRUE;
1316 c = 0;
1317 for(;;) {
1318 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1319
1320 // DOUBLE THE SAMPLES!
1321 if(firstpart) {
1322 sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4);
1323 }
1324 else {
1325 sendbyte = (cmd[c] & 0x0f) | (cmd[c] << 4);
1326 c++;
1327 }
1328 if(sendbyte == 0xff) {
1329 sendbyte = 0xfe;
1330 }
1331 AT91C_BASE_SSC->SSC_THR = sendbyte;
1332 firstpart = !firstpart;
1333
1334 if(c >= len) {
1335 break;
1336 }
1337 }
1338 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1339 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1340 (void)r;
1341 }
1342 WDT_HIT();
1343 }
1344 if (samples) *samples = (c + *wait) << 3;
1345 }
1346
1347
1348 //-----------------------------------------------------------------------------
1349 // Prepare iClass reader command to send to FPGA
1350 //-----------------------------------------------------------------------------
1351 void CodeIClassCommand(const uint8_t * cmd, int len)
1352 {
1353 int i, j, k;
1354 uint8_t b;
1355
1356 ToSendReset();
1357
1358 // Start of Communication: 1 out of 4
1359 ToSend[++ToSendMax] = 0xf0;
1360 ToSend[++ToSendMax] = 0x00;
1361 ToSend[++ToSendMax] = 0x0f;
1362 ToSend[++ToSendMax] = 0x00;
1363
1364 // Modulate the bytes
1365 for (i = 0; i < len; i++) {
1366 b = cmd[i];
1367 for(j = 0; j < 4; j++) {
1368 for(k = 0; k < 4; k++) {
1369 if(k == (b & 3)) {
1370 ToSend[++ToSendMax] = 0x0f;
1371 }
1372 else {
1373 ToSend[++ToSendMax] = 0x00;
1374 }
1375 }
1376 b >>= 2;
1377 }
1378 }
1379
1380 // End of Communication
1381 ToSend[++ToSendMax] = 0x00;
1382 ToSend[++ToSendMax] = 0x00;
1383 ToSend[++ToSendMax] = 0xf0;
1384 ToSend[++ToSendMax] = 0x00;
1385
1386 // Convert from last character reference to length
1387 ToSendMax++;
1388 }
1389
1390 void ReaderTransmitIClass(uint8_t* frame, int len)
1391 {
1392 int wait = 0;
1393 int samples = 0;
1394 int par = 0;
1395
1396 // This is tied to other size changes
1397 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1398 CodeIClassCommand(frame,len);
1399
1400 // Select the card
1401 TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
1402 if(trigger)
1403 LED_A_ON();
1404
1405 // Store reader command in buffer
1406 if (tracing) LogTrace(frame,len,rsamples,par,TRUE);
1407 }
1408
1409 //-----------------------------------------------------------------------------
1410 // Wait a certain time for tag response
1411 // If a response is captured return TRUE
1412 // If it takes too long return FALSE
1413 //-----------------------------------------------------------------------------
1414 static int GetIClassAnswer(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
1415 {
1416 // buffer needs to be 512 bytes
1417 int c;
1418
1419 // Set FPGA mode to "reader listen mode", no modulation (listen
1420 // only, since we are receiving, not transmitting).
1421 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1422
1423 // Now get the answer from the card
1424 Demod.output = receivedResponse;
1425 Demod.len = 0;
1426 Demod.state = DEMOD_UNSYNCD;
1427
1428 uint8_t b;
1429 if (elapsed) *elapsed = 0;
1430
1431 bool skip = FALSE;
1432
1433 c = 0;
1434 for(;;) {
1435 WDT_HIT();
1436
1437 if(BUTTON_PRESS()) return FALSE;
1438
1439 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1440 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1441 if (elapsed) (*elapsed)++;
1442 }
1443 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1444 if(c < timeout) { c++; } else { return FALSE; }
1445 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1446 skip = !skip;
1447 if(skip) continue;
1448 /*if(ManchesterDecoding((b>>4) & 0xf)) {
1449 *samples = ((c - 1) << 3) + 4;
1450 return TRUE;
1451 }*/
1452 if(ManchesterDecoding(b & 0x0f)) {
1453 *samples = c << 3;
1454 return TRUE;
1455 }
1456 }
1457 }
1458 }
1459
1460 int ReaderReceiveIClass(uint8_t* receivedAnswer)
1461 {
1462 int samples = 0;
1463 if (!GetIClassAnswer(receivedAnswer,160,&samples,0)) return FALSE;
1464 rsamples += samples;
1465 if (tracing) LogTrace(receivedAnswer,Demod.len,rsamples,Demod.parityBits,FALSE);
1466 if(samples == 0) return FALSE;
1467 return Demod.len;
1468 }
1469
1470 void setupIclassReader()
1471 {
1472 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1473 // Reset trace buffer
1474 iso14a_set_tracing(TRUE);
1475 iso14a_clear_trace();
1476
1477 // Setup SSC
1478 FpgaSetupSsc();
1479 // Start from off (no field generated)
1480 // Signal field is off with the appropriate LED
1481 LED_D_OFF();
1482 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1483 SpinDelay(200);
1484
1485 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1486
1487 // Now give it time to spin up.
1488 // Signal field is on with the appropriate LED
1489 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1490 SpinDelay(200);
1491 LED_A_ON();
1492
1493 }
1494
1495 // Reader iClass Anticollission
1496 void ReaderIClass(uint8_t arg0) {
1497 uint8_t act_all[] = { 0x0a };
1498 uint8_t identify[] = { 0x0c };
1499 uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1500 uint8_t readcheck_cc[]= { 0x88, 0x02 };
1501
1502 uint8_t card_data[24]={0};
1503 uint8_t last_csn[8]={0};
1504
1505 uint8_t* resp = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1506
1507 int read_status= 0;
1508 bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE;
1509
1510 setupIclassReader();
1511
1512 size_t datasize = 0;
1513 while(!BUTTON_PRESS())
1514 {
1515 WDT_HIT();
1516
1517 // Send act_all
1518 ReaderTransmitIClass(act_all, 1);
1519 // Card present?
1520 if(ReaderReceiveIClass(resp)) {
1521
1522 ReaderTransmitIClass(identify, 1);
1523
1524 if(ReaderReceiveIClass(resp) == 10) {
1525 //Copy the Anti-collision CSN to our select-packet
1526 memcpy(&select[1],resp,8);
1527 //Dbprintf("Anti-collision CSN: %02x %02x %02x %02x %02x %02x %02x %02x",resp[0], resp[1], resp[2],
1528 // resp[3], resp[4], resp[5],
1529 // resp[6], resp[7]);
1530 //Select the card
1531 ReaderTransmitIClass(select, sizeof(select));
1532
1533 if(ReaderReceiveIClass(resp) == 10) {
1534 //Save CSN in response data
1535 memcpy(card_data,resp,8);
1536 datasize += 8;
1537 //Flag that we got to at least stage 1, read CSN
1538 read_status = 1;
1539
1540 // Card selected
1541 //Dbprintf("Readcheck on Sector 2");
1542 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1543 if(ReaderReceiveIClass(resp) == 8) {
1544 //Save CC (e-purse) in response data
1545 memcpy(card_data+8,resp,8);
1546 datasize += 8;
1547 //Got both
1548 read_status = 2;
1549 }
1550
1551 LED_B_ON();
1552 //Send back to client, but don't bother if we already sent this
1553 if(memcmp(last_csn, card_data, 8) != 0)
1554 cmd_send(CMD_ACK,read_status,0,0,card_data,datasize);
1555
1556 //Save that we already sent this....
1557 if(read_status == 2)
1558 memcpy(last_csn, card_data, 8);
1559
1560 LED_B_OFF();
1561
1562 if(abort_after_read) break;
1563 }
1564 }
1565 }
1566
1567 if(traceLen > TRACE_SIZE) {
1568 DbpString("Trace full");
1569 break;
1570 }
1571 }
1572 LED_A_OFF();
1573 }
1574
1575 void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
1576 uint8_t act_all[] = { 0x0a };
1577 uint8_t identify[] = { 0x0c };
1578 uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1579 uint8_t readcheck_cc[]= { 0x88, 0x02 };
1580 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1581 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1582
1583 uint16_t crc = 0;
1584 uint8_t cardsize=0;
1585 bool read_success=false;
1586 uint8_t mem=0;
1587
1588 static struct memory_t{
1589 int k16;
1590 int book;
1591 int k2;
1592 int lockauth;
1593 int keyaccess;
1594 } memory;
1595
1596 uint8_t* resp = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1597
1598 setupIclassReader();
1599
1600
1601 for(int i=0;i<1;i++) {
1602
1603 if(traceLen > TRACE_SIZE) {
1604 DbpString("Trace full");
1605 break;
1606 }
1607
1608 if (BUTTON_PRESS()) break;
1609
1610 // Send act_all
1611 ReaderTransmitIClass(act_all, 1);
1612 // Card present?
1613 if(ReaderReceiveIClass(resp)) {
1614 ReaderTransmitIClass(identify, 1);
1615 if(ReaderReceiveIClass(resp) == 10) {
1616 // Select card
1617 memcpy(&select[1],resp,8);
1618 ReaderTransmitIClass(select, sizeof(select));
1619
1620 if(ReaderReceiveIClass(resp) == 10) {
1621 Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1622 resp[0], resp[1], resp[2],
1623 resp[3], resp[4], resp[5],
1624 resp[6], resp[7]);
1625 }
1626 // Card selected
1627 Dbprintf("Readcheck on Sector 2");
1628 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1629 if(ReaderReceiveIClass(resp) == 8) {
1630 Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x",
1631 resp[0], resp[1], resp[2],
1632 resp[3], resp[4], resp[5],
1633 resp[6], resp[7]);
1634 }else return;
1635 Dbprintf("Authenticate");
1636 //for now replay captured auth (as cc not updated)
1637 memcpy(check+5,MAC,4);
1638 //Dbprintf(" AA: %02x %02x %02x %02x",
1639 // check[5], check[6], check[7],check[8]);
1640 ReaderTransmitIClass(check, sizeof(check));
1641 if(ReaderReceiveIClass(resp) == 4) {
1642 Dbprintf(" AR: %02x %02x %02x %02x",
1643 resp[0], resp[1], resp[2],resp[3]);
1644 }else {
1645 Dbprintf("Error: Authentication Fail!");
1646 return;
1647 }
1648 Dbprintf("Dump Contents");
1649 //first get configuration block
1650 read_success=false;
1651 read[1]=1;
1652 uint8_t *blockno=&read[1];
1653 crc = iclass_crc16((char *)blockno,1);
1654 read[2] = crc >> 8;
1655 read[3] = crc & 0xff;
1656 while(!read_success){
1657 ReaderTransmitIClass(read, sizeof(read));
1658 if(ReaderReceiveIClass(resp) == 10) {
1659 read_success=true;
1660 mem=resp[5];
1661 memory.k16= (mem & 0x80);
1662 memory.book= (mem & 0x20);
1663 memory.k2= (mem & 0x8);
1664 memory.lockauth= (mem & 0x2);
1665 memory.keyaccess= (mem & 0x1);
1666
1667 }
1668 }
1669 if (memory.k16){
1670 cardsize=255;
1671 }else cardsize=32;
1672 //then loop around remaining blocks
1673 for(uint8_t j=0; j<cardsize; j++){
1674 read_success=false;
1675 uint8_t *blockno=&j;
1676 //crc_data[0]=j;
1677 read[1]=j;
1678 crc = iclass_crc16((char *)blockno,1);
1679 read[2] = crc >> 8;
1680 read[3] = crc & 0xff;
1681 while(!read_success){
1682 ReaderTransmitIClass(read, sizeof(read));
1683 if(ReaderReceiveIClass(resp) == 10) {
1684 read_success=true;
1685 Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
1686 j, resp[0], resp[1], resp[2],
1687 resp[3], resp[4], resp[5],
1688 resp[6], resp[7]);
1689 }
1690 }
1691 }
1692 }
1693 }
1694 WDT_HIT();
1695 }
1696
1697 LED_A_OFF();
1698 }
1699
1700 //2. Create Read method (cut-down from above) based off responses from 1.
1701 // Since we have the MAC could continue to use replay function.
1702 //3. Create Write method
1703 /*
1704 void IClass_iso14443A_write(uint8_t arg0, uint8_t blockNo, uint8_t *data, uint8_t *MAC) {
1705 uint8_t act_all[] = { 0x0a };
1706 uint8_t identify[] = { 0x0c };
1707 uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1708 uint8_t readcheck_cc[]= { 0x88, 0x02 };
1709 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1710 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1711 uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1712
1713 uint16_t crc = 0;
1714
1715 uint8_t* resp = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1716
1717 // Reset trace buffer
1718 memset(trace, 0x44, RECV_CMD_OFFSET);
1719 traceLen = 0;
1720
1721 // Setup SSC
1722 FpgaSetupSsc();
1723 // Start from off (no field generated)
1724 // Signal field is off with the appropriate LED
1725 LED_D_OFF();
1726 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1727 SpinDelay(200);
1728
1729 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1730
1731 // Now give it time to spin up.
1732 // Signal field is on with the appropriate LED
1733 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1734 SpinDelay(200);
1735
1736 LED_A_ON();
1737
1738 for(int i=0;i<1;i++) {
1739
1740 if(traceLen > TRACE_SIZE) {
1741 DbpString("Trace full");
1742 break;
1743 }
1744
1745 if (BUTTON_PRESS()) break;
1746
1747 // Send act_all
1748 ReaderTransmitIClass(act_all, 1);
1749 // Card present?
1750 if(ReaderReceiveIClass(resp)) {
1751 ReaderTransmitIClass(identify, 1);
1752 if(ReaderReceiveIClass(resp) == 10) {
1753 // Select card
1754 memcpy(&select[1],resp,8);
1755 ReaderTransmitIClass(select, sizeof(select));
1756
1757 if(ReaderReceiveIClass(resp) == 10) {
1758 Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1759 resp[0], resp[1], resp[2],
1760 resp[3], resp[4], resp[5],
1761 resp[6], resp[7]);
1762 }
1763 // Card selected
1764 Dbprintf("Readcheck on Sector 2");
1765 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1766 if(ReaderReceiveIClass(resp) == 8) {
1767 Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x",
1768 resp[0], resp[1], resp[2],
1769 resp[3], resp[4], resp[5],
1770 resp[6], resp[7]);
1771 }else return;
1772 Dbprintf("Authenticate");
1773 //for now replay captured auth (as cc not updated)
1774 memcpy(check+5,MAC,4);
1775 Dbprintf(" AA: %02x %02x %02x %02x",
1776 check[5], check[6], check[7],check[8]);
1777 ReaderTransmitIClass(check, sizeof(check));
1778 if(ReaderReceiveIClass(resp) == 4) {
1779 Dbprintf(" AR: %02x %02x %02x %02x",
1780 resp[0], resp[1], resp[2],resp[3]);
1781 }else {
1782 Dbprintf("Error: Authentication Fail!");
1783 return;
1784 }
1785 Dbprintf("Write Block");
1786
1787 //read configuration for max block number
1788 read_success=false;
1789 read[1]=1;
1790 uint8_t *blockno=&read[1];
1791 crc = iclass_crc16((char *)blockno,1);
1792 read[2] = crc >> 8;
1793 read[3] = crc & 0xff;
1794 while(!read_success){
1795 ReaderTransmitIClass(read, sizeof(read));
1796 if(ReaderReceiveIClass(resp) == 10) {
1797 read_success=true;
1798 mem=resp[5];
1799 memory.k16= (mem & 0x80);
1800 memory.book= (mem & 0x20);
1801 memory.k2= (mem & 0x8);
1802 memory.lockauth= (mem & 0x2);
1803 memory.keyaccess= (mem & 0x1);
1804
1805 }
1806 }
1807 if (memory.k16){
1808 cardsize=255;
1809 }else cardsize=32;
1810 //check card_size
1811
1812 memcpy(write+1,blockNo,1);
1813 memcpy(write+2,data,8);
1814 memcpy(write+10,mac,4);
1815 while(!send_success){
1816 ReaderTransmitIClass(write, sizeof(write));
1817 if(ReaderReceiveIClass(resp) == 10) {
1818 write_success=true;
1819 }
1820 }//
1821 }
1822 WDT_HIT();
1823 }
1824
1825 LED_A_OFF();
1826 }*/
Impressum, Datenschutz