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