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