]> cvs.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443a.c
removed -fPIC directive
[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}
9ca155ba 901static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded);
15c4dc5a 902
903//-----------------------------------------------------------------------------
904// Main loop of simulated tag: receive commands from reader, decide what
905// response to send, and send it.
906//-----------------------------------------------------------------------------
81cd0474 907void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd)
15c4dc5a 908{
81cd0474 909 // Enable and clear the trace
910 tracing = TRUE;
d19929cb 911 iso14a_clear_trace();
81cd0474 912
15c4dc5a 913 // This function contains the tag emulation
81cd0474 914 uint8_t sak;
915
916 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
917 uint8_t response1[2];
918
919 switch (tagType) {
920 case 1: { // MIFARE Classic
921 // Says: I am Mifare 1k - original line
922 response1[0] = 0x04;
923 response1[1] = 0x00;
924 sak = 0x08;
925 } break;
926 case 2: { // MIFARE Ultralight
927 // Says: I am a stupid memory tag, no crypto
928 response1[0] = 0x04;
929 response1[1] = 0x00;
930 sak = 0x00;
931 } break;
932 case 3: { // MIFARE DESFire
933 // Says: I am a DESFire tag, ph33r me
934 response1[0] = 0x04;
935 response1[1] = 0x03;
936 sak = 0x20;
937 } break;
938 case 4: { // ISO/IEC 14443-4
939 // Says: I am a javacard (JCOP)
940 response1[0] = 0x04;
941 response1[1] = 0x00;
942 sak = 0x28;
943 } break;
944 default: {
945 Dbprintf("Error: unkown tagtype (%d)",tagType);
946 return;
947 } break;
948 }
949
950 // The second response contains the (mandatory) first 24 bits of the UID
951 uint8_t response2[5];
952
953 // Check if the uid uses the (optional) part
954 uint8_t response2a[5];
955 if (uid_2nd) {
956 response2[0] = 0x88;
957 num_to_bytes(uid_1st,3,response2+1);
958 num_to_bytes(uid_2nd,4,response2a);
959 response2a[4] = response2a[0] ^ response2a[1] ^ response2a[2] ^ response2a[3];
960
961 // Configure the ATQA and SAK accordingly
962 response1[0] |= 0x40;
963 sak |= 0x04;
964 } else {
965 num_to_bytes(uid_1st,4,response2);
966 // Configure the ATQA and SAK accordingly
967 response1[0] &= 0xBF;
968 sak &= 0xFB;
969 }
970
971 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
972 response2[4] = response2[0] ^ response2[1] ^ response2[2] ^ response2[3];
973
974 // Prepare the mandatory SAK (for 4 and 7 byte UID)
975 uint8_t response3[3];
976 response3[0] = sak;
977 ComputeCrc14443(CRC_14443_A, response3, 1, &response3[1], &response3[2]);
978
979 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
980 uint8_t response3a[3];
981 response3a[0] = sak & 0xFB;
982 ComputeCrc14443(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]);
983
254b70a4 984 uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
985 uint8_t response6[] = { 0x03, 0x3B, 0x00, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
986 ComputeCrc14443(CRC_14443_A, response6, 3, &response6[3], &response6[4]);
81cd0474 987
254b70a4 988 uint8_t *resp;
989 int respLen;
15c4dc5a 990
81cd0474 991 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
15c4dc5a 992 // This will need
993 // 144 data bits (18 * 8)
994 // 18 parity bits
995 // 2 Start and stop
996 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
997 // 1 just for the case
998 // ----------- +
999 // 166
1000 //
1001 // 166 bytes, since every bit that needs to be send costs us a byte
1002 //
1003
254b70a4 1004 // Respond with card type
1005 uint8_t *resp1 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
1006 int resp1Len;
15c4dc5a 1007
254b70a4 1008 // Anticollision cascade1 - respond with uid
1009 uint8_t *resp2 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 166);
1010 int resp2Len;
15c4dc5a 1011
254b70a4 1012 // Anticollision cascade2 - respond with 2nd half of uid if asked
1013 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1014 uint8_t *resp2a = (((uint8_t *)BigBuf) + 1140);
1015 int resp2aLen;
15c4dc5a 1016
254b70a4 1017 // Acknowledge select - cascade 1
1018 uint8_t *resp3 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*2));
1019 int resp3Len;
15c4dc5a 1020
254b70a4 1021 // Acknowledge select - cascade 2
1022 uint8_t *resp3a = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*3));
1023 int resp3aLen;
15c4dc5a 1024
254b70a4 1025 // Response to a read request - not implemented atm
1026 uint8_t *resp4 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*4));
1027 int resp4Len;
15c4dc5a 1028
254b70a4 1029 // Authenticate response - nonce
1030 uint8_t *resp5 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*5));
1031 int resp5Len;
15c4dc5a 1032
254b70a4 1033 // Authenticate response - nonce
1034 uint8_t *resp6 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + (166*6));
1035 int resp6Len;
15c4dc5a 1036
254b70a4 1037 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
1038 int len;
15c4dc5a 1039
1040 // To control where we are in the protocol
1041 int order = 0;
1042 int lastorder;
1043
1044 // Just to allow some checks
1045 int happened = 0;
1046 int happened2 = 0;
1047
81cd0474 1048 int cmdsRecvd = 0;
1049 uint8_t* respdata = NULL;
1050 int respsize = 0;
1051 uint8_t nack = 0x04;
15c4dc5a 1052
81cd0474 1053 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
15c4dc5a 1054
1055 // Prepare the responses of the anticollision phase
1056 // there will be not enough time to do this at the moment the reader sends it REQA
1057
1058 // Answer to request
1059 CodeIso14443aAsTag(response1, sizeof(response1));
254b70a4 1060 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
15c4dc5a 1061
1062 // Send our UID (cascade 1)
1063 CodeIso14443aAsTag(response2, sizeof(response2));
254b70a4 1064 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
15c4dc5a 1065
1066 // Answer to select (cascade1)
1067 CodeIso14443aAsTag(response3, sizeof(response3));
254b70a4 1068 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
15c4dc5a 1069
1070 // Send the cascade 2 2nd part of the uid
1071 CodeIso14443aAsTag(response2a, sizeof(response2a));
254b70a4 1072 memcpy(resp2a, ToSend, ToSendMax); resp2aLen = ToSendMax;
15c4dc5a 1073
1074 // Answer to select (cascade 2)
1075 CodeIso14443aAsTag(response3a, sizeof(response3a));
254b70a4 1076 memcpy(resp3a, ToSend, ToSendMax); resp3aLen = ToSendMax;
15c4dc5a 1077
1078 // Strange answer is an example of rare message size (3 bits)
8f51ddb0 1079 CodeStrangeAnswerAsTag();
15c4dc5a 1080 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1081
1082 // Authentication answer (random nonce)
1083 CodeIso14443aAsTag(response5, sizeof(response5));
254b70a4 1084 memcpy(resp5, ToSend, ToSendMax); resp5Len = ToSendMax;
15c4dc5a 1085
254b70a4 1086 // dummy ATS (pseudo-ATR), answer to RATS
1087 CodeIso14443aAsTag(response6, sizeof(response6));
1088 memcpy(resp6, ToSend, ToSendMax); resp6Len = ToSendMax;
15c4dc5a 1089
254b70a4 1090 // We need to listen to the high-frequency, peak-detected path.
1091 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1092 FpgaSetupSsc();
15c4dc5a 1093
254b70a4 1094 cmdsRecvd = 0;
15c4dc5a 1095
254b70a4 1096 LED_A_ON();
1097 for(;;) {
1098
81cd0474 1099 if(!GetIso14443aCommandFromReader(receivedCmd, &len, RECV_CMD_SIZE)) {
254b70a4 1100 DbpString("button press");
1101 break;
1102 }
1103 // 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
1104 // Okay, look at the command now.
1105 lastorder = order;
1106 if(receivedCmd[0] == 0x26) { // Received a REQUEST
15c4dc5a 1107 resp = resp1; respLen = resp1Len; order = 1;
81cd0474 1108 respdata = response1;
1109 respsize = sizeof(response1);
254b70a4 1110 } else if(receivedCmd[0] == 0x52) { // Received a WAKEUP
15c4dc5a 1111 resp = resp1; respLen = resp1Len; order = 6;
81cd0474 1112 respdata = response1;
1113 respsize = sizeof(response1);
254b70a4 1114 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // Received request for UID (cascade 1)
15c4dc5a 1115 resp = resp2; respLen = resp2Len; order = 2;
81cd0474 1116 respdata = response2;
1117 respsize = sizeof(response2);
254b70a4 1118 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x95) { // Received request for UID (cascade 2)
15c4dc5a 1119 resp = resp2a; respLen = resp2aLen; order = 20;
81cd0474 1120 respdata = response2a;
1121 respsize = sizeof(response2a);
254b70a4 1122 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x93) { // Received a SELECT (cascade 1)
15c4dc5a 1123 resp = resp3; respLen = resp3Len; order = 3;
81cd0474 1124 respdata = response3;
1125 respsize = sizeof(response3);
254b70a4 1126 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2)
15c4dc5a 1127 resp = resp3a; respLen = resp3aLen; order = 30;
81cd0474 1128 respdata = response3a;
1129 respsize = sizeof(response3a);
254b70a4 1130 } else if(receivedCmd[0] == 0x30) { // Received a (plain) READ
15c4dc5a 1131 resp = resp4; respLen = resp4Len; order = 4; // Do nothing
254b70a4 1132 Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
81cd0474 1133 respdata = &nack;
1134 respsize = sizeof(nack); // 4-bit answer
254b70a4 1135 } else if(receivedCmd[0] == 0x50) { // Received a HALT
15c4dc5a 1136 DbpString("Reader requested we HALT!:");
254b70a4 1137 // Do not respond
1138 resp = resp1; respLen = 0; order = 0;
81cd0474 1139 respdata = NULL;
1140 respsize = 0;
254b70a4 1141 } else if(receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61) { // Received an authentication request
15c4dc5a 1142 resp = resp5; respLen = resp5Len; order = 7;
254b70a4 1143 respdata = response5;
1144 respsize = sizeof(response5);
1145 } else if(receivedCmd[0] == 0xE0) { // Received a RATS request
1146 resp = resp6; respLen = resp6Len; order = 70;
1147 respdata = response6;
1148 respsize = sizeof(response6);
81cd0474 1149 } else {
1150 // Never seen this command before
7862f4ad 1151 Dbprintf("Received (len=%d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",
20f9a2a1 1152 len,
15c4dc5a 1153 receivedCmd[0], receivedCmd[1], receivedCmd[2],
20f9a2a1
M
1154 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1155 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
15c4dc5a 1156 // Do not respond
1157 resp = resp1; respLen = 0; order = 0;
81cd0474 1158 respdata = NULL;
1159 respsize = 0;
1160 }
15c4dc5a 1161
1162 // Count number of wakeups received after a halt
1163 if(order == 6 && lastorder == 5) { happened++; }
1164
1165 // Count number of other messages after a halt
1166 if(order != 6 && lastorder == 5) { happened2++; }
1167
1168 // Look at last parity bit to determine timing of answer
1169 if((Uart.parityBits & 0x01) || receivedCmd[0] == 0x52) {
1170 // 1236, so correction bit needed
9f693930 1171 //i = 0;
15c4dc5a 1172 }
1173
15c4dc5a 1174 if(cmdsRecvd > 999) {
1175 DbpString("1000 commands later...");
254b70a4 1176 break;
1177 } else {
15c4dc5a 1178 cmdsRecvd++;
1179 }
1180
81cd0474 1181 if(respLen > 0) {
81cd0474 1182 EmSendCmd14443aRaw(resp, respLen, receivedCmd[0] == 0x52);
1183 }
1184
1185 if (tracing) {
1186 LogTrace(receivedCmd,len, 0, Uart.parityBits, TRUE);
1187 if (respdata != NULL) {
1188 LogTrace(respdata,respsize, 0, SwapBits(GetParity(respdata,respsize),respsize), FALSE);
1189 }
4ab4336a 1190 if(traceLen > TRACE_SIZE) {
1191 DbpString("Trace full");
1192 break;
1193 }
81cd0474 1194 }
15c4dc5a 1195
81cd0474 1196 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
254b70a4 1197 }
15c4dc5a 1198
1199 Dbprintf("%x %x %x", happened, happened2, cmdsRecvd);
1200 LED_A_OFF();
1201}
1202
1203//-----------------------------------------------------------------------------
1204// Transmit the command (to the tag) that was placed in ToSend[].
1205//-----------------------------------------------------------------------------
f7e3ed82 1206static void TransmitFor14443a(const uint8_t *cmd, int len, int *samples, int *wait)
15c4dc5a 1207{
1208 int c;
e30c654b 1209
15c4dc5a 1210 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
e30c654b 1211
15c4dc5a 1212 if (wait)
1213 if(*wait < 10)
1214 *wait = 10;
e30c654b 1215
15c4dc5a 1216 for(c = 0; c < *wait;) {
1217 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1218 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1219 c++;
1220 }
1221 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 1222 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 1223 (void)r;
1224 }
1225 WDT_HIT();
1226 }
e30c654b 1227
15c4dc5a 1228 c = 0;
1229 for(;;) {
1230 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1231 AT91C_BASE_SSC->SSC_THR = cmd[c];
1232 c++;
1233 if(c >= len) {
1234 break;
1235 }
1236 }
1237 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 1238 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 1239 (void)r;
1240 }
1241 WDT_HIT();
1242 }
1243 if (samples) *samples = (c + *wait) << 3;
1244}
1245
15c4dc5a 1246//-----------------------------------------------------------------------------
1247// Code a 7-bit command without parity bit
1248// This is especially for 0x26 and 0x52 (REQA and WUPA)
1249//-----------------------------------------------------------------------------
f7e3ed82 1250void ShortFrameFromReader(const uint8_t bt)
15c4dc5a 1251{
1252 int j;
1253 int last;
f7e3ed82 1254 uint8_t b;
15c4dc5a 1255
1256 ToSendReset();
1257
1258 // Start of Communication (Seq. Z)
72934aa3 1259 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1260 last = 0;
1261
1262 b = bt;
1263 for(j = 0; j < 7; j++) {
1264 if(b & 1) {
1265 // Sequence X
72934aa3 1266 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1267 last = 1;
1268 } else {
1269 if(last == 0) {
1270 // Sequence Z
72934aa3 1271 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1272 }
1273 else {
1274 // Sequence Y
72934aa3 1275 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1276 last = 0;
1277 }
1278 }
1279 b >>= 1;
1280 }
1281
1282 // End of Communication
1283 if(last == 0) {
1284 // Sequence Z
72934aa3 1285 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1286 }
1287 else {
1288 // Sequence Y
72934aa3 1289 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1290 last = 0;
1291 }
1292 // Sequence Y
72934aa3 1293 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1294
1295 // Just to be sure!
72934aa3 1296 ToSend[++ToSendMax] = SEC_Y;
1297 ToSend[++ToSendMax] = SEC_Y;
1298 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1299
1300 // Convert from last character reference to length
1301 ToSendMax++;
1302}
1303
1304//-----------------------------------------------------------------------------
1305// Prepare reader command to send to FPGA
e30c654b 1306//
15c4dc5a 1307//-----------------------------------------------------------------------------
f7e3ed82 1308void CodeIso14443aAsReaderPar(const uint8_t * cmd, int len, uint32_t dwParity)
15c4dc5a 1309{
1310 int i, j;
1311 int last;
f7e3ed82 1312 uint8_t b;
e30c654b 1313
15c4dc5a 1314 ToSendReset();
e30c654b 1315
15c4dc5a 1316 // Start of Communication (Seq. Z)
72934aa3 1317 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1318 last = 0;
e30c654b 1319
15c4dc5a 1320 // Generate send structure for the data bits
1321 for (i = 0; i < len; i++) {
1322 // Get the current byte to send
1323 b = cmd[i];
e30c654b 1324
15c4dc5a 1325 for (j = 0; j < 8; j++) {
1326 if (b & 1) {
1327 // Sequence X
72934aa3 1328 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1329 last = 1;
1330 } else {
1331 if (last == 0) {
1332 // Sequence Z
72934aa3 1333 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1334 } else {
1335 // Sequence Y
72934aa3 1336 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1337 last = 0;
1338 }
1339 }
1340 b >>= 1;
1341 }
e30c654b 1342
15c4dc5a 1343 // Get the parity bit
1344 if ((dwParity >> i) & 0x01) {
1345 // Sequence X
72934aa3 1346 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1347 last = 1;
1348 } else {
1349 if (last == 0) {
1350 // Sequence Z
72934aa3 1351 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1352 } else {
1353 // Sequence Y
72934aa3 1354 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1355 last = 0;
1356 }
1357 }
1358 }
e30c654b 1359
15c4dc5a 1360 // End of Communication
1361 if (last == 0) {
1362 // Sequence Z
72934aa3 1363 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1364 } else {
1365 // Sequence Y
72934aa3 1366 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1367 last = 0;
1368 }
1369 // Sequence Y
72934aa3 1370 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1371
15c4dc5a 1372 // Just to be sure!
72934aa3 1373 ToSend[++ToSendMax] = SEC_Y;
1374 ToSend[++ToSendMax] = SEC_Y;
1375 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1376
15c4dc5a 1377 // Convert from last character reference to length
1378 ToSendMax++;
1379}
1380
9ca155ba
M
1381//-----------------------------------------------------------------------------
1382// Wait for commands from reader
1383// Stop when button is pressed (return 1) or field was gone (return 2)
1384// Or return 0 when command is captured
1385//-----------------------------------------------------------------------------
1386static int EmGetCmd(uint8_t *received, int *len, int maxLen)
1387{
1388 *len = 0;
1389
1390 uint32_t timer = 0, vtime = 0;
1391 int analogCnt = 0;
1392 int analogAVG = 0;
1393
1394 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1395 // only, since we are receiving, not transmitting).
1396 // Signal field is off with the appropriate LED
1397 LED_D_OFF();
1398 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1399
1400 // Set ADC to read field strength
1401 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
1402 AT91C_BASE_ADC->ADC_MR =
1403 ADC_MODE_PRESCALE(32) |
1404 ADC_MODE_STARTUP_TIME(16) |
1405 ADC_MODE_SAMPLE_HOLD_TIME(8);
1406 AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF);
1407 // start ADC
1408 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1409
1410 // Now run a 'software UART' on the stream of incoming samples.
1411 Uart.output = received;
1412 Uart.byteCntMax = maxLen;
1413 Uart.state = STATE_UNSYNCD;
1414
1415 for(;;) {
1416 WDT_HIT();
1417
1418 if (BUTTON_PRESS()) return 1;
1419
1420 // test if the field exists
1421 if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF)) {
1422 analogCnt++;
1423 analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF];
1424 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1425 if (analogCnt >= 32) {
1426 if ((33000 * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
1427 vtime = GetTickCount();
1428 if (!timer) timer = vtime;
1429 // 50ms no field --> card to idle state
1430 if (vtime - timer > 50) return 2;
1431 } else
1432 if (timer) timer = 0;
1433 analogCnt = 0;
1434 analogAVG = 0;
1435 }
1436 }
1437 // transmit none
1438 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1439 AT91C_BASE_SSC->SSC_THR = 0x00;
1440 }
1441 // receive and test the miller decoding
1442 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1443 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1444 if(MillerDecoding((b & 0xf0) >> 4)) {
1445 *len = Uart.byteCnt;
8f51ddb0 1446 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
9ca155ba
M
1447 return 0;
1448 }
1449 if(MillerDecoding(b & 0x0f)) {
1450 *len = Uart.byteCnt;
8f51ddb0 1451 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
9ca155ba
M
1452 return 0;
1453 }
1454 }
1455 }
1456}
1457
1458static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded)
1459{
1460 int i, u = 0;
1461 uint8_t b = 0;
1462
1463 // Modulate Manchester
1464 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1465 AT91C_BASE_SSC->SSC_THR = 0x00;
1466 FpgaSetupSsc();
1467
1468 // include correction bit
1469 i = 1;
1470 if((Uart.parityBits & 0x01) || correctionNeeded) {
1471 // 1236, so correction bit needed
1472 i = 0;
1473 }
1474
1475 // send cycle
1476 for(;;) {
1477 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1478 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1479 (void)b;
1480 }
1481 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1482 if(i > respLen) {
8f51ddb0 1483 b = 0xff; // was 0x00
9ca155ba
M
1484 u++;
1485 } else {
1486 b = resp[i];
1487 i++;
1488 }
1489 AT91C_BASE_SSC->SSC_THR = b;
1490
1491 if(u > 4) break;
1492 }
1493 if(BUTTON_PRESS()) {
1494 break;
1495 }
1496 }
1497
1498 return 0;
1499}
1500
8f51ddb0
M
1501int EmSend4bitEx(uint8_t resp, int correctionNeeded){
1502 Code4bitAnswerAsTag(resp);
0a39986e 1503 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
8f51ddb0 1504 if (tracing) LogTrace(&resp, 1, GetDeltaCountUS(), GetParity(&resp, 1), FALSE);
0a39986e 1505 return res;
9ca155ba
M
1506}
1507
8f51ddb0
M
1508int EmSend4bit(uint8_t resp){
1509 return EmSend4bitEx(resp, 0);
1510}
1511
1512int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par){
1513 CodeIso14443aAsTagPar(resp, respLen, par);
1514 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
1515 if (tracing) LogTrace(resp, respLen, GetDeltaCountUS(), par, FALSE);
1516 return res;
1517}
1518
1519int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded){
1520 return EmSendCmdExPar(resp, respLen, correctionNeeded, GetParity(resp, respLen));
1521}
1522
1523int EmSendCmd(uint8_t *resp, int respLen){
1524 return EmSendCmdExPar(resp, respLen, 0, GetParity(resp, respLen));
1525}
1526
1527int EmSendCmdPar(uint8_t *resp, int respLen, uint32_t par){
1528 return EmSendCmdExPar(resp, respLen, 0, par);
9ca155ba
M
1529}
1530
15c4dc5a 1531//-----------------------------------------------------------------------------
1532// Wait a certain time for tag response
1533// If a response is captured return TRUE
1534// If it takes to long return FALSE
1535//-----------------------------------------------------------------------------
f7e3ed82 1536static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
15c4dc5a 1537{
1538 // buffer needs to be 512 bytes
1539 int c;
1540
1541 // Set FPGA mode to "reader listen mode", no modulation (listen
534983d7 1542 // only, since we are receiving, not transmitting).
1543 // Signal field is on with the appropriate LED
1544 LED_D_ON();
1545 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
15c4dc5a 1546
534983d7 1547 // Now get the answer from the card
1548 Demod.output = receivedResponse;
1549 Demod.len = 0;
1550 Demod.state = DEMOD_UNSYNCD;
15c4dc5a 1551
f7e3ed82 1552 uint8_t b;
15c4dc5a 1553 if (elapsed) *elapsed = 0;
1554
1555 c = 0;
1556 for(;;) {
534983d7 1557 WDT_HIT();
15c4dc5a 1558
534983d7 1559 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1560 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
15c4dc5a 1561 if (elapsed) (*elapsed)++;
534983d7 1562 }
1563 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1564 if(c < iso14a_timeout) { c++; } else { return FALSE; }
1565 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
72934aa3 1566 if(ManchesterDecoding((b>>4) & 0xf)) {
15c4dc5a 1567 *samples = ((c - 1) << 3) + 4;
1568 return TRUE;
1569 }
1570 if(ManchesterDecoding(b & 0x0f)) {
1571 *samples = c << 3;
1572 return TRUE;
1573 }
534983d7 1574 }
1575 }
15c4dc5a 1576}
1577
f7e3ed82 1578void ReaderTransmitShort(const uint8_t* bt)
15c4dc5a 1579{
1580 int wait = 0;
1581 int samples = 0;
1582
1583 ShortFrameFromReader(*bt);
e30c654b 1584
15c4dc5a 1585 // Select the card
e30c654b 1586 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
1587
15c4dc5a 1588 // Store reader command in buffer
1589 if (tracing) LogTrace(bt,1,0,GetParity(bt,1),TRUE);
1590}
1591
f7e3ed82 1592void ReaderTransmitPar(uint8_t* frame, int len, uint32_t par)
15c4dc5a 1593{
1594 int wait = 0;
1595 int samples = 0;
e30c654b 1596
15c4dc5a 1597 // This is tied to other size changes
f7e3ed82 1598 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
15c4dc5a 1599 CodeIso14443aAsReaderPar(frame,len,par);
e30c654b 1600
15c4dc5a 1601 // Select the card
e30c654b 1602 TransmitFor14443a(ToSend, ToSendMax, &samples, &wait);
534983d7 1603 if(trigger)
1604 LED_A_ON();
e30c654b 1605
15c4dc5a 1606 // Store reader command in buffer
1607 if (tracing) LogTrace(frame,len,0,par,TRUE);
1608}
1609
1610
f7e3ed82 1611void ReaderTransmit(uint8_t* frame, int len)
15c4dc5a 1612{
1613 // Generate parity and redirect
1614 ReaderTransmitPar(frame,len,GetParity(frame,len));
1615}
1616
f7e3ed82 1617int ReaderReceive(uint8_t* receivedAnswer)
15c4dc5a 1618{
1619 int samples = 0;
20f9a2a1 1620 if (!GetIso14443aAnswerFromTag(receivedAnswer,160,&samples,0)) return FALSE;
15c4dc5a 1621 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
7e758047 1622 if(samples == 0) return FALSE;
1623 return Demod.len;
15c4dc5a 1624}
1625
f89c7050
M
1626int ReaderReceivePar(uint8_t* receivedAnswer, uint32_t * parptr)
1627{
1628 int samples = 0;
1629 if (!GetIso14443aAnswerFromTag(receivedAnswer,160,&samples,0)) return FALSE;
1630 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1631 *parptr = Demod.parityBits;
1632 if(samples == 0) return FALSE;
1633 return Demod.len;
1634}
1635
7e758047 1636/* performs iso14443a anticolision procedure
534983d7 1637 * fills the uid pointer unless NULL
1638 * fills resp_data unless NULL */
79a73ab2 1639int iso14443a_select_card(byte_t* uid_ptr, iso14a_card_select_t* p_hi14a_card, uint32_t* cuid_ptr) {
20f9a2a1 1640 uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
f7e3ed82 1641 uint8_t sel_all[] = { 0x93,0x20 };
1642 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
7e758047 1643 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
902cb3c0 1644 uint8_t* resp = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET); // was 3560 - tied to other size changes
79a73ab2 1645 byte_t uid_resp[4];
1646 size_t uid_resp_len;
15c4dc5a 1647
534983d7 1648 uint8_t sak = 0x04; // cascade uid
1649 int cascade_level = 0;
7e758047 1650 int len;
79a73ab2 1651
7e758047 1652 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1653 ReaderTransmitShort(wupa);
1654 // Receive the ATQA
1655 if(!ReaderReceive(resp)) return 0;
902cb3c0 1656// Dbprintf("atqa: %02x %02x",resp[0],resp[1]);
1657
79a73ab2 1658 if(p_hi14a_card) {
1659 memcpy(p_hi14a_card->atqa, resp, 2);
1660 p_hi14a_card->uidlen = 0;
1661 memset(p_hi14a_card->uid,0,10);
1662 }
534983d7 1663
79a73ab2 1664 // clear uid
1665 if (uid_ptr) {
1666 memset(uid_ptr,0,10);
1667 }
1668
534983d7 1669 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
7e758047 1670 // which case we need to make a cascade 2 request and select - this is a long UID
534983d7 1671 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1672 for(; sak & 0x04; cascade_level++)
7e758047 1673 {
534983d7 1674 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1675 sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
1676
1677 // SELECT_ALL
1678 ReaderTransmit(sel_all,sizeof(sel_all));
1679 if (!ReaderReceive(resp)) return 0;
79a73ab2 1680
1681 // First backup the current uid
1682 memcpy(uid_resp,resp,4);
1683 uid_resp_len = 4;
1684 // Dbprintf("uid: %02x %02x %02x %02x",uid_resp[0],uid_resp[1],uid_resp[2],uid_resp[3]);
1685
20f9a2a1 1686 // calculate crypto UID
79a73ab2 1687 if(cuid_ptr) {
1688 *cuid_ptr = bytes_to_num(uid_resp, 4);
1689 }
e30c654b 1690
7e758047 1691 // Construct SELECT UID command
534983d7 1692 memcpy(sel_uid+2,resp,5);
1693 AppendCrc14443a(sel_uid,7);
1694 ReaderTransmit(sel_uid,sizeof(sel_uid));
1695
7e758047 1696 // Receive the SAK
1697 if (!ReaderReceive(resp)) return 0;
534983d7 1698 sak = resp[0];
79a73ab2 1699
1700 // Test if more parts of the uid are comming
1701 if ((sak & 0x04) && uid_resp[0] == 0x88) {
1702 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
1703 // http://www.nxp.com/documents/application_note/AN10927.pdf
1704 memcpy(uid_ptr, uid_ptr + 1, 3);
1705 uid_resp_len = 3;
1706 }
1707
1708 if(uid_ptr) {
1709 memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len);
1710 }
1711
1712 if(p_hi14a_card) {
1713 memcpy(p_hi14a_card->uid + (cascade_level*3), uid_resp, uid_resp_len);
1714 p_hi14a_card->uidlen += uid_resp_len;
1715 }
7e758047 1716 }
79a73ab2 1717
1718 if(p_hi14a_card) {
1719 p_hi14a_card->sak = sak;
1720 p_hi14a_card->ats_len = 0;
20f9a2a1 1721 }
534983d7 1722
79a73ab2 1723 if( (sak & 0x20) == 0) {
7e758047 1724 return 2; // non iso14443a compliant tag
79a73ab2 1725 }
534983d7 1726
7e758047 1727 // Request for answer to select
79a73ab2 1728 if(p_hi14a_card) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
20f9a2a1
M
1729 AppendCrc14443a(rats, 2);
1730 ReaderTransmit(rats, sizeof(rats));
1731
1732 if (!(len = ReaderReceive(resp))) return 0;
1733
79a73ab2 1734 memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats));
1735 p_hi14a_card->ats_len = len;
534983d7 1736 }
20f9a2a1 1737
b0127e65 1738 // reset the PCB block number
1739 iso14_pcb_blocknum = 0;
7e758047 1740 return 1;
1741}
15c4dc5a 1742
7e758047 1743void iso14443a_setup() {
902cb3c0 1744 // Set up the synchronous serial port
1745 FpgaSetupSsc();
7e758047 1746 // Start from off (no field generated)
1747 // Signal field is off with the appropriate LED
1748 LED_D_OFF();
1749 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
902cb3c0 1750 SpinDelay(50);
15c4dc5a 1751
7e758047 1752 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
e30c654b 1753
7e758047 1754 // Now give it time to spin up.
1755 // Signal field is on with the appropriate LED
1756 LED_D_ON();
1757 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
902cb3c0 1758 SpinDelay(50);
534983d7 1759
1760 iso14a_timeout = 2048; //default
7e758047 1761}
15c4dc5a 1762
534983d7 1763int iso14_apdu(uint8_t * cmd, size_t cmd_len, void * data) {
1764 uint8_t real_cmd[cmd_len+4];
1765 real_cmd[0] = 0x0a; //I-Block
b0127e65 1766 // put block number into the PCB
1767 real_cmd[0] |= iso14_pcb_blocknum;
534983d7 1768 real_cmd[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1769 memcpy(real_cmd+2, cmd, cmd_len);
1770 AppendCrc14443a(real_cmd,cmd_len+2);
1771
1772 ReaderTransmit(real_cmd, cmd_len+4);
1773 size_t len = ReaderReceive(data);
b0127e65 1774 uint8_t * data_bytes = (uint8_t *) data;
1775 if (!len)
1776 return 0; //DATA LINK ERROR
1777 // if we received an I- or R(ACK)-Block with a block number equal to the
1778 // current block number, toggle the current block number
1779 else if (len >= 4 // PCB+CID+CRC = 4 bytes
1780 && ((data_bytes[0] & 0xC0) == 0 // I-Block
1781 || (data_bytes[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1782 && (data_bytes[0] & 0x01) == iso14_pcb_blocknum) // equal block numbers
1783 {
1784 iso14_pcb_blocknum ^= 1;
1785 }
1786
534983d7 1787 return len;
1788}
1789
7e758047 1790//-----------------------------------------------------------------------------
1791// Read an ISO 14443a tag. Send out commands and store answers.
1792//
1793//-----------------------------------------------------------------------------
902cb3c0 1794void ReaderIso14443a(UsbCommand * c)
7e758047 1795{
534983d7 1796 iso14a_command_t param = c->arg[0];
1797 uint8_t * cmd = c->d.asBytes;
1798 size_t len = c->arg[1];
79a73ab2 1799 uint32_t arg0 = 0;
1800 byte_t buf[USB_CMD_DATA_SIZE];
902cb3c0 1801
1802 iso14a_clear_trace();
1803 iso14a_set_tracing(true);
e30c654b 1804
79a73ab2 1805 if(param & ISO14A_REQUEST_TRIGGER) {
1806 iso14a_set_trigger(1);
1807 }
15c4dc5a 1808
534983d7 1809 if(param & ISO14A_CONNECT) {
1810 iso14443a_setup();
79a73ab2 1811 arg0 = iso14443a_select_card(NULL,(iso14a_card_select_t*)buf,NULL);
1812 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(iso14a_card_select_t));
902cb3c0 1813// UsbSendPacket((void *)ack, sizeof(UsbCommand));
534983d7 1814 }
e30c654b 1815
534983d7 1816 if(param & ISO14A_SET_TIMEOUT) {
1817 iso14a_timeout = c->arg[2];
1818 }
e30c654b 1819
534983d7 1820 if(param & ISO14A_SET_TIMEOUT) {
1821 iso14a_timeout = c->arg[2];
1822 }
e30c654b 1823
534983d7 1824 if(param & ISO14A_APDU) {
902cb3c0 1825 arg0 = iso14_apdu(cmd, len, buf);
79a73ab2 1826 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
902cb3c0 1827// UsbSendPacket((void *)ack, sizeof(UsbCommand));
534983d7 1828 }
e30c654b 1829
534983d7 1830 if(param & ISO14A_RAW) {
1831 if(param & ISO14A_APPEND_CRC) {
1832 AppendCrc14443a(cmd,len);
1833 len += 2;
15c4dc5a 1834 }
534983d7 1835 ReaderTransmit(cmd,len);
902cb3c0 1836 arg0 = ReaderReceive(buf);
1837// UsbSendPacket((void *)ack, sizeof(UsbCommand));
79a73ab2 1838 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
534983d7 1839 }
15c4dc5a 1840
79a73ab2 1841 if(param & ISO14A_REQUEST_TRIGGER) {
1842 iso14a_set_trigger(0);
1843 }
15c4dc5a 1844
79a73ab2 1845 if(param & ISO14A_NO_DISCONNECT) {
534983d7 1846 return;
79a73ab2 1847 }
15c4dc5a 1848
15c4dc5a 1849 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1850 LEDsoff();
15c4dc5a 1851}
b0127e65 1852
15c4dc5a 1853//-----------------------------------------------------------------------------
1854// Read an ISO 14443a tag. Send out commands and store answers.
1855//
1856//-----------------------------------------------------------------------------
f7e3ed82 1857void ReaderMifare(uint32_t parameter)
15c4dc5a 1858{
15c4dc5a 1859 // Mifare AUTH
f7e3ed82 1860 uint8_t mf_auth[] = { 0x60,0x00,0xf5,0x7b };
f89c7050 1861 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
e30c654b 1862
902cb3c0 1863 uint8_t* receivedAnswer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET); // was 3560 - tied to other size changes
f89c7050
M
1864 traceLen = 0;
1865 tracing = false;
e30c654b 1866
7e758047 1867 iso14443a_setup();
e30c654b 1868
15c4dc5a 1869 LED_A_ON();
1870 LED_B_OFF();
1871 LED_C_OFF();
e30c654b 1872
f89c7050
M
1873 byte_t nt_diff = 0;
1874 LED_A_OFF();
1875 byte_t par = 0;
9f693930 1876 //byte_t par_mask = 0xff;
f89c7050
M
1877 byte_t par_low = 0;
1878 int led_on = TRUE;
50193c1e 1879 uint8_t uid[8];
f89c7050 1880 uint32_t cuid;
e30c654b 1881
f89c7050
M
1882 tracing = FALSE;
1883 byte_t nt[4] = {0,0,0,0};
f397b5cc 1884 byte_t nt_attacked[4], nt_noattack[4];
f89c7050
M
1885 byte_t par_list[8] = {0,0,0,0,0,0,0,0};
1886 byte_t ks_list[8] = {0,0,0,0,0,0,0,0};
f397b5cc 1887 num_to_bytes(parameter, 4, nt_noattack);
50193c1e 1888 int isOK = 0, isNULL = 0;
f397b5cc 1889
f89c7050
M
1890 while(TRUE)
1891 {
bfaecce6 1892 LED_C_OFF();
f89c7050 1893 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
5a9506ac 1894 SpinDelay(50);
f89c7050 1895 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
bfaecce6
M
1896 LED_C_ON();
1897 SpinDelay(2);
e30c654b 1898
f89c7050
M
1899 // Test if the action was cancelled
1900 if(BUTTON_PRESS()) {
1901 break;
1902 }
e30c654b 1903
f89c7050 1904 if(!iso14443a_select_card(uid, NULL, &cuid)) continue;
e30c654b 1905
f89c7050
M
1906 // Transmit MIFARE_CLASSIC_AUTH
1907 ReaderTransmit(mf_auth, sizeof(mf_auth));
15c4dc5a 1908
f89c7050
M
1909 // Receive the (16 bit) "random" nonce
1910 if (!ReaderReceive(receivedAnswer)) continue;
1911 memcpy(nt, receivedAnswer, 4);
e30c654b 1912
f89c7050
M
1913 // Transmit reader nonce and reader answer
1914 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar),par);
15c4dc5a 1915
f89c7050
M
1916 // Receive 4 bit answer
1917 if (ReaderReceive(receivedAnswer))
1918 {
f397b5cc
M
1919 if ( (parameter != 0) && (memcmp(nt, nt_noattack, 4) == 0) ) continue;
1920
423efacc 1921 isNULL = !(nt_attacked[0] == 0) && (nt_attacked[1] == 0) && (nt_attacked[2] == 0) && (nt_attacked[3] == 0);
50193c1e
M
1922 if ( (isNULL != 0 ) && (memcmp(nt, nt_attacked, 4) != 0) ) continue;
1923
f89c7050
M
1924 if (nt_diff == 0)
1925 {
1926 LED_A_ON();
1927 memcpy(nt_attacked, nt, 4);
9f693930 1928 //par_mask = 0xf8;
f89c7050
M
1929 par_low = par & 0x07;
1930 }
15c4dc5a 1931
f89c7050
M
1932 led_on = !led_on;
1933 if(led_on) LED_B_ON(); else LED_B_OFF();
1934 par_list[nt_diff] = par;
1935 ks_list[nt_diff] = receivedAnswer[0] ^ 0x05;
e30c654b 1936
f89c7050
M
1937 // Test if the information is complete
1938 if (nt_diff == 0x07) {
1939 isOK = 1;
1940 break;
1941 }
1942
1943 nt_diff = (nt_diff + 1) & 0x07;
1944 mf_nr_ar[3] = nt_diff << 5;
1945 par = par_low;
1946 } else {
1947 if (nt_diff == 0)
1948 {
1949 par++;
1950 } else {
1951 par = (((par >> 3) + 1) << 3) | par_low;
1952 }
1953 }
1954 }
e30c654b 1955
f89c7050
M
1956 LogTrace(nt, 4, 0, GetParity(nt, 4), TRUE);
1957 LogTrace(par_list, 8, 0, GetParity(par_list, 8), TRUE);
1958 LogTrace(ks_list, 8, 0, GetParity(ks_list, 8), TRUE);
e30c654b 1959
902cb3c0 1960 byte_t buf[48];
1961// UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
1962 memcpy(buf + 0, uid, 4);
1963 memcpy(buf + 4, nt, 4);
1964 memcpy(buf + 8, par_list, 8);
1965 memcpy(buf + 16, ks_list, 8);
f89c7050
M
1966
1967 LED_B_ON();
902cb3c0 1968 cmd_send(CMD_ACK,isOK,0,0,buf,48);
1969// UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
f89c7050
M
1970 LED_B_OFF();
1971
1972 // Thats it...
15c4dc5a 1973 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1974 LEDsoff();
f89c7050
M
1975 tracing = TRUE;
1976
f397b5cc 1977 if (MF_DBGLEVEL >= 1) DbpString("COMMAND mifare FINISHED");
20f9a2a1
M
1978}
1979
20f9a2a1
M
1980
1981//-----------------------------------------------------------------------------
1982// MIFARE 1K simulate.
1983//
1984//-----------------------------------------------------------------------------
1985void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
1986{
50193c1e 1987 int cardSTATE = MFEMUL_NOFIELD;
8556b852 1988 int _7BUID = 0;
9ca155ba 1989 int vHf = 0; // in mV
9f693930 1990 //int nextCycleTimeout = 0;
8f51ddb0 1991 int res;
51969283 1992// uint32_t timer = 0;
0a39986e
M
1993 uint32_t selTimer = 0;
1994 uint32_t authTimer = 0;
1995 uint32_t par = 0;
9ca155ba 1996 int len = 0;
8f51ddb0 1997 uint8_t cardWRBL = 0;
9ca155ba
M
1998 uint8_t cardAUTHSC = 0;
1999 uint8_t cardAUTHKEY = 0xff; // no authentication
9f693930 2000 //uint32_t cardRn = 0;
51969283 2001 uint32_t cardRr = 0;
9ca155ba 2002 uint32_t cuid = 0;
9f693930 2003 //uint32_t rn_enc = 0;
51969283 2004 uint32_t ans = 0;
0014cb46
M
2005 uint32_t cardINTREG = 0;
2006 uint8_t cardINTBLOCK = 0;
9ca155ba
M
2007 struct Crypto1State mpcs = {0, 0};
2008 struct Crypto1State *pcs;
2009 pcs = &mpcs;
2010
8f51ddb0
M
2011 uint8_t* receivedCmd = eml_get_bigbufptr_recbuf();
2012 uint8_t *response = eml_get_bigbufptr_sendbuf();
9ca155ba 2013
8556b852 2014 static uint8_t rATQA[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
9ca155ba 2015
0a39986e
M
2016 static uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2017 static uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
9ca155ba 2018
0a39986e 2019 static uint8_t rSAK[] = {0x08, 0xb6, 0xdd};
8556b852 2020 static uint8_t rSAK1[] = {0x04, 0xda, 0x17};
9ca155ba 2021
0014cb46
M
2022 static uint8_t rAUTH_NT[] = {0x01, 0x02, 0x03, 0x04};
2023// static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
0a39986e 2024 static uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
0014cb46 2025
0a39986e
M
2026 // clear trace
2027 traceLen = 0;
2028 tracing = true;
51969283
M
2029
2030 // Authenticate response - nonce
2031 uint32_t nonce = bytes_to_num(rAUTH_NT, 4);
9ca155ba 2032
8556b852
M
2033 // get UID from emul memory
2034 emlGetMemBt(receivedCmd, 7, 1);
2035 _7BUID = !(receivedCmd[0] == 0x00);
2036 if (!_7BUID) { // ---------- 4BUID
2037 rATQA[0] = 0x04;
2038
2039 emlGetMemBt(rUIDBCC1, 0, 4);
2040 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
2041 } else { // ---------- 7BUID
2042 rATQA[0] = 0x44;
2043
2044 rUIDBCC1[0] = 0x88;
2045 emlGetMemBt(&rUIDBCC1[1], 0, 3);
2046 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
2047 emlGetMemBt(rUIDBCC2, 3, 4);
2048 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
2049 }
2050
9ca155ba 2051// -------------------------------------- test area
50193c1e 2052
9ca155ba 2053// -------------------------------------- END test area
8f51ddb0
M
2054 // start mkseconds counter
2055 StartCountUS();
9ca155ba
M
2056
2057 // We need to listen to the high-frequency, peak-detected path.
2058 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2059 FpgaSetupSsc();
2060
2061 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
2062 SpinDelay(200);
2063
0014cb46 2064 if (MF_DBGLEVEL >= 1) Dbprintf("Started. 7buid=%d", _7BUID);
8f51ddb0
M
2065 // calibrate mkseconds counter
2066 GetDeltaCountUS();
9ca155ba
M
2067 while (true) {
2068 WDT_HIT();
9ca155ba 2069
8f51ddb0
M
2070 if(BUTTON_PRESS()) {
2071 break;
2072 }
2073
9ca155ba
M
2074 // find reader field
2075 // Vref = 3300mV, and an 10:1 voltage divider on the input
2076 // can measure voltages up to 33000 mV
2077 if (cardSTATE == MFEMUL_NOFIELD) {
2078 vHf = (33000 * AvgAdc(ADC_CHAN_HF)) >> 10;
2079 if (vHf > MF_MINFIELDV) {
0014cb46 2080 cardSTATE_TO_IDLE();
9ca155ba
M
2081 LED_A_ON();
2082 }
2083 }
2084
2085 if (cardSTATE != MFEMUL_NOFIELD) {
81cd0474 2086 res = EmGetCmd(receivedCmd, &len, RECV_CMD_SIZE); // (+ nextCycleTimeout)
9ca155ba
M
2087 if (res == 2) {
2088 cardSTATE = MFEMUL_NOFIELD;
2089 LEDsoff();
2090 continue;
2091 }
2092 if(res) break;
2093 }
2094
9f693930 2095 //nextCycleTimeout = 0;
8f51ddb0 2096
9ca155ba 2097// if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
0a39986e
M
2098
2099 if (len != 4 && cardSTATE != MFEMUL_NOFIELD) { // len != 4 <---- speed up the code 4 authentication
8f51ddb0 2100 // REQ or WUP request in ANY state and WUP in HALTED state
0a39986e
M
2101 if (len == 1 && ((receivedCmd[0] == 0x26 && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == 0x52)) {
2102 selTimer = GetTickCount();
2103 EmSendCmdEx(rATQA, sizeof(rATQA), (receivedCmd[0] == 0x52));
2104 cardSTATE = MFEMUL_SELECT1;
2105
2106 // init crypto block
2107 LED_B_OFF();
2108 LED_C_OFF();
2109 crypto1_destroy(pcs);
2110 cardAUTHKEY = 0xff;
2111 }
2112 }
9ca155ba 2113
50193c1e
M
2114 switch (cardSTATE) {
2115 case MFEMUL_NOFIELD:{
2116 break;
2117 }
9ca155ba 2118 case MFEMUL_HALTED:{
0a39986e 2119 break;
9ca155ba 2120 }
50193c1e
M
2121 case MFEMUL_IDLE:{
2122 break;
2123 }
2124 case MFEMUL_SELECT1:{
9ca155ba
M
2125 // select all
2126 if (len == 2 && (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x20)) {
2127 EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
0014cb46 2128 break;
9ca155ba
M
2129 }
2130
2131 // select card
0a39986e
M
2132 if (len == 9 &&
2133 (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
8556b852
M
2134 if (!_7BUID)
2135 EmSendCmd(rSAK, sizeof(rSAK));
2136 else
2137 EmSendCmd(rSAK1, sizeof(rSAK1));
9ca155ba
M
2138
2139 cuid = bytes_to_num(rUIDBCC1, 4);
8556b852
M
2140 if (!_7BUID) {
2141 cardSTATE = MFEMUL_WORK;
0014cb46
M
2142 LED_B_ON();
2143 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
2144 break;
8556b852
M
2145 } else {
2146 cardSTATE = MFEMUL_SELECT2;
2147 break;
2148 }
9ca155ba
M
2149 }
2150
50193c1e
M
2151 break;
2152 }
2153 case MFEMUL_SELECT2:{
0014cb46
M
2154 if (!len) break;
2155
8556b852 2156 if (len == 2 && (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x20)) {
9ca155ba 2157 EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
8556b852
M
2158 break;
2159 }
9ca155ba 2160
8556b852
M
2161 // select 2 card
2162 if (len == 9 &&
2163 (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC2, 4) == 0)) {
2164 EmSendCmd(rSAK, sizeof(rSAK));
2165
2166 cuid = bytes_to_num(rUIDBCC2, 4);
2167 cardSTATE = MFEMUL_WORK;
2168 LED_B_ON();
0014cb46 2169 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer);
8556b852
M
2170 break;
2171 }
0014cb46
M
2172
2173 // i guess there is a command). go into the work state.
2174 if (len != 4) break;
2175 cardSTATE = MFEMUL_WORK;
2176 goto lbWORK;
50193c1e
M
2177 }
2178 case MFEMUL_AUTH1:{
9ca155ba 2179 if (len == 8) {
51969283 2180 // --- crypto
9f693930
GY
2181 //rn_enc = bytes_to_num(receivedCmd, 4);
2182 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
51969283
M
2183 cardRr = bytes_to_num(&receivedCmd[4], 4) ^ crypto1_word(pcs, 0, 0);
2184 // test if auth OK
2185 if (cardRr != prng_successor(nonce, 64)){
0014cb46
M
2186 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr, prng_successor(nonce, 64));
2187 cardSTATE_TO_IDLE();
51969283
M
2188 break;
2189 }
2190 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2191 num_to_bytes(ans, 4, rAUTH_AT);
2192 // --- crypto
2193 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
0a39986e
M
2194 cardSTATE = MFEMUL_AUTH2;
2195 } else {
0014cb46 2196 cardSTATE_TO_IDLE();
9ca155ba 2197 }
0a39986e 2198 if (cardSTATE != MFEMUL_AUTH2) break;
50193c1e
M
2199 }
2200 case MFEMUL_AUTH2:{
9ca155ba 2201 LED_C_ON();
0a39986e 2202 cardSTATE = MFEMUL_WORK;
0014cb46 2203 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC, cardAUTHKEY, GetTickCount() - authTimer);
50193c1e
M
2204 break;
2205 }
9ca155ba 2206 case MFEMUL_WORK:{
0014cb46 2207lbWORK: if (len == 0) break;
0a39986e 2208
51969283
M
2209 if (cardAUTHKEY == 0xff) {
2210 // first authentication
2211 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2212 authTimer = GetTickCount();
2213
2214 cardAUTHSC = receivedCmd[1] / 4; // received block num
2215 cardAUTHKEY = receivedCmd[0] - 0x60;
2216
2217 // --- crypto
2218 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
2219 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
2220 num_to_bytes(nonce, 4, rAUTH_AT);
2221 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2222 // --- crypto
2223
2224// last working revision
2225// EmSendCmd14443aRaw(resp1, resp1Len, 0);
2226// LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2227
2228 cardSTATE = MFEMUL_AUTH1;
9f693930 2229 //nextCycleTimeout = 10;
51969283
M
2230 break;
2231 }
2232 } else {
2233 // decrypt seqence
2234 mf_crypto1_decrypt(pcs, receivedCmd, len);
2235
2236 // nested authentication
2237 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2238 authTimer = GetTickCount();
2239
2240 cardAUTHSC = receivedCmd[1] / 4; // received block num
2241 cardAUTHKEY = receivedCmd[0] - 0x60;
2242
2243 // --- crypto
2244 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
2245 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
2246 num_to_bytes(ans, 4, rAUTH_AT);
2247 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2248 // --- crypto
2249
2250 cardSTATE = MFEMUL_AUTH1;
9f693930 2251 //nextCycleTimeout = 10;
51969283
M
2252 break;
2253 }
2254 }
0a39986e 2255
8f51ddb0
M
2256 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2257 // BUT... ACK --> NACK
2258 if (len == 1 && receivedCmd[0] == CARD_ACK) {
2259 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2260 break;
2261 }
2262
2263 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2264 if (len == 1 && receivedCmd[0] == CARD_NACK_NA) {
2265 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2266 break;
0a39986e
M
2267 }
2268
2269 // read block
2270 if (len == 4 && receivedCmd[0] == 0x30) {
51969283 2271 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
8f51ddb0
M
2272 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2273 break;
2274 }
2275 emlGetMem(response, receivedCmd[1], 1);
2276 AppendCrc14443a(response, 16);
2277 mf_crypto1_encrypt(pcs, response, 18, &par);
2278 EmSendCmdPar(response, 18, par);
0a39986e
M
2279 break;
2280 }
2281
2282 // write block
2283 if (len == 4 && receivedCmd[0] == 0xA0) {
51969283 2284 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
8f51ddb0
M
2285 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2286 break;
2287 }
2288 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
9f693930 2289 //nextCycleTimeout = 50;
8f51ddb0
M
2290 cardSTATE = MFEMUL_WRITEBL2;
2291 cardWRBL = receivedCmd[1];
0a39986e 2292 break;
9ca155ba 2293 }
8f51ddb0 2294
0014cb46
M
2295 // works with cardINTREG
2296
2297 // increment, decrement, restore
2298 if (len == 4 && (receivedCmd[0] == 0xC0 || receivedCmd[0] == 0xC1 || receivedCmd[0] == 0xC2)) {
2299 if (receivedCmd[1] >= 16 * 4 ||
2300 receivedCmd[1] / 4 != cardAUTHSC ||
2301 emlCheckValBl(receivedCmd[1])) {
2302 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2303 break;
2304 }
2305 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2306 if (receivedCmd[0] == 0xC1)
2307 cardSTATE = MFEMUL_INTREG_INC;
2308 if (receivedCmd[0] == 0xC0)
2309 cardSTATE = MFEMUL_INTREG_DEC;
2310 if (receivedCmd[0] == 0xC2)
2311 cardSTATE = MFEMUL_INTREG_REST;
2312 cardWRBL = receivedCmd[1];
2313
2314 break;
2315 }
2316
2317
2318 // transfer
2319 if (len == 4 && receivedCmd[0] == 0xB0) {
2320 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
2321 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2322 break;
2323 }
2324
2325 if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd[1]))
2326 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2327 else
2328 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2329
2330 break;
2331 }
2332
9ca155ba 2333 // halt
0a39986e 2334 if (len == 4 && (receivedCmd[0] == 0x50 && receivedCmd[1] == 0x00)) {
9ca155ba 2335 LED_B_OFF();
0a39986e 2336 LED_C_OFF();
0014cb46
M
2337 cardSTATE = MFEMUL_HALTED;
2338 if (MF_DBGLEVEL >= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
0a39986e 2339 break;
9ca155ba 2340 }
51969283 2341
8f51ddb0
M
2342 // command not allowed
2343 if (len == 4) {
2344 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2345 break;
2346 }
51969283
M
2347
2348 // case break
2349 break;
8f51ddb0
M
2350 }
2351 case MFEMUL_WRITEBL2:{
2352 if (len == 18){
2353 mf_crypto1_decrypt(pcs, receivedCmd, len);
2354 emlSetMem(receivedCmd, cardWRBL, 1);
2355 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2356 cardSTATE = MFEMUL_WORK;
2357 break;
51969283 2358 } else {
0014cb46 2359 cardSTATE_TO_IDLE();
51969283 2360 break;
8f51ddb0 2361 }
8f51ddb0 2362 break;
50193c1e 2363 }
0014cb46
M
2364
2365 case MFEMUL_INTREG_INC:{
2366 mf_crypto1_decrypt(pcs, receivedCmd, len);
2367 memcpy(&ans, receivedCmd, 4);
2368 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2369 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2370 cardSTATE_TO_IDLE();
2371 break;
2372 }
2373 cardINTREG = cardINTREG + ans;
2374 cardSTATE = MFEMUL_WORK;
2375 break;
2376 }
2377 case MFEMUL_INTREG_DEC:{
2378 mf_crypto1_decrypt(pcs, receivedCmd, len);
2379 memcpy(&ans, receivedCmd, 4);
2380 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2381 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2382 cardSTATE_TO_IDLE();
2383 break;
2384 }
2385 cardINTREG = cardINTREG - ans;
2386 cardSTATE = MFEMUL_WORK;
2387 break;
2388 }
2389 case MFEMUL_INTREG_REST:{
2390 mf_crypto1_decrypt(pcs, receivedCmd, len);
2391 memcpy(&ans, receivedCmd, 4);
2392 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2393 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2394 cardSTATE_TO_IDLE();
2395 break;
2396 }
2397 cardSTATE = MFEMUL_WORK;
2398 break;
2399 }
50193c1e 2400 }
50193c1e
M
2401 }
2402
9ca155ba
M
2403 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2404 LEDsoff();
2405
0a39986e 2406 // add trace trailer
8f51ddb0 2407 memset(rAUTH_NT, 0x44, 4);
0a39986e
M
2408 LogTrace(rAUTH_NT, 4, 0, 0, TRUE);
2409
0014cb46 2410 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, traceLen);
15c4dc5a 2411}
b62a5a84
M
2412
2413//-----------------------------------------------------------------------------
2414// MIFARE sniffer.
2415//
2416//-----------------------------------------------------------------------------
5cd9ec01
M
2417void RAMFUNC SniffMifare(uint8_t param) {
2418 // param:
2419 // bit 0 - trigger from first card answer
2420 // bit 1 - trigger from first reader 7-bit request
39864b0b
M
2421
2422 // C(red) A(yellow) B(green)
b62a5a84
M
2423 LEDsoff();
2424 // init trace buffer
d19929cb 2425 iso14a_clear_trace();
b62a5a84 2426
b62a5a84
M
2427 // The command (reader -> tag) that we're receiving.
2428 // The length of a received command will in most cases be no more than 18 bytes.
2429 // So 32 should be enough!
2430 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
2431 // The response (tag -> reader) that we're receiving.
2432 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
2433
2434 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2435 // into trace, along with its length and other annotations.
2436 //uint8_t *trace = (uint8_t *)BigBuf;
2437
2438 // The DMA buffer, used to stream samples from the FPGA
2439 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
5cd9ec01
M
2440 int8_t *data = dmaBuf;
2441 int maxDataLen = 0;
2442 int dataLen = 0;
b62a5a84
M
2443
2444 // Set up the demodulator for tag -> reader responses.
2445 Demod.output = receivedResponse;
2446 Demod.len = 0;
2447 Demod.state = DEMOD_UNSYNCD;
2448
2449 // Set up the demodulator for the reader -> tag commands
2450 memset(&Uart, 0, sizeof(Uart));
2451 Uart.output = receivedCmd;
2452 Uart.byteCntMax = 32; // was 100 (greg)//////////////////
2453 Uart.state = STATE_UNSYNCD;
2454
2455 // Setup for the DMA.
2456 FpgaSetupSsc();
b62a5a84
M
2457 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
2458
2459 // And put the FPGA in the appropriate mode
2460 // Signal field is off with the appropriate LED
2461 LED_D_OFF();
2462 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
2463 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
39864b0b
M
2464
2465 // init sniffer
2466 MfSniffInit();
2467 int sniffCounter = 0;
b62a5a84 2468
b62a5a84
M
2469 // And now we loop, receiving samples.
2470 while(true) {
5cd9ec01
M
2471 if(BUTTON_PRESS()) {
2472 DbpString("cancelled by button");
2473 goto done;
2474 }
2475
b62a5a84
M
2476 LED_A_ON();
2477 WDT_HIT();
39864b0b
M
2478
2479 if (++sniffCounter > 65) {
2480 if (MfSniffSend(2000)) {
55acbb2a 2481 FpgaEnableSscDma();
39864b0b
M
2482 }
2483 sniffCounter = 0;
2484 }
5cd9ec01
M
2485
2486 int register readBufDataP = data - dmaBuf;
2487 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
2488 if (readBufDataP <= dmaBufDataP){
2489 dataLen = dmaBufDataP - readBufDataP;
2490 } else {
2491 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP + 1;
2492 }
2493 // test for length of buffer
2494 if(dataLen > maxDataLen) {
2495 maxDataLen = dataLen;
2496 if(dataLen > 400) {
2497 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen);
b62a5a84
M
2498 goto done;
2499 }
2500 }
5cd9ec01 2501 if(dataLen < 1) continue;
b62a5a84 2502
5cd9ec01
M
2503 // primary buffer was stopped( <-- we lost data!
2504 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
2505 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
2506 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
55acbb2a 2507 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen); // temporary
5cd9ec01
M
2508 }
2509 // secondary buffer sets as primary, secondary buffer was stopped
2510 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
2511 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
b62a5a84
M
2512 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
2513 }
5cd9ec01
M
2514
2515 LED_A_OFF();
b62a5a84 2516
5cd9ec01 2517 if(MillerDecoding((data[0] & 0xF0) >> 4)) {
39864b0b 2518 LED_C_INV();
5cd9ec01 2519 // check - if there is a short 7bit request from reader
71d90e54 2520 if (MfSniffLogic(receivedCmd, Uart.byteCnt, Uart.parityBits, Uart.bitCnt, TRUE)) break;
5cd9ec01 2521
b62a5a84
M
2522 /* And ready to receive another command. */
2523 Uart.state = STATE_UNSYNCD;
39864b0b
M
2524
2525 /* And also reset the demod code */
b62a5a84 2526 Demod.state = DEMOD_UNSYNCD;
b62a5a84
M
2527 }
2528
5cd9ec01 2529 if(ManchesterDecoding(data[0] & 0x0F)) {
39864b0b 2530 LED_C_INV();
b62a5a84 2531
71d90e54 2532 if (MfSniffLogic(receivedResponse, Demod.len, Demod.parityBits, Demod.bitCount, FALSE)) break;
b62a5a84
M
2533
2534 // And ready to receive another response.
2535 memset(&Demod, 0, sizeof(Demod));
2536 Demod.output = receivedResponse;
2537 Demod.state = DEMOD_UNSYNCD;
39864b0b
M
2538
2539 /* And also reset the uart code */
2540 Uart.state = STATE_UNSYNCD;
b62a5a84
M
2541 }
2542
5cd9ec01
M
2543 data++;
2544 if(data > dmaBuf + DMA_BUFFER_SIZE) {
2545 data = dmaBuf;
b62a5a84
M
2546 }
2547 } // main cycle
2548
2549 DbpString("COMMAND FINISHED");
2550
2551done:
55acbb2a 2552 FpgaDisableSscDma();
39864b0b
M
2553 MfSniffEnd();
2554
55acbb2a 2555 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen, Uart.state, Uart.byteCnt, Uart.byteCntMax);
b62a5a84
M
2556 LEDsoff();
2557}
Impressum, Datenschutz