]> git.zerfleddert.de Git - proxmark3-svn/blame_incremental - armsrc/iso14443a.c
Fixed writing em410x 40bits UID on T5555/T55x7 tags on 32bits systems
[proxmark3-svn] / armsrc / iso14443a.c
... / ...
CommitLineData
1//-----------------------------------------------------------------------------
2// Merlok - June 2011, 2012
3// Gerhard de Koning Gans - May 2008
4// Hagen Fritsch - June 2010
5//
6// This code is licensed to you under the terms of the GNU GPL, version 2 or,
7// at your option, any later version. See the LICENSE.txt file for the text of
8// the license.
9//-----------------------------------------------------------------------------
10// Routines to support ISO 14443 type A.
11//-----------------------------------------------------------------------------
12
13#include "proxmark3.h"
14#include "apps.h"
15#include "util.h"
16#include "string.h"
17
18#include "iso14443crc.h"
19#include "iso14443a.h"
20#include "crapto1.h"
21#include "mifareutil.h"
22
23static uint32_t iso14a_timeout;
24uint8_t *trace = (uint8_t *) BigBuf;
25int traceLen = 0;
26int rsamples = 0;
27int tracing = TRUE;
28uint8_t trigger = 0;
29
30// CARD TO READER - manchester
31// Sequence D: 11110000 modulation with subcarrier during first half
32// Sequence E: 00001111 modulation with subcarrier during second half
33// Sequence F: 00000000 no modulation with subcarrier
34// READER TO CARD - miller
35// Sequence X: 00001100 drop after half a period
36// Sequence Y: 00000000 no drop
37// Sequence Z: 11000000 drop at start
38#define SEC_D 0xf0
39#define SEC_E 0x0f
40#define SEC_F 0x00
41#define SEC_X 0x0c
42#define SEC_Y 0x00
43#define SEC_Z 0xc0
44
45const uint8_t OddByteParity[256] = {
46 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
47 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
48 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
49 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
50 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
51 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
52 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
57 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
58 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
59 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
60 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
61 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
62};
63
64
65void iso14a_set_trigger(int enable) {
66 trigger = enable;
67}
68
69void iso14a_clear_tracelen(void) {
70 traceLen = 0;
71}
72void iso14a_set_tracing(int enable) {
73 tracing = enable;
74}
75
76//-----------------------------------------------------------------------------
77// Generate the parity value for a byte sequence
78//
79//-----------------------------------------------------------------------------
80byte_t oddparity (const byte_t bt)
81{
82 return OddByteParity[bt];
83}
84
85uint32_t GetParity(const uint8_t * pbtCmd, int iLen)
86{
87 int i;
88 uint32_t dwPar = 0;
89
90 // Generate the encrypted data
91 for (i = 0; i < iLen; i++) {
92 // Save the encrypted parity bit
93 dwPar |= ((OddByteParity[pbtCmd[i]]) << i);
94 }
95 return dwPar;
96}
97
98void AppendCrc14443a(uint8_t* data, int len)
99{
100 ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
101}
102
103// The function LogTrace() is also used by the iClass implementation in iClass.c
104int RAMFUNC LogTrace(const uint8_t * btBytes, int iLen, int iSamples, uint32_t dwParity, int bReader)
105{
106 // Return when trace is full
107 if (traceLen >= TRACE_SIZE) return FALSE;
108
109 // Trace the random, i'm curious
110 rsamples += iSamples;
111 trace[traceLen++] = ((rsamples >> 0) & 0xff);
112 trace[traceLen++] = ((rsamples >> 8) & 0xff);
113 trace[traceLen++] = ((rsamples >> 16) & 0xff);
114 trace[traceLen++] = ((rsamples >> 24) & 0xff);
115 if (!bReader) {
116 trace[traceLen - 1] |= 0x80;
117 }
118 trace[traceLen++] = ((dwParity >> 0) & 0xff);
119 trace[traceLen++] = ((dwParity >> 8) & 0xff);
120 trace[traceLen++] = ((dwParity >> 16) & 0xff);
121 trace[traceLen++] = ((dwParity >> 24) & 0xff);
122 trace[traceLen++] = iLen;
123 memcpy(trace + traceLen, btBytes, iLen);
124 traceLen += iLen;
125 return TRUE;
126}
127
128//-----------------------------------------------------------------------------
129// The software UART that receives commands from the reader, and its state
130// variables.
131//-----------------------------------------------------------------------------
132static tUart Uart;
133
134static RAMFUNC int MillerDecoding(int bit)
135{
136 //int error = 0;
137 int bitright;
138
139 if(!Uart.bitBuffer) {
140 Uart.bitBuffer = bit ^ 0xFF0;
141 return FALSE;
142 }
143 else {
144 Uart.bitBuffer <<= 4;
145 Uart.bitBuffer ^= bit;
146 }
147
148 int EOC = FALSE;
149
150 if(Uart.state != STATE_UNSYNCD) {
151 Uart.posCnt++;
152
153 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
154 bit = 0x00;
155 }
156 else {
157 bit = 0x01;
158 }
159 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
160 bitright = 0x00;
161 }
162 else {
163 bitright = 0x01;
164 }
165 if(bit != bitright) { bit = bitright; }
166
167 if(Uart.posCnt == 1) {
168 // measurement first half bitperiod
169 if(!bit) {
170 Uart.drop = DROP_FIRST_HALF;
171 }
172 }
173 else {
174 // measurement second half bitperiod
175 if(!bit & (Uart.drop == DROP_NONE)) {
176 Uart.drop = DROP_SECOND_HALF;
177 }
178 else if(!bit) {
179 // measured a drop in first and second half
180 // which should not be possible
181 Uart.state = STATE_ERROR_WAIT;
182 //error = 0x01;
183 }
184
185 Uart.posCnt = 0;
186
187 switch(Uart.state) {
188 case STATE_START_OF_COMMUNICATION:
189 Uart.shiftReg = 0;
190 if(Uart.drop == DROP_SECOND_HALF) {
191 // error, should not happen in SOC
192 Uart.state = STATE_ERROR_WAIT;
193 //error = 0x02;
194 }
195 else {
196 // correct SOC
197 Uart.state = STATE_MILLER_Z;
198 }
199 break;
200
201 case STATE_MILLER_Z:
202 Uart.bitCnt++;
203 Uart.shiftReg >>= 1;
204 if(Uart.drop == DROP_NONE) {
205 // logic '0' followed by sequence Y
206 // end of communication
207 Uart.state = STATE_UNSYNCD;
208 EOC = TRUE;
209 }
210 // if(Uart.drop == DROP_FIRST_HALF) {
211 // Uart.state = STATE_MILLER_Z; stay the same
212 // we see a logic '0' }
213 if(Uart.drop == DROP_SECOND_HALF) {
214 // we see a logic '1'
215 Uart.shiftReg |= 0x100;
216 Uart.state = STATE_MILLER_X;
217 }
218 break;
219
220 case STATE_MILLER_X:
221 Uart.shiftReg >>= 1;
222 if(Uart.drop == DROP_NONE) {
223 // sequence Y, we see a '0'
224 Uart.state = STATE_MILLER_Y;
225 Uart.bitCnt++;
226 }
227 if(Uart.drop == DROP_FIRST_HALF) {
228 // Would be STATE_MILLER_Z
229 // but Z does not follow X, so error
230 Uart.state = STATE_ERROR_WAIT;
231 //error = 0x03;
232 }
233 if(Uart.drop == DROP_SECOND_HALF) {
234 // We see a '1' and stay in state X
235 Uart.shiftReg |= 0x100;
236 Uart.bitCnt++;
237 }
238 break;
239
240 case STATE_MILLER_Y:
241 Uart.bitCnt++;
242 Uart.shiftReg >>= 1;
243 if(Uart.drop == DROP_NONE) {
244 // logic '0' followed by sequence Y
245 // end of communication
246 Uart.state = STATE_UNSYNCD;
247 EOC = TRUE;
248 }
249 if(Uart.drop == DROP_FIRST_HALF) {
250 // we see a '0'
251 Uart.state = STATE_MILLER_Z;
252 }
253 if(Uart.drop == DROP_SECOND_HALF) {
254 // We see a '1' and go to state X
255 Uart.shiftReg |= 0x100;
256 Uart.state = STATE_MILLER_X;
257 }
258 break;
259
260 case STATE_ERROR_WAIT:
261 // That went wrong. Now wait for at least two bit periods
262 // and try to sync again
263 if(Uart.drop == DROP_NONE) {
264 Uart.highCnt = 6;
265 Uart.state = STATE_UNSYNCD;
266 }
267 break;
268
269 default:
270 Uart.state = STATE_UNSYNCD;
271 Uart.highCnt = 0;
272 break;
273 }
274
275 Uart.drop = DROP_NONE;
276
277 // should have received at least one whole byte...
278 if((Uart.bitCnt == 2) && EOC && (Uart.byteCnt > 0)) {
279 return TRUE;
280 }
281
282 if(Uart.bitCnt == 9) {
283 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
284 Uart.byteCnt++;
285
286 Uart.parityBits <<= 1;
287 Uart.parityBits ^= ((Uart.shiftReg >> 8) & 0x01);
288
289 if(EOC) {
290 // when End of Communication received and
291 // all data bits processed..
292 return TRUE;
293 }
294 Uart.bitCnt = 0;
295 }
296
297 /*if(error) {
298 Uart.output[Uart.byteCnt] = 0xAA;
299 Uart.byteCnt++;
300 Uart.output[Uart.byteCnt] = error & 0xFF;
301 Uart.byteCnt++;
302 Uart.output[Uart.byteCnt] = 0xAA;
303 Uart.byteCnt++;
304 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
305 Uart.byteCnt++;
306 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
307 Uart.byteCnt++;
308 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
309 Uart.byteCnt++;
310 Uart.output[Uart.byteCnt] = 0xAA;
311 Uart.byteCnt++;
312 return TRUE;
313 }*/
314 }
315
316 }
317 else {
318 bit = Uart.bitBuffer & 0xf0;
319 bit >>= 4;
320 bit ^= 0x0F;
321 if(bit) {
322 // should have been high or at least (4 * 128) / fc
323 // according to ISO this should be at least (9 * 128 + 20) / fc
324 if(Uart.highCnt == 8) {
325 // we went low, so this could be start of communication
326 // it turns out to be safer to choose a less significant
327 // syncbit... so we check whether the neighbour also represents the drop
328 Uart.posCnt = 1; // apparently we are busy with our first half bit period
329 Uart.syncBit = bit & 8;
330 Uart.samples = 3;
331 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
332 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
333 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
334 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
335 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
336 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
337 Uart.syncBit = 8;
338
339 // the first half bit period is expected in next sample
340 Uart.posCnt = 0;
341 Uart.samples = 3;
342 }
343 }
344 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
345
346 Uart.syncBit <<= 4;
347 Uart.state = STATE_START_OF_COMMUNICATION;
348 Uart.drop = DROP_FIRST_HALF;
349 Uart.bitCnt = 0;
350 Uart.byteCnt = 0;
351 Uart.parityBits = 0;
352 //error = 0;
353 }
354 else {
355 Uart.highCnt = 0;
356 }
357 }
358 else {
359 if(Uart.highCnt < 8) {
360 Uart.highCnt++;
361 }
362 }
363 }
364
365 return FALSE;
366}
367
368//=============================================================================
369// ISO 14443 Type A - Manchester
370//=============================================================================
371static tDemod Demod;
372
373static RAMFUNC int ManchesterDecoding(int v)
374{
375 int bit;
376 int modulation;
377 //int error = 0;
378
379 if(!Demod.buff) {
380 Demod.buff = 1;
381 Demod.buffer = v;
382 return FALSE;
383 }
384 else {
385 bit = Demod.buffer;
386 Demod.buffer = v;
387 }
388
389 if(Demod.state==DEMOD_UNSYNCD) {
390 Demod.output[Demod.len] = 0xfa;
391 Demod.syncBit = 0;
392 //Demod.samples = 0;
393 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
394
395 if(bit & 0x08) {
396 Demod.syncBit = 0x08;
397 }
398
399 if(bit & 0x04) {
400 if(Demod.syncBit) {
401 bit <<= 4;
402 }
403 Demod.syncBit = 0x04;
404 }
405
406 if(bit & 0x02) {
407 if(Demod.syncBit) {
408 bit <<= 2;
409 }
410 Demod.syncBit = 0x02;
411 }
412
413 if(bit & 0x01 && Demod.syncBit) {
414 Demod.syncBit = 0x01;
415 }
416
417 if(Demod.syncBit) {
418 Demod.len = 0;
419 Demod.state = DEMOD_START_OF_COMMUNICATION;
420 Demod.sub = SUB_FIRST_HALF;
421 Demod.bitCount = 0;
422 Demod.shiftReg = 0;
423 Demod.parityBits = 0;
424 Demod.samples = 0;
425 if(Demod.posCount) {
426 if(trigger) LED_A_OFF();
427 switch(Demod.syncBit) {
428 case 0x08: Demod.samples = 3; break;
429 case 0x04: Demod.samples = 2; break;
430 case 0x02: Demod.samples = 1; break;
431 case 0x01: Demod.samples = 0; break;
432 }
433 }
434 //error = 0;
435 }
436 }
437 else {
438 //modulation = bit & Demod.syncBit;
439 modulation = ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
440
441 Demod.samples += 4;
442
443 if(Demod.posCount==0) {
444 Demod.posCount = 1;
445 if(modulation) {
446 Demod.sub = SUB_FIRST_HALF;
447 }
448 else {
449 Demod.sub = SUB_NONE;
450 }
451 }
452 else {
453 Demod.posCount = 0;
454 if(modulation && (Demod.sub == SUB_FIRST_HALF)) {
455 if(Demod.state!=DEMOD_ERROR_WAIT) {
456 Demod.state = DEMOD_ERROR_WAIT;
457 Demod.output[Demod.len] = 0xaa;
458 //error = 0x01;
459 }
460 }
461 else if(modulation) {
462 Demod.sub = SUB_SECOND_HALF;
463 }
464
465 switch(Demod.state) {
466 case DEMOD_START_OF_COMMUNICATION:
467 if(Demod.sub == SUB_FIRST_HALF) {
468 Demod.state = DEMOD_MANCHESTER_D;
469 }
470 else {
471 Demod.output[Demod.len] = 0xab;
472 Demod.state = DEMOD_ERROR_WAIT;
473 //error = 0x02;
474 }
475 break;
476
477 case DEMOD_MANCHESTER_D:
478 case DEMOD_MANCHESTER_E:
479 if(Demod.sub == SUB_FIRST_HALF) {
480 Demod.bitCount++;
481 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
482 Demod.state = DEMOD_MANCHESTER_D;
483 }
484 else if(Demod.sub == SUB_SECOND_HALF) {
485 Demod.bitCount++;
486 Demod.shiftReg >>= 1;
487 Demod.state = DEMOD_MANCHESTER_E;
488 }
489 else {
490 Demod.state = DEMOD_MANCHESTER_F;
491 }
492 break;
493
494 case DEMOD_MANCHESTER_F:
495 // Tag response does not need to be a complete byte!
496 if(Demod.len > 0 || Demod.bitCount > 0) {
497 if(Demod.bitCount > 0) {
498 Demod.shiftReg >>= (9 - Demod.bitCount);
499 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
500 Demod.len++;
501 // No parity bit, so just shift a 0
502 Demod.parityBits <<= 1;
503 }
504
505 Demod.state = DEMOD_UNSYNCD;
506 return TRUE;
507 }
508 else {
509 Demod.output[Demod.len] = 0xad;
510 Demod.state = DEMOD_ERROR_WAIT;
511 //error = 0x03;
512 }
513 break;
514
515 case DEMOD_ERROR_WAIT:
516 Demod.state = DEMOD_UNSYNCD;
517 break;
518
519 default:
520 Demod.output[Demod.len] = 0xdd;
521 Demod.state = DEMOD_UNSYNCD;
522 break;
523 }
524
525 if(Demod.bitCount>=9) {
526 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
527 Demod.len++;
528
529 Demod.parityBits <<= 1;
530 Demod.parityBits ^= ((Demod.shiftReg >> 8) & 0x01);
531
532 Demod.bitCount = 0;
533 Demod.shiftReg = 0;
534 }
535
536 /*if(error) {
537 Demod.output[Demod.len] = 0xBB;
538 Demod.len++;
539 Demod.output[Demod.len] = error & 0xFF;
540 Demod.len++;
541 Demod.output[Demod.len] = 0xBB;
542 Demod.len++;
543 Demod.output[Demod.len] = bit & 0xFF;
544 Demod.len++;
545 Demod.output[Demod.len] = Demod.buffer & 0xFF;
546 Demod.len++;
547 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
548 Demod.len++;
549 Demod.output[Demod.len] = 0xBB;
550 Demod.len++;
551 return TRUE;
552 }*/
553
554 }
555
556 } // end (state != UNSYNCED)
557
558 return FALSE;
559}
560
561//=============================================================================
562// Finally, a `sniffer' for ISO 14443 Type A
563// Both sides of communication!
564//=============================================================================
565
566//-----------------------------------------------------------------------------
567// Record the sequence of commands sent by the reader to the tag, with
568// triggering so that we start recording at the point that the tag is moved
569// near the reader.
570//-----------------------------------------------------------------------------
571void RAMFUNC SnoopIso14443a(uint8_t param) {
572 // param:
573 // bit 0 - trigger from first card answer
574 // bit 1 - trigger from first reader 7-bit request
575
576 LEDsoff();
577 // init trace buffer
578 traceLen = 0;
579 memset(trace, 0x44, TRACE_SIZE);
580
581 // We won't start recording the frames that we acquire until we trigger;
582 // a good trigger condition to get started is probably when we see a
583 // response from the tag.
584 // triggered == FALSE -- to wait first for card
585 int triggered = !(param & 0x03);
586
587 // The command (reader -> tag) that we're receiving.
588 // The length of a received command will in most cases be no more than 18 bytes.
589 // So 32 should be enough!
590 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
591 // The response (tag -> reader) that we're receiving.
592 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
593
594 // As we receive stuff, we copy it from receivedCmd or receivedResponse
595 // into trace, along with its length and other annotations.
596 //uint8_t *trace = (uint8_t *)BigBuf;
597
598 // The DMA buffer, used to stream samples from the FPGA
599 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
600 int8_t *data = dmaBuf;
601 int maxDataLen = 0;
602 int dataLen = 0;
603
604 // Set up the demodulator for tag -> reader responses.
605 Demod.output = receivedResponse;
606 Demod.len = 0;
607 Demod.state = DEMOD_UNSYNCD;
608
609 // Set up the demodulator for the reader -> tag commands
610 memset(&Uart, 0, sizeof(Uart));
611 Uart.output = receivedCmd;
612 Uart.byteCntMax = 32; // was 100 (greg)//////////////////
613 Uart.state = STATE_UNSYNCD;
614
615 // Setup for the DMA.
616 FpgaSetupSsc();
617 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
618
619 // And put the FPGA in the appropriate mode
620 // Signal field is off with the appropriate LED
621 LED_D_OFF();
622 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
623 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
624
625 // Count of samples received so far, so that we can include timing
626 // information in the trace buffer.
627 rsamples = 0;
628 // And now we loop, receiving samples.
629 while(true) {
630 if(BUTTON_PRESS()) {
631 DbpString("cancelled by button");
632 goto done;
633 }
634
635 LED_A_ON();
636 WDT_HIT();
637
638 int register readBufDataP = data - dmaBuf;
639 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
640 if (readBufDataP <= dmaBufDataP){
641 dataLen = dmaBufDataP - readBufDataP;
642 } else {
643 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP + 1;
644 }
645 // test for length of buffer
646 if(dataLen > maxDataLen) {
647 maxDataLen = dataLen;
648 if(dataLen > 400) {
649 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen);
650 goto done;
651 }
652 }
653 if(dataLen < 1) continue;
654
655 // primary buffer was stopped( <-- we lost data!
656 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
657 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
658 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
659 Dbprintf("RxEmpty ERROR!!! %d", dataLen); // temporary
660 }
661 // secondary buffer sets as primary, secondary buffer was stopped
662 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
663 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
664 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
665 }
666
667 LED_A_OFF();
668
669 rsamples += 4;
670 if(MillerDecoding((data[0] & 0xF0) >> 4)) {
671 LED_C_ON();
672
673 // check - if there is a short 7bit request from reader
674 if ((!triggered) && (param & 0x02) && (Uart.byteCnt == 1) && (Uart.bitCnt = 9)) triggered = TRUE;
675
676 if(triggered) {
677 if (!LogTrace(receivedCmd, Uart.byteCnt, 0 - Uart.samples, Uart.parityBits, TRUE)) break;
678 }
679 /* And ready to receive another command. */
680 Uart.state = STATE_UNSYNCD;
681 /* And also reset the demod code, which might have been */
682 /* false-triggered by the commands from the reader. */
683 Demod.state = DEMOD_UNSYNCD;
684 LED_B_OFF();
685 }
686
687 if(ManchesterDecoding(data[0] & 0x0F)) {
688 LED_B_ON();
689
690 if (!LogTrace(receivedResponse, Demod.len, 0 - Demod.samples, Demod.parityBits, FALSE)) break;
691
692 if ((!triggered) && (param & 0x01)) triggered = TRUE;
693
694 // And ready to receive another response.
695 memset(&Demod, 0, sizeof(Demod));
696 Demod.output = receivedResponse;
697 Demod.state = DEMOD_UNSYNCD;
698 LED_C_OFF();
699 }
700
701 data++;
702 if(data > dmaBuf + DMA_BUFFER_SIZE) {
703 data = dmaBuf;
704 }
705 } // main cycle
706
707 DbpString("COMMAND FINISHED");
708
709done:
710 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
711 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen, Uart.state, Uart.byteCnt);
712 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
713 LEDsoff();
714}
715
716//-----------------------------------------------------------------------------
717// Prepare tag messages
718//-----------------------------------------------------------------------------
719static void CodeIso14443aAsTagPar(const uint8_t *cmd, int len, uint32_t dwParity)
720{
721 int i;
722
723 ToSendReset();
724
725 // Correction bit, might be removed when not needed
726 ToSendStuffBit(0);
727 ToSendStuffBit(0);
728 ToSendStuffBit(0);
729 ToSendStuffBit(0);
730 ToSendStuffBit(1); // 1
731 ToSendStuffBit(0);
732 ToSendStuffBit(0);
733 ToSendStuffBit(0);
734
735 // Send startbit
736 ToSend[++ToSendMax] = SEC_D;
737
738 for(i = 0; i < len; i++) {
739 int j;
740 uint8_t b = cmd[i];
741
742 // Data bits
743 for(j = 0; j < 8; j++) {
744 if(b & 1) {
745 ToSend[++ToSendMax] = SEC_D;
746 } else {
747 ToSend[++ToSendMax] = SEC_E;
748 }
749 b >>= 1;
750 }
751
752 // Get the parity bit
753 if ((dwParity >> i) & 0x01) {
754 ToSend[++ToSendMax] = SEC_D;
755 } else {
756 ToSend[++ToSendMax] = SEC_E;
757 }
758 }
759
760 // Send stopbit
761 ToSend[++ToSendMax] = SEC_F;
762
763 // Convert from last byte pos to length
764 ToSendMax++;
765}
766
767static void CodeIso14443aAsTag(const uint8_t *cmd, int len){
768 CodeIso14443aAsTagPar(cmd, len, GetParity(cmd, len));
769}
770
771//-----------------------------------------------------------------------------
772// This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
773//-----------------------------------------------------------------------------
774static void CodeStrangeAnswerAsTag()
775{
776 int i;
777
778 ToSendReset();
779
780 // Correction bit, might be removed when not needed
781 ToSendStuffBit(0);
782 ToSendStuffBit(0);
783 ToSendStuffBit(0);
784 ToSendStuffBit(0);
785 ToSendStuffBit(1); // 1
786 ToSendStuffBit(0);
787 ToSendStuffBit(0);
788 ToSendStuffBit(0);
789
790 // Send startbit
791 ToSend[++ToSendMax] = SEC_D;
792
793 // 0
794 ToSend[++ToSendMax] = SEC_E;
795
796 // 0
797 ToSend[++ToSendMax] = SEC_E;
798
799 // 1
800 ToSend[++ToSendMax] = SEC_D;
801
802 // Send stopbit
803 ToSend[++ToSendMax] = SEC_F;
804
805 // Flush the buffer in FPGA!!
806 for(i = 0; i < 5; i++) {
807 ToSend[++ToSendMax] = SEC_F;
808 }
809
810 // Convert from last byte pos to length
811 ToSendMax++;
812}
813
814static void Code4bitAnswerAsTag(uint8_t cmd)
815{
816 int i;
817
818 ToSendReset();
819
820 // Correction bit, might be removed when not needed
821 ToSendStuffBit(0);
822 ToSendStuffBit(0);
823 ToSendStuffBit(0);
824 ToSendStuffBit(0);
825 ToSendStuffBit(1); // 1
826 ToSendStuffBit(0);
827 ToSendStuffBit(0);
828 ToSendStuffBit(0);
829
830 // Send startbit
831 ToSend[++ToSendMax] = SEC_D;
832
833 uint8_t b = cmd;
834 for(i = 0; i < 4; i++) {
835 if(b & 1) {
836 ToSend[++ToSendMax] = SEC_D;
837 } else {
838 ToSend[++ToSendMax] = SEC_E;
839 }
840 b >>= 1;
841 }
842
843 // Send stopbit
844 ToSend[++ToSendMax] = SEC_F;
845
846 // Flush the buffer in FPGA!!
847 for(i = 0; i < 5; i++) {
848 ToSend[++ToSendMax] = SEC_F;
849 }
850
851 // Convert from last byte pos to length
852 ToSendMax++;
853}
854
855//-----------------------------------------------------------------------------
856// Wait for commands from reader
857// Stop when button is pressed
858// Or return TRUE when command is captured
859//-----------------------------------------------------------------------------
860static int GetIso14443aCommandFromReader(uint8_t *received, int *len, int maxLen)
861{
862 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
863 // only, since we are receiving, not transmitting).
864 // Signal field is off with the appropriate LED
865 LED_D_OFF();
866 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
867
868 // Now run a `software UART' on the stream of incoming samples.
869 Uart.output = received;
870 Uart.byteCntMax = maxLen;
871 Uart.state = STATE_UNSYNCD;
872
873 for(;;) {
874 WDT_HIT();
875
876 if(BUTTON_PRESS()) return FALSE;
877
878 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
879 AT91C_BASE_SSC->SSC_THR = 0x00;
880 }
881 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
882 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
883 if(MillerDecoding((b & 0xf0) >> 4)) {
884 *len = Uart.byteCnt;
885 return TRUE;
886 }
887 if(MillerDecoding(b & 0x0f)) {
888 *len = Uart.byteCnt;
889 return TRUE;
890 }
891 }
892 }
893}
894static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded);
895
896//-----------------------------------------------------------------------------
897// Main loop of simulated tag: receive commands from reader, decide what
898// response to send, and send it.
899//-----------------------------------------------------------------------------
900void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd)
901{
902 // Enable and clear the trace
903 tracing = TRUE;
904 traceLen = 0;
905 memset(trace, 0x44, TRACE_SIZE);
906
907 // This function contains the tag emulation
908 uint8_t sak;
909
910 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
911 uint8_t response1[2];
912
913 switch (tagType) {
914 case 1: { // MIFARE Classic
915 // Says: I am Mifare 1k - original line
916 response1[0] = 0x04;
917 response1[1] = 0x00;
918 sak = 0x08;
919 } break;
920 case 2: { // MIFARE Ultralight
921 // Says: I am a stupid memory tag, no crypto
922 response1[0] = 0x04;
923 response1[1] = 0x00;
924 sak = 0x00;
925 } break;
926 case 3: { // MIFARE DESFire
927 // Says: I am a DESFire tag, ph33r me
928 response1[0] = 0x04;
929 response1[1] = 0x03;
930 sak = 0x20;
931 } break;
932 case 4: { // ISO/IEC 14443-4
933 // Says: I am a javacard (JCOP)
934 response1[0] = 0x04;
935 response1[1] = 0x00;
936 sak = 0x28;
937 } break;
938 default: {
939 Dbprintf("Error: unkown tagtype (%d)",tagType);
940 return;
941 } break;
942 }
943
944 // The second response contains the (mandatory) first 24 bits of the UID
945 uint8_t response2[5];
946
947 // Check if the uid uses the (optional) part
948 uint8_t response2a[5];
949 if (uid_2nd) {
950 response2[0] = 0x88;
951 num_to_bytes(uid_1st,3,response2+1);
952 num_to_bytes(uid_2nd,4,response2a);
953 response2a[4] = response2a[0] ^ response2a[1] ^ response2a[2] ^ response2a[3];
954
955 // Configure the ATQA and SAK accordingly
956 response1[0] |= 0x40;
957 sak |= 0x04;
958 } else {
959 num_to_bytes(uid_1st,4,response2);
960 // Configure the ATQA and SAK accordingly
961 response1[0] &= 0xBF;
962 sak &= 0xFB;
963 }
964
965 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
966 response2[4] = response2[0] ^ response2[1] ^ response2[2] ^ response2[3];
967
968 // Prepare the mandatory SAK (for 4 and 7 byte UID)
969 uint8_t response3[3];
970 response3[0] = sak;
971 ComputeCrc14443(CRC_14443_A, response3, 1, &response3[1], &response3[2]);
972
973 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
974 uint8_t response3a[3];
975 response3a[0] = sak & 0xFB;
976 ComputeCrc14443(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]);
977
978 uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
979 uint8_t response6[] = { 0x03, 0x3B, 0x00, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
980 ComputeCrc14443(CRC_14443_A, response6, 3, &response6[3], &response6[4]);
981
982 uint8_t *resp;
983 int respLen;
984
985 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
986 // This will need
987 // 144 data bits (18 * 8)
988 // 18 parity bits
989 // 2 Start and stop
990 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
991 // 1 just for the case
992 // ----------- +
993 // 166
994 //
995 // 166 bytes, since every bit that needs to be send costs us a byte
996 //
997
998 // Respond with card type
999 uint8_t *resp1 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
1000 int resp1Len;
1001
1002 // Anticollision cascade1 - respond with uid
1003 uint8_t *resp2 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 166);
1004 int resp2Len;
1005
1006 // Anticollision cascade2 - respond with 2nd half of uid if asked
1007 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1008 uint8_t *resp2a = (((uint8_t *)BigBuf) + 1140);
1009 int resp2aLen;
1010
1011 // Acknowledge select - cascade 1
1012 uint8_t *resp3 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*2));
1013 int resp3Len;
1014
1015 // Acknowledge select - cascade 2
1016 uint8_t *resp3a = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*3));
1017 int resp3aLen;
1018
1019 // Response to a read request - not implemented atm
1020 uint8_t *resp4 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*4));
1021 int resp4Len;
1022
1023 // Authenticate response - nonce
1024 uint8_t *resp5 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*5));
1025 int resp5Len;
1026
1027 // Authenticate response - nonce
1028 uint8_t *resp6 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*6));
1029 int resp6Len;
1030
1031 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
1032 int len;
1033
1034 // To control where we are in the protocol
1035 int order = 0;
1036 int lastorder;
1037
1038 // Just to allow some checks
1039 int happened = 0;
1040 int happened2 = 0;
1041
1042 int cmdsRecvd = 0;
1043 uint8_t* respdata = NULL;
1044 int respsize = 0;
1045 uint8_t nack = 0x04;
1046
1047 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
1048
1049 // Prepare the responses of the anticollision phase
1050 // there will be not enough time to do this at the moment the reader sends it REQA
1051
1052 // Answer to request
1053 CodeIso14443aAsTag(response1, sizeof(response1));
1054 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
1055
1056 // Send our UID (cascade 1)
1057 CodeIso14443aAsTag(response2, sizeof(response2));
1058 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
1059
1060 // Answer to select (cascade1)
1061 CodeIso14443aAsTag(response3, sizeof(response3));
1062 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
1063
1064 // Send the cascade 2 2nd part of the uid
1065 CodeIso14443aAsTag(response2a, sizeof(response2a));
1066 memcpy(resp2a, ToSend, ToSendMax); resp2aLen = ToSendMax;
1067
1068 // Answer to select (cascade 2)
1069 CodeIso14443aAsTag(response3a, sizeof(response3a));
1070 memcpy(resp3a, ToSend, ToSendMax); resp3aLen = ToSendMax;
1071
1072 // Strange answer is an example of rare message size (3 bits)
1073 CodeStrangeAnswerAsTag();
1074 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1075
1076 // Authentication answer (random nonce)
1077 CodeIso14443aAsTag(response5, sizeof(response5));
1078 memcpy(resp5, ToSend, ToSendMax); resp5Len = ToSendMax;
1079
1080 // dummy ATS (pseudo-ATR), answer to RATS
1081 CodeIso14443aAsTag(response6, sizeof(response6));
1082 memcpy(resp6, ToSend, ToSendMax); resp6Len = ToSendMax;
1083
1084 // We need to listen to the high-frequency, peak-detected path.
1085 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1086 FpgaSetupSsc();
1087
1088 cmdsRecvd = 0;
1089
1090 LED_A_ON();
1091 for(;;) {
1092
1093 if(!GetIso14443aCommandFromReader(receivedCmd, &len, RECV_CMD_SIZE)) {
1094 DbpString("button press");
1095 break;
1096 }
1097 // doob - added loads of debug strings so we can see what the reader is saying to us during the sim as hi14alist is not populated
1098 // Okay, look at the command now.
1099 lastorder = order;
1100 if(receivedCmd[0] == 0x26) { // Received a REQUEST
1101 resp = resp1; respLen = resp1Len; order = 1;
1102 respdata = response1;
1103 respsize = sizeof(response1);
1104 } else if(receivedCmd[0] == 0x52) { // Received a WAKEUP
1105 resp = resp1; respLen = resp1Len; order = 6;
1106 respdata = response1;
1107 respsize = sizeof(response1);
1108 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // Received request for UID (cascade 1)
1109 resp = resp2; respLen = resp2Len; order = 2;
1110 respdata = response2;
1111 respsize = sizeof(response2);
1112 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x95) { // Received request for UID (cascade 2)
1113 resp = resp2a; respLen = resp2aLen; order = 20;
1114 respdata = response2a;
1115 respsize = sizeof(response2a);
1116 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x93) { // Received a SELECT (cascade 1)
1117 resp = resp3; respLen = resp3Len; order = 3;
1118 respdata = response3;
1119 respsize = sizeof(response3);
1120 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2)
1121 resp = resp3a; respLen = resp3aLen; order = 30;
1122 respdata = response3a;
1123 respsize = sizeof(response3a);
1124 } else if(receivedCmd[0] == 0x30) { // Received a (plain) READ
1125 resp = resp4; respLen = resp4Len; order = 4; // Do nothing
1126 Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
1127 respdata = &nack;
1128 respsize = sizeof(nack); // 4-bit answer
1129 } else if(receivedCmd[0] == 0x50) { // Received a HALT
1130 DbpString("Reader requested we HALT!:");
1131 // Do not respond
1132 resp = resp1; respLen = 0; order = 0;
1133 respdata = NULL;
1134 respsize = 0;
1135 } else if(receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61) { // Received an authentication request
1136 resp = resp5; respLen = resp5Len; order = 7;
1137 respdata = response5;
1138 respsize = sizeof(response5);
1139 } else if(receivedCmd[0] == 0xE0) { // Received a RATS request
1140 resp = resp6; respLen = resp6Len; order = 70;
1141 respdata = response6;
1142 respsize = sizeof(response6);
1143 } else {
1144 // Never seen this command before
1145 Dbprintf("Received (len=%d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1146 len,
1147 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1148 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1149 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1150 // Do not respond
1151 resp = resp1; respLen = 0; order = 0;
1152 respdata = NULL;
1153 respsize = 0;
1154 }
1155
1156 // Count number of wakeups received after a halt
1157 if(order == 6 && lastorder == 5) { happened++; }
1158
1159 // Count number of other messages after a halt
1160 if(order != 6 && lastorder == 5) { happened2++; }
1161
1162 // Look at last parity bit to determine timing of answer
1163 if((Uart.parityBits & 0x01) || receivedCmd[0] == 0x52) {
1164 // 1236, so correction bit needed
1165 //i = 0;
1166 }
1167
1168 if(cmdsRecvd > 999) {
1169 DbpString("1000 commands later...");
1170 break;
1171 } else {
1172 cmdsRecvd++;
1173 }
1174
1175 if(respLen > 0) {
1176 EmSendCmd14443aRaw(resp, respLen, receivedCmd[0] == 0x52);
1177 }
1178
1179 if (tracing) {
1180 LogTrace(receivedCmd,len, 0, Uart.parityBits, TRUE);
1181 if (respdata != NULL) {
1182 LogTrace(respdata,respsize, 0, SwapBits(GetParity(respdata,respsize),respsize), FALSE);
1183 }
1184 if(traceLen > TRACE_SIZE) {
1185 DbpString("Trace full");
1186 break;
1187 }
1188 }
1189
1190 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
1191 }
1192
1193 Dbprintf("%x %x %x", happened, happened2, cmdsRecvd);
1194 LED_A_OFF();
1195}
1196
1197//-----------------------------------------------------------------------------
1198// Transmit the command (to the tag) that was placed in ToSend[].
1199//-----------------------------------------------------------------------------
1200static void TransmitFor14443a(const uint8_t *cmd, int len, int *samples, int *wait)
1201{
1202 int c;
1203
1204 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1205
1206 if (wait)
1207 if(*wait < 10)
1208 *wait = 10;
1209
1210 for(c = 0; c < *wait;) {
1211 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1212 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1213 c++;
1214 }
1215 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1216 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1217 (void)r;
1218 }
1219 WDT_HIT();
1220 }
1221
1222 c = 0;
1223 for(;;) {
1224 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1225 AT91C_BASE_SSC->SSC_THR = cmd[c];
1226 c++;
1227 if(c >= len) {
1228 break;
1229 }
1230 }
1231 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1232 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1233 (void)r;
1234 }
1235 WDT_HIT();
1236 }
1237 if (samples) *samples = (c + *wait) << 3;
1238}
1239
1240//-----------------------------------------------------------------------------
1241// Code a 7-bit command without parity bit
1242// This is especially for 0x26 and 0x52 (REQA and WUPA)
1243//-----------------------------------------------------------------------------
1244void ShortFrameFromReader(const uint8_t bt)
1245{
1246 int j;
1247 int last;
1248 uint8_t b;
1249
1250 ToSendReset();
1251
1252 // Start of Communication (Seq. Z)
1253 ToSend[++ToSendMax] = SEC_Z;
1254 last = 0;
1255
1256 b = bt;
1257 for(j = 0; j < 7; j++) {
1258 if(b & 1) {
1259 // Sequence X
1260 ToSend[++ToSendMax] = SEC_X;
1261 last = 1;
1262 } else {
1263 if(last == 0) {
1264 // Sequence Z
1265 ToSend[++ToSendMax] = SEC_Z;
1266 }
1267 else {
1268 // Sequence Y
1269 ToSend[++ToSendMax] = SEC_Y;
1270 last = 0;
1271 }
1272 }
1273 b >>= 1;
1274 }
1275
1276 // End of Communication
1277 if(last == 0) {
1278 // Sequence Z
1279 ToSend[++ToSendMax] = SEC_Z;
1280 }
1281 else {
1282 // Sequence Y
1283 ToSend[++ToSendMax] = SEC_Y;
1284 last = 0;
1285 }
1286 // Sequence Y
1287 ToSend[++ToSendMax] = SEC_Y;
1288
1289 // Just to be sure!
1290 ToSend[++ToSendMax] = SEC_Y;
1291 ToSend[++ToSendMax] = SEC_Y;
1292 ToSend[++ToSendMax] = SEC_Y;
1293
1294 // Convert from last character reference to length
1295 ToSendMax++;
1296}
1297
1298//-----------------------------------------------------------------------------
1299// Prepare reader command to send to FPGA
1300//
1301//-----------------------------------------------------------------------------
1302void CodeIso14443aAsReaderPar(const uint8_t * cmd, int len, uint32_t dwParity)
1303{
1304 int i, j;
1305 int last;
1306 uint8_t b;
1307
1308 ToSendReset();
1309
1310 // Start of Communication (Seq. Z)
1311 ToSend[++ToSendMax] = SEC_Z;
1312 last = 0;
1313
1314 // Generate send structure for the data bits
1315 for (i = 0; i < len; i++) {
1316 // Get the current byte to send
1317 b = cmd[i];
1318
1319 for (j = 0; j < 8; j++) {
1320 if (b & 1) {
1321 // Sequence X
1322 ToSend[++ToSendMax] = SEC_X;
1323 last = 1;
1324 } else {
1325 if (last == 0) {
1326 // Sequence Z
1327 ToSend[++ToSendMax] = SEC_Z;
1328 } else {
1329 // Sequence Y
1330 ToSend[++ToSendMax] = SEC_Y;
1331 last = 0;
1332 }
1333 }
1334 b >>= 1;
1335 }
1336
1337 // Get the parity bit
1338 if ((dwParity >> i) & 0x01) {
1339 // Sequence X
1340 ToSend[++ToSendMax] = SEC_X;
1341 last = 1;
1342 } else {
1343 if (last == 0) {
1344 // Sequence Z
1345 ToSend[++ToSendMax] = SEC_Z;
1346 } else {
1347 // Sequence Y
1348 ToSend[++ToSendMax] = SEC_Y;
1349 last = 0;
1350 }
1351 }
1352 }
1353
1354 // End of Communication
1355 if (last == 0) {
1356 // Sequence Z
1357 ToSend[++ToSendMax] = SEC_Z;
1358 } else {
1359 // Sequence Y
1360 ToSend[++ToSendMax] = SEC_Y;
1361 last = 0;
1362 }
1363 // Sequence Y
1364 ToSend[++ToSendMax] = SEC_Y;
1365
1366 // Just to be sure!
1367 ToSend[++ToSendMax] = SEC_Y;
1368 ToSend[++ToSendMax] = SEC_Y;
1369 ToSend[++ToSendMax] = SEC_Y;
1370
1371 // Convert from last character reference to length
1372 ToSendMax++;
1373}
1374
1375//-----------------------------------------------------------------------------
1376// Wait for commands from reader
1377// Stop when button is pressed (return 1) or field was gone (return 2)
1378// Or return 0 when command is captured
1379//-----------------------------------------------------------------------------
1380static int EmGetCmd(uint8_t *received, int *len, int maxLen)
1381{
1382 *len = 0;
1383
1384 uint32_t timer = 0, vtime = 0;
1385 int analogCnt = 0;
1386 int analogAVG = 0;
1387
1388 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1389 // only, since we are receiving, not transmitting).
1390 // Signal field is off with the appropriate LED
1391 LED_D_OFF();
1392 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1393
1394 // Set ADC to read field strength
1395 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
1396 AT91C_BASE_ADC->ADC_MR =
1397 ADC_MODE_PRESCALE(32) |
1398 ADC_MODE_STARTUP_TIME(16) |
1399 ADC_MODE_SAMPLE_HOLD_TIME(8);
1400 AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF);
1401 // start ADC
1402 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1403
1404 // Now run a 'software UART' on the stream of incoming samples.
1405 Uart.output = received;
1406 Uart.byteCntMax = maxLen;
1407 Uart.state = STATE_UNSYNCD;
1408
1409 for(;;) {
1410 WDT_HIT();
1411
1412 if (BUTTON_PRESS()) return 1;
1413
1414 // test if the field exists
1415 if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF)) {
1416 analogCnt++;
1417 analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF];
1418 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1419 if (analogCnt >= 32) {
1420 if ((33000 * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
1421 vtime = GetTickCount();
1422 if (!timer) timer = vtime;
1423 // 50ms no field --> card to idle state
1424 if (vtime - timer > 50) return 2;
1425 } else
1426 if (timer) timer = 0;
1427 analogCnt = 0;
1428 analogAVG = 0;
1429 }
1430 }
1431 // transmit none
1432 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1433 AT91C_BASE_SSC->SSC_THR = 0x00;
1434 }
1435 // receive and test the miller decoding
1436 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1437 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1438 if(MillerDecoding((b & 0xf0) >> 4)) {
1439 *len = Uart.byteCnt;
1440 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
1441 return 0;
1442 }
1443 if(MillerDecoding(b & 0x0f)) {
1444 *len = Uart.byteCnt;
1445 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
1446 return 0;
1447 }
1448 }
1449 }
1450}
1451
1452static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded)
1453{
1454 int i, u = 0;
1455 uint8_t b = 0;
1456
1457 // Modulate Manchester
1458 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1459 AT91C_BASE_SSC->SSC_THR = 0x00;
1460 FpgaSetupSsc();
1461
1462 // include correction bit
1463 i = 1;
1464 if((Uart.parityBits & 0x01) || correctionNeeded) {
1465 // 1236, so correction bit needed
1466 i = 0;
1467 }
1468
1469 // send cycle
1470 for(;;) {
1471 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1472 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1473 (void)b;
1474 }
1475 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1476 if(i > respLen) {
1477 b = 0xff; // was 0x00
1478 u++;
1479 } else {
1480 b = resp[i];
1481 i++;
1482 }
1483 AT91C_BASE_SSC->SSC_THR = b;
1484
1485 if(u > 4) break;
1486 }
1487 if(BUTTON_PRESS()) {
1488 break;
1489 }
1490 }
1491
1492 return 0;
1493}
1494
1495int EmSend4bitEx(uint8_t resp, int correctionNeeded){
1496 Code4bitAnswerAsTag(resp);
1497 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
1498 if (tracing) LogTrace(&resp, 1, GetDeltaCountUS(), GetParity(&resp, 1), FALSE);
1499 return res;
1500}
1501
1502int EmSend4bit(uint8_t resp){
1503 return EmSend4bitEx(resp, 0);
1504}
1505
1506int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par){
1507 CodeIso14443aAsTagPar(resp, respLen, par);
1508 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
1509 if (tracing) LogTrace(resp, respLen, GetDeltaCountUS(), par, FALSE);
1510 return res;
1511}
1512
1513int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded){
1514 return EmSendCmdExPar(resp, respLen, correctionNeeded, GetParity(resp, respLen));
1515}
1516
1517int EmSendCmd(uint8_t *resp, int respLen){
1518 return EmSendCmdExPar(resp, respLen, 0, GetParity(resp, respLen));
1519}
1520
1521int EmSendCmdPar(uint8_t *resp, int respLen, uint32_t par){
1522 return EmSendCmdExPar(resp, respLen, 0, par);
1523}
1524
1525//-----------------------------------------------------------------------------
1526// Wait a certain time for tag response
1527// If a response is captured return TRUE
1528// If it takes to long return FALSE
1529//-----------------------------------------------------------------------------
1530static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
1531{
1532 // buffer needs to be 512 bytes
1533 int c;
1534
1535 // Set FPGA mode to "reader listen mode", no modulation (listen
1536 // only, since we are receiving, not transmitting).
1537 // Signal field is on with the appropriate LED
1538 LED_D_ON();
1539 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1540
1541 // Now get the answer from the card
1542 Demod.output = receivedResponse;
1543 Demod.len = 0;
1544 Demod.state = DEMOD_UNSYNCD;
1545
1546 uint8_t b;
1547 if (elapsed) *elapsed = 0;
1548
1549 c = 0;
1550 for(;;) {
1551 WDT_HIT();
1552
1553 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1554 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1555 if (elapsed) (*elapsed)++;
1556 }
1557 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1558 if(c < iso14a_timeout) { c++; } else { return FALSE; }
1559 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1560 if(ManchesterDecoding((b>>4) & 0xf)) {
1561 *samples = ((c - 1) << 3) + 4;
1562 return TRUE;
1563 }
1564 if(ManchesterDecoding(b & 0x0f)) {
1565 *samples = c << 3;
1566 return TRUE;
1567 }
1568 }
1569 }
1570}
1571
1572void ReaderTransmitShort(const uint8_t* bt)
1573{
1574 int wait = 0;
1575 int samples = 0;
1576
1577 ShortFrameFromReader(*bt);
1578
1579 // Select the card
1580 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
1581
1582 // Store reader command in buffer
1583 if (tracing) LogTrace(bt,1,0,GetParity(bt,1),TRUE);
1584}
1585
1586void ReaderTransmitPar(uint8_t* frame, int len, uint32_t par)
1587{
1588 int wait = 0;
1589 int samples = 0;
1590
1591 // This is tied to other size changes
1592 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1593 CodeIso14443aAsReaderPar(frame,len,par);
1594
1595 // Select the card
1596 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
1597 if(trigger)
1598 LED_A_ON();
1599
1600 // Store reader command in buffer
1601 if (tracing) LogTrace(frame,len,0,par,TRUE);
1602}
1603
1604
1605void ReaderTransmit(uint8_t* frame, int len)
1606{
1607 // Generate parity and redirect
1608 ReaderTransmitPar(frame,len,GetParity(frame,len));
1609}
1610
1611int ReaderReceive(uint8_t* receivedAnswer)
1612{
1613 int samples = 0;
1614 if (!GetIso14443aAnswerFromTag(receivedAnswer,160,&samples,0)) return FALSE;
1615 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1616 if(samples == 0) return FALSE;
1617 return Demod.len;
1618}
1619
1620int ReaderReceivePar(uint8_t* receivedAnswer, uint32_t * parptr)
1621{
1622 int samples = 0;
1623 if (!GetIso14443aAnswerFromTag(receivedAnswer,160,&samples,0)) return FALSE;
1624 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1625 *parptr = Demod.parityBits;
1626 if(samples == 0) return FALSE;
1627 return Demod.len;
1628}
1629
1630/* performs iso14443a anticolision procedure
1631 * fills the uid pointer unless NULL
1632 * fills resp_data unless NULL */
1633int iso14443a_select_card(uint8_t * uid_ptr, iso14a_card_select_t * resp_data, uint32_t * cuid_ptr) {
1634 uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1635 uint8_t sel_all[] = { 0x93,0x20 };
1636 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1637 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1638
1639 uint8_t* resp = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1640
1641 uint8_t sak = 0x04; // cascade uid
1642 int cascade_level = 0;
1643
1644 int len;
1645
1646 // clear uid
1647 memset(uid_ptr, 0, 8);
1648
1649 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1650 ReaderTransmitShort(wupa);
1651 // Receive the ATQA
1652 if(!ReaderReceive(resp)) return 0;
1653
1654 if(resp_data)
1655 memcpy(resp_data->atqa, resp, 2);
1656
1657 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1658 // which case we need to make a cascade 2 request and select - this is a long UID
1659 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1660 for(; sak & 0x04; cascade_level++)
1661 {
1662 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1663 sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
1664
1665 // SELECT_ALL
1666 ReaderTransmit(sel_all,sizeof(sel_all));
1667 if (!ReaderReceive(resp)) return 0;
1668 if(uid_ptr) memcpy(uid_ptr + cascade_level*4, resp, 4);
1669
1670 // calculate crypto UID
1671 if(cuid_ptr) *cuid_ptr = bytes_to_num(resp, 4);
1672
1673 // Construct SELECT UID command
1674 memcpy(sel_uid+2,resp,5);
1675 AppendCrc14443a(sel_uid,7);
1676 ReaderTransmit(sel_uid,sizeof(sel_uid));
1677
1678 // Receive the SAK
1679 if (!ReaderReceive(resp)) return 0;
1680 sak = resp[0];
1681 }
1682 if(resp_data) {
1683 resp_data->sak = sak;
1684 resp_data->ats_len = 0;
1685 }
1686 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1687 if (uid_ptr[0] == 0x88) {
1688 memcpy(uid_ptr, uid_ptr + 1, 7);
1689 uid_ptr[7] = 0;
1690 }
1691
1692 if( (sak & 0x20) == 0)
1693 return 2; // non iso14443a compliant tag
1694
1695 // Request for answer to select
1696 if(resp_data) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1697 AppendCrc14443a(rats, 2);
1698 ReaderTransmit(rats, sizeof(rats));
1699
1700 if (!(len = ReaderReceive(resp))) return 0;
1701
1702 memcpy(resp_data->ats, resp, sizeof(resp_data->ats));
1703 resp_data->ats_len = len;
1704 }
1705
1706 return 1;
1707}
1708
1709void iso14443a_setup() {
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 LED_D_ON();
1723 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1724 SpinDelay(200);
1725
1726 iso14a_timeout = 2048; //default
1727}
1728
1729int iso14_apdu(uint8_t * cmd, size_t cmd_len, void * data) {
1730 uint8_t real_cmd[cmd_len+4];
1731 real_cmd[0] = 0x0a; //I-Block
1732 real_cmd[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1733 memcpy(real_cmd+2, cmd, cmd_len);
1734 AppendCrc14443a(real_cmd,cmd_len+2);
1735
1736 ReaderTransmit(real_cmd, cmd_len+4);
1737 size_t len = ReaderReceive(data);
1738 if(!len)
1739 return -1; //DATA LINK ERROR
1740
1741 return len;
1742}
1743
1744
1745//-----------------------------------------------------------------------------
1746// Read an ISO 14443a tag. Send out commands and store answers.
1747//
1748//-----------------------------------------------------------------------------
1749void ReaderIso14443a(UsbCommand * c, UsbCommand * ack)
1750{
1751 iso14a_command_t param = c->arg[0];
1752 uint8_t * cmd = c->d.asBytes;
1753 size_t len = c->arg[1];
1754
1755 if(param & ISO14A_REQUEST_TRIGGER) iso14a_set_trigger(1);
1756
1757 if(param & ISO14A_CONNECT) {
1758 iso14443a_setup();
1759 ack->arg[0] = iso14443a_select_card(ack->d.asBytes, (iso14a_card_select_t *) (ack->d.asBytes+12), NULL);
1760 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1761 }
1762
1763 if(param & ISO14A_SET_TIMEOUT) {
1764 iso14a_timeout = c->arg[2];
1765 }
1766
1767 if(param & ISO14A_SET_TIMEOUT) {
1768 iso14a_timeout = c->arg[2];
1769 }
1770
1771 if(param & ISO14A_APDU) {
1772 ack->arg[0] = iso14_apdu(cmd, len, ack->d.asBytes);
1773 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1774 }
1775
1776 if(param & ISO14A_RAW) {
1777 if(param & ISO14A_APPEND_CRC) {
1778 AppendCrc14443a(cmd,len);
1779 len += 2;
1780 }
1781 ReaderTransmit(cmd,len);
1782 ack->arg[0] = ReaderReceive(ack->d.asBytes);
1783 UsbSendPacket((void *)ack, sizeof(UsbCommand));
1784 }
1785
1786 if(param & ISO14A_REQUEST_TRIGGER) iso14a_set_trigger(0);
1787
1788 if(param & ISO14A_NO_DISCONNECT)
1789 return;
1790
1791 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1792 LEDsoff();
1793}
1794//-----------------------------------------------------------------------------
1795// Read an ISO 14443a tag. Send out commands and store answers.
1796//
1797//-----------------------------------------------------------------------------
1798void ReaderMifare(uint32_t parameter)
1799{
1800 // Mifare AUTH
1801 uint8_t mf_auth[] = { 0x60,0x00,0xf5,0x7b };
1802 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1803
1804 uint8_t* receivedAnswer = (((uint8_t *)BigBuf) + 3560); // was 3560 - tied to other size changes
1805 traceLen = 0;
1806 tracing = false;
1807
1808 iso14443a_setup();
1809
1810 LED_A_ON();
1811 LED_B_OFF();
1812 LED_C_OFF();
1813
1814 byte_t nt_diff = 0;
1815 LED_A_OFF();
1816 byte_t par = 0;
1817 //byte_t par_mask = 0xff;
1818 byte_t par_low = 0;
1819 int led_on = TRUE;
1820 uint8_t uid[8];
1821 uint32_t cuid;
1822
1823 tracing = FALSE;
1824 byte_t nt[4] = {0,0,0,0};
1825 byte_t nt_attacked[4], nt_noattack[4];
1826 byte_t par_list[8] = {0,0,0,0,0,0,0,0};
1827 byte_t ks_list[8] = {0,0,0,0,0,0,0,0};
1828 num_to_bytes(parameter, 4, nt_noattack);
1829 int isOK = 0, isNULL = 0;
1830
1831 while(TRUE)
1832 {
1833 LED_C_ON();
1834 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1835 SpinDelay(200);
1836 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1837 LED_C_OFF();
1838
1839 // Test if the action was cancelled
1840 if(BUTTON_PRESS()) {
1841 break;
1842 }
1843
1844 if(!iso14443a_select_card(uid, NULL, &cuid)) continue;
1845
1846 // Transmit MIFARE_CLASSIC_AUTH
1847 ReaderTransmit(mf_auth, sizeof(mf_auth));
1848
1849 // Receive the (16 bit) "random" nonce
1850 if (!ReaderReceive(receivedAnswer)) continue;
1851 memcpy(nt, receivedAnswer, 4);
1852
1853 // Transmit reader nonce and reader answer
1854 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar),par);
1855
1856 // Receive 4 bit answer
1857 if (ReaderReceive(receivedAnswer))
1858 {
1859 if ( (parameter != 0) && (memcmp(nt, nt_noattack, 4) == 0) ) continue;
1860
1861 isNULL = !(nt_attacked[0] == 0) && (nt_attacked[1] == 0) && (nt_attacked[2] == 0) && (nt_attacked[3] == 0);
1862 if ( (isNULL != 0 ) && (memcmp(nt, nt_attacked, 4) != 0) ) continue;
1863
1864 if (nt_diff == 0)
1865 {
1866 LED_A_ON();
1867 memcpy(nt_attacked, nt, 4);
1868 //par_mask = 0xf8;
1869 par_low = par & 0x07;
1870 }
1871
1872 led_on = !led_on;
1873 if(led_on) LED_B_ON(); else LED_B_OFF();
1874 par_list[nt_diff] = par;
1875 ks_list[nt_diff] = receivedAnswer[0] ^ 0x05;
1876
1877 // Test if the information is complete
1878 if (nt_diff == 0x07) {
1879 isOK = 1;
1880 break;
1881 }
1882
1883 nt_diff = (nt_diff + 1) & 0x07;
1884 mf_nr_ar[3] = nt_diff << 5;
1885 par = par_low;
1886 } else {
1887 if (nt_diff == 0)
1888 {
1889 par++;
1890 } else {
1891 par = (((par >> 3) + 1) << 3) | par_low;
1892 }
1893 }
1894 }
1895
1896 LogTrace(nt, 4, 0, GetParity(nt, 4), TRUE);
1897 LogTrace(par_list, 8, 0, GetParity(par_list, 8), TRUE);
1898 LogTrace(ks_list, 8, 0, GetParity(ks_list, 8), TRUE);
1899
1900 UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
1901 memcpy(ack.d.asBytes + 0, uid, 4);
1902 memcpy(ack.d.asBytes + 4, nt, 4);
1903 memcpy(ack.d.asBytes + 8, par_list, 8);
1904 memcpy(ack.d.asBytes + 16, ks_list, 8);
1905
1906 LED_B_ON();
1907 UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
1908 LED_B_OFF();
1909
1910 // Thats it...
1911 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1912 LEDsoff();
1913 tracing = TRUE;
1914
1915 if (MF_DBGLEVEL >= 1) DbpString("COMMAND mifare FINISHED");
1916}
1917
1918
1919//-----------------------------------------------------------------------------
1920// MIFARE 1K simulate.
1921//
1922//-----------------------------------------------------------------------------
1923void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
1924{
1925 int cardSTATE = MFEMUL_NOFIELD;
1926 int _7BUID = 0;
1927 int vHf = 0; // in mV
1928 //int nextCycleTimeout = 0;
1929 int res;
1930// uint32_t timer = 0;
1931 uint32_t selTimer = 0;
1932 uint32_t authTimer = 0;
1933 uint32_t par = 0;
1934 int len = 0;
1935 uint8_t cardWRBL = 0;
1936 uint8_t cardAUTHSC = 0;
1937 uint8_t cardAUTHKEY = 0xff; // no authentication
1938 //uint32_t cardRn = 0;
1939 uint32_t cardRr = 0;
1940 uint32_t cuid = 0;
1941 //uint32_t rn_enc = 0;
1942 uint32_t ans = 0;
1943 uint32_t cardINTREG = 0;
1944 uint8_t cardINTBLOCK = 0;
1945 struct Crypto1State mpcs = {0, 0};
1946 struct Crypto1State *pcs;
1947 pcs = &mpcs;
1948
1949 uint8_t* receivedCmd = eml_get_bigbufptr_recbuf();
1950 uint8_t *response = eml_get_bigbufptr_sendbuf();
1951
1952 static uint8_t rATQA[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
1953
1954 static uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
1955 static uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
1956
1957 static uint8_t rSAK[] = {0x08, 0xb6, 0xdd};
1958 static uint8_t rSAK1[] = {0x04, 0xda, 0x17};
1959
1960 static uint8_t rAUTH_NT[] = {0x01, 0x02, 0x03, 0x04};
1961// static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
1962 static uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
1963
1964 // clear trace
1965 traceLen = 0;
1966 tracing = true;
1967
1968 // Authenticate response - nonce
1969 uint32_t nonce = bytes_to_num(rAUTH_NT, 4);
1970
1971 // get UID from emul memory
1972 emlGetMemBt(receivedCmd, 7, 1);
1973 _7BUID = !(receivedCmd[0] == 0x00);
1974 if (!_7BUID) { // ---------- 4BUID
1975 rATQA[0] = 0x04;
1976
1977 emlGetMemBt(rUIDBCC1, 0, 4);
1978 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
1979 } else { // ---------- 7BUID
1980 rATQA[0] = 0x44;
1981
1982 rUIDBCC1[0] = 0x88;
1983 emlGetMemBt(&rUIDBCC1[1], 0, 3);
1984 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
1985 emlGetMemBt(rUIDBCC2, 3, 4);
1986 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
1987 }
1988
1989// -------------------------------------- test area
1990
1991// -------------------------------------- END test area
1992 // start mkseconds counter
1993 StartCountUS();
1994
1995 // We need to listen to the high-frequency, peak-detected path.
1996 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1997 FpgaSetupSsc();
1998
1999 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
2000 SpinDelay(200);
2001
2002 if (MF_DBGLEVEL >= 1) Dbprintf("Started. 7buid=%d", _7BUID);
2003 // calibrate mkseconds counter
2004 GetDeltaCountUS();
2005 while (true) {
2006 WDT_HIT();
2007
2008 if(BUTTON_PRESS()) {
2009 break;
2010 }
2011
2012 // find reader field
2013 // Vref = 3300mV, and an 10:1 voltage divider on the input
2014 // can measure voltages up to 33000 mV
2015 if (cardSTATE == MFEMUL_NOFIELD) {
2016 vHf = (33000 * AvgAdc(ADC_CHAN_HF)) >> 10;
2017 if (vHf > MF_MINFIELDV) {
2018 cardSTATE_TO_IDLE();
2019 LED_A_ON();
2020 }
2021 }
2022
2023 if (cardSTATE != MFEMUL_NOFIELD) {
2024 res = EmGetCmd(receivedCmd, &len, RECV_CMD_SIZE); // (+ nextCycleTimeout)
2025 if (res == 2) {
2026 cardSTATE = MFEMUL_NOFIELD;
2027 LEDsoff();
2028 continue;
2029 }
2030 if(res) break;
2031 }
2032
2033 //nextCycleTimeout = 0;
2034
2035// if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2036
2037 if (len != 4 && cardSTATE != MFEMUL_NOFIELD) { // len != 4 <---- speed up the code 4 authentication
2038 // REQ or WUP request in ANY state and WUP in HALTED state
2039 if (len == 1 && ((receivedCmd[0] == 0x26 && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == 0x52)) {
2040 selTimer = GetTickCount();
2041 EmSendCmdEx(rATQA, sizeof(rATQA), (receivedCmd[0] == 0x52));
2042 cardSTATE = MFEMUL_SELECT1;
2043
2044 // init crypto block
2045 LED_B_OFF();
2046 LED_C_OFF();
2047 crypto1_destroy(pcs);
2048 cardAUTHKEY = 0xff;
2049 }
2050 }
2051
2052 switch (cardSTATE) {
2053 case MFEMUL_NOFIELD:{
2054 break;
2055 }
2056 case MFEMUL_HALTED:{
2057 break;
2058 }
2059 case MFEMUL_IDLE:{
2060 break;
2061 }
2062 case MFEMUL_SELECT1:{
2063 // select all
2064 if (len == 2 && (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x20)) {
2065 EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
2066 break;
2067 }
2068
2069 // select card
2070 if (len == 9 &&
2071 (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
2072 if (!_7BUID)
2073 EmSendCmd(rSAK, sizeof(rSAK));
2074 else
2075 EmSendCmd(rSAK1, sizeof(rSAK1));
2076
2077 cuid = bytes_to_num(rUIDBCC1, 4);
2078 if (!_7BUID) {
2079 cardSTATE = MFEMUL_WORK;
2080 LED_B_ON();
2081 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
2082 break;
2083 } else {
2084 cardSTATE = MFEMUL_SELECT2;
2085 break;
2086 }
2087 }
2088
2089 break;
2090 }
2091 case MFEMUL_SELECT2:{
2092 if (!len) break;
2093
2094 if (len == 2 && (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x20)) {
2095 EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
2096 break;
2097 }
2098
2099 // select 2 card
2100 if (len == 9 &&
2101 (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC2, 4) == 0)) {
2102 EmSendCmd(rSAK, sizeof(rSAK));
2103
2104 cuid = bytes_to_num(rUIDBCC2, 4);
2105 cardSTATE = MFEMUL_WORK;
2106 LED_B_ON();
2107 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer);
2108 break;
2109 }
2110
2111 // i guess there is a command). go into the work state.
2112 if (len != 4) break;
2113 cardSTATE = MFEMUL_WORK;
2114 goto lbWORK;
2115 }
2116 case MFEMUL_AUTH1:{
2117 if (len == 8) {
2118 // --- crypto
2119 //rn_enc = bytes_to_num(receivedCmd, 4);
2120 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2121 cardRr = bytes_to_num(&receivedCmd[4], 4) ^ crypto1_word(pcs, 0, 0);
2122 // test if auth OK
2123 if (cardRr != prng_successor(nonce, 64)){
2124 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr, prng_successor(nonce, 64));
2125 cardSTATE_TO_IDLE();
2126 break;
2127 }
2128 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2129 num_to_bytes(ans, 4, rAUTH_AT);
2130 // --- crypto
2131 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2132 cardSTATE = MFEMUL_AUTH2;
2133 } else {
2134 cardSTATE_TO_IDLE();
2135 }
2136 if (cardSTATE != MFEMUL_AUTH2) break;
2137 }
2138 case MFEMUL_AUTH2:{
2139 LED_C_ON();
2140 cardSTATE = MFEMUL_WORK;
2141 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC, cardAUTHKEY, GetTickCount() - authTimer);
2142 break;
2143 }
2144 case MFEMUL_WORK:{
2145lbWORK: if (len == 0) break;
2146
2147 if (cardAUTHKEY == 0xff) {
2148 // first authentication
2149 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2150 authTimer = GetTickCount();
2151
2152 cardAUTHSC = receivedCmd[1] / 4; // received block num
2153 cardAUTHKEY = receivedCmd[0] - 0x60;
2154
2155 // --- crypto
2156 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
2157 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
2158 num_to_bytes(nonce, 4, rAUTH_AT);
2159 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2160 // --- crypto
2161
2162// last working revision
2163// EmSendCmd14443aRaw(resp1, resp1Len, 0);
2164// LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2165
2166 cardSTATE = MFEMUL_AUTH1;
2167 //nextCycleTimeout = 10;
2168 break;
2169 }
2170 } else {
2171 // decrypt seqence
2172 mf_crypto1_decrypt(pcs, receivedCmd, len);
2173
2174 // nested authentication
2175 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2176 authTimer = GetTickCount();
2177
2178 cardAUTHSC = receivedCmd[1] / 4; // received block num
2179 cardAUTHKEY = receivedCmd[0] - 0x60;
2180
2181 // --- crypto
2182 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
2183 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
2184 num_to_bytes(ans, 4, rAUTH_AT);
2185 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2186 // --- crypto
2187
2188 cardSTATE = MFEMUL_AUTH1;
2189 //nextCycleTimeout = 10;
2190 break;
2191 }
2192 }
2193
2194 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2195 // BUT... ACK --> NACK
2196 if (len == 1 && receivedCmd[0] == CARD_ACK) {
2197 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2198 break;
2199 }
2200
2201 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2202 if (len == 1 && receivedCmd[0] == CARD_NACK_NA) {
2203 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2204 break;
2205 }
2206
2207 // read block
2208 if (len == 4 && receivedCmd[0] == 0x30) {
2209 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
2210 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2211 break;
2212 }
2213 emlGetMem(response, receivedCmd[1], 1);
2214 AppendCrc14443a(response, 16);
2215 mf_crypto1_encrypt(pcs, response, 18, &par);
2216 EmSendCmdPar(response, 18, par);
2217 break;
2218 }
2219
2220 // write block
2221 if (len == 4 && receivedCmd[0] == 0xA0) {
2222 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
2223 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2224 break;
2225 }
2226 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2227 //nextCycleTimeout = 50;
2228 cardSTATE = MFEMUL_WRITEBL2;
2229 cardWRBL = receivedCmd[1];
2230 break;
2231 }
2232
2233 // works with cardINTREG
2234
2235 // increment, decrement, restore
2236 if (len == 4 && (receivedCmd[0] == 0xC0 || receivedCmd[0] == 0xC1 || receivedCmd[0] == 0xC2)) {
2237 if (receivedCmd[1] >= 16 * 4 ||
2238 receivedCmd[1] / 4 != cardAUTHSC ||
2239 emlCheckValBl(receivedCmd[1])) {
2240 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2241 break;
2242 }
2243 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2244 if (receivedCmd[0] == 0xC1)
2245 cardSTATE = MFEMUL_INTREG_INC;
2246 if (receivedCmd[0] == 0xC0)
2247 cardSTATE = MFEMUL_INTREG_DEC;
2248 if (receivedCmd[0] == 0xC2)
2249 cardSTATE = MFEMUL_INTREG_REST;
2250 cardWRBL = receivedCmd[1];
2251
2252 break;
2253 }
2254
2255
2256 // transfer
2257 if (len == 4 && receivedCmd[0] == 0xB0) {
2258 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
2259 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2260 break;
2261 }
2262
2263 if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd[1]))
2264 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2265 else
2266 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2267
2268 break;
2269 }
2270
2271 // halt
2272 if (len == 4 && (receivedCmd[0] == 0x50 && receivedCmd[1] == 0x00)) {
2273 LED_B_OFF();
2274 LED_C_OFF();
2275 cardSTATE = MFEMUL_HALTED;
2276 if (MF_DBGLEVEL >= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
2277 break;
2278 }
2279
2280 // command not allowed
2281 if (len == 4) {
2282 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2283 break;
2284 }
2285
2286 // case break
2287 break;
2288 }
2289 case MFEMUL_WRITEBL2:{
2290 if (len == 18){
2291 mf_crypto1_decrypt(pcs, receivedCmd, len);
2292 emlSetMem(receivedCmd, cardWRBL, 1);
2293 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2294 cardSTATE = MFEMUL_WORK;
2295 break;
2296 } else {
2297 cardSTATE_TO_IDLE();
2298 break;
2299 }
2300 break;
2301 }
2302
2303 case MFEMUL_INTREG_INC:{
2304 mf_crypto1_decrypt(pcs, receivedCmd, len);
2305 memcpy(&ans, receivedCmd, 4);
2306 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2307 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2308 cardSTATE_TO_IDLE();
2309 break;
2310 }
2311 cardINTREG = cardINTREG + ans;
2312 cardSTATE = MFEMUL_WORK;
2313 break;
2314 }
2315 case MFEMUL_INTREG_DEC:{
2316 mf_crypto1_decrypt(pcs, receivedCmd, len);
2317 memcpy(&ans, receivedCmd, 4);
2318 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2319 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2320 cardSTATE_TO_IDLE();
2321 break;
2322 }
2323 cardINTREG = cardINTREG - ans;
2324 cardSTATE = MFEMUL_WORK;
2325 break;
2326 }
2327 case MFEMUL_INTREG_REST:{
2328 mf_crypto1_decrypt(pcs, receivedCmd, len);
2329 memcpy(&ans, receivedCmd, 4);
2330 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2331 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2332 cardSTATE_TO_IDLE();
2333 break;
2334 }
2335 cardSTATE = MFEMUL_WORK;
2336 break;
2337 }
2338 }
2339 }
2340
2341 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2342 LEDsoff();
2343
2344 // add trace trailer
2345 memset(rAUTH_NT, 0x44, 4);
2346 LogTrace(rAUTH_NT, 4, 0, 0, TRUE);
2347
2348 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, traceLen);
2349}
2350
2351//-----------------------------------------------------------------------------
2352// MIFARE sniffer.
2353//
2354//-----------------------------------------------------------------------------
2355void RAMFUNC SniffMifare(uint8_t param) {
2356 // param:
2357 // bit 0 - trigger from first card answer
2358 // bit 1 - trigger from first reader 7-bit request
2359
2360 LEDsoff();
2361 // init trace buffer
2362 traceLen = 0;
2363 memset(trace, 0x44, TRACE_SIZE);
2364
2365 // The command (reader -> tag) that we're receiving.
2366 // The length of a received command will in most cases be no more than 18 bytes.
2367 // So 32 should be enough!
2368 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
2369 // The response (tag -> reader) that we're receiving.
2370 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
2371
2372 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2373 // into trace, along with its length and other annotations.
2374 //uint8_t *trace = (uint8_t *)BigBuf;
2375
2376 // The DMA buffer, used to stream samples from the FPGA
2377 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
2378 int8_t *data = dmaBuf;
2379 int maxDataLen = 0;
2380 int dataLen = 0;
2381// data = dmaBuf;
2382
2383 // Set up the demodulator for tag -> reader responses.
2384 Demod.output = receivedResponse;
2385 Demod.len = 0;
2386 Demod.state = DEMOD_UNSYNCD;
2387
2388 // Set up the demodulator for the reader -> tag commands
2389 memset(&Uart, 0, sizeof(Uart));
2390 Uart.output = receivedCmd;
2391 Uart.byteCntMax = 32; // was 100 (greg)//////////////////
2392 Uart.state = STATE_UNSYNCD;
2393
2394 // Setup for the DMA.
2395 FpgaSetupSsc();
2396 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
2397
2398 // And put the FPGA in the appropriate mode
2399 // Signal field is off with the appropriate LED
2400 LED_D_OFF();
2401 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
2402 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2403
2404 // Count of samples received so far, so that we can include timing
2405 // information in the trace buffer.
2406 rsamples = 0;
2407 // And now we loop, receiving samples.
2408 while(true) {
2409 if(BUTTON_PRESS()) {
2410 DbpString("cancelled by button");
2411 goto done;
2412 }
2413
2414 LED_A_ON();
2415 WDT_HIT();
2416
2417 int register readBufDataP = data - dmaBuf;
2418 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
2419 if (readBufDataP <= dmaBufDataP){
2420 dataLen = dmaBufDataP - readBufDataP;
2421 } else {
2422 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP + 1;
2423 }
2424 // test for length of buffer
2425 if(dataLen > maxDataLen) {
2426 maxDataLen = dataLen;
2427 if(dataLen > 400) {
2428 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen);
2429 goto done;
2430 }
2431 }
2432 if(dataLen < 1) continue;
2433
2434 // primary buffer was stopped( <-- we lost data!
2435 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
2436 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
2437 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
2438 Dbprintf("RxEmpty ERROR!!! %d", dataLen); // temporary
2439 }
2440 // secondary buffer sets as primary, secondary buffer was stopped
2441 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
2442 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
2443 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
2444 }
2445
2446 LED_A_OFF();
2447
2448 rsamples += 4;
2449 if(MillerDecoding((data[0] & 0xF0) >> 4)) {
2450 LED_C_ON();
2451 // check - if there is a short 7bit request from reader
2452 if ((Uart.byteCnt == 1) && (Uart.bitCnt = 9)) {
2453
2454 }
2455 if (!LogTrace(receivedCmd, Uart.byteCnt, 0 - Uart.samples, Uart.parityBits, TRUE)) break;
2456
2457 /* And ready to receive another command. */
2458 Uart.state = STATE_UNSYNCD;
2459 /* And also reset the demod code, which might have been */
2460 /* false-triggered by the commands from the reader. */
2461 Demod.state = DEMOD_UNSYNCD;
2462 LED_B_OFF();
2463 }
2464
2465 if(ManchesterDecoding(data[0] & 0x0F)) {
2466 LED_B_ON();
2467
2468 if (!LogTrace(receivedResponse, Demod.len, 0 - Demod.samples, Demod.parityBits, FALSE)) break;
2469
2470 // And ready to receive another response.
2471 memset(&Demod, 0, sizeof(Demod));
2472 Demod.output = receivedResponse;
2473 Demod.state = DEMOD_UNSYNCD;
2474 LED_C_OFF();
2475 }
2476
2477 data++;
2478 if(data > dmaBuf + DMA_BUFFER_SIZE) {
2479 data = dmaBuf;
2480 }
2481 } // main cycle
2482
2483 DbpString("COMMAND FINISHED");
2484
2485done:
2486 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
2487 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen, Uart.state, Uart.byteCnt);
2488 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
2489 LEDsoff();
2490}
Impressum, Datenschutz