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