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