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