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