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