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