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