]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iclass.c
Merge pull request #862 from pwpiwi/fix_iclass_sim
[proxmark3-svn] / armsrc / iclass.c
CommitLineData
cee5a30d 1//-----------------------------------------------------------------------------
2// Gerhard de Koning Gans - May 2008
3// Hagen Fritsch - June 2010
4// Gerhard de Koning Gans - May 2011
1e262141 5// Gerhard de Koning Gans - June 2012 - Added iClass card and reader emulation
cee5a30d 6//
7// This code is licensed to you under the terms of the GNU GPL, version 2 or,
8// at your option, any later version. See the LICENSE.txt file for the text of
9// the license.
10//-----------------------------------------------------------------------------
11// Routines to support iClass.
12//-----------------------------------------------------------------------------
13// Based on ISO14443a implementation. Still in experimental phase.
14// Contribution made during a security research at Radboud University Nijmegen
17505ce2 15//
cee5a30d 16// Please feel free to contribute and extend iClass support!!
17//-----------------------------------------------------------------------------
18//
cee5a30d 19// FIX:
20// ====
21// We still have sometimes a demodulation error when snooping iClass communication.
22// The resulting trace of a read-block-03 command may look something like this:
23//
17505ce2 24// + 22279: : 0c 03 e8 01
cee5a30d 25//
26// ...with an incorrect answer...
27//
28// + 85: 0: TAG ff! ff! ff! ff! ff! ff! ff! ff! bb 33 bb 00 01! 0e! 04! bb !crc
29//
30// We still left the error signalling bytes in the traces like 0xbb
31//
32// A correct trace should look like this:
33//
17505ce2 34// + 21112: : 0c 03 e8 01
35// + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5
cee5a30d 36//
37//-----------------------------------------------------------------------------
38
17505ce2 39#include "iclass.h"
40
cee5a30d 41#include "proxmark3.h"
42#include "apps.h"
43#include "util.h"
44#include "string.h"
3d2c9c9b 45#include "printf.h"
7e67e42f 46#include "common.h"
fecd8202 47#include "cmd.h"
6e49717b 48#include "iso14443a.h"
3d2c9c9b 49#include "iso15693.h"
1e262141 50// Needed for CRC in emulation mode;
51// same construction as in ISO 14443;
52// different initial value (CRC_ICLASS)
53#include "iso14443crc.h"
c3963755 54#include "iso15693tools.h"
b67f7ec3 55#include "protocols.h"
10a8875c 56#include "optimized_cipher.h"
979c7655 57#include "usb_cdc.h" // for usb_poll_validate_length
fc52fbd4 58#include "fpgaloader.h"
10a8875c 59
1e262141 60static int timeout = 4096;
cee5a30d 61
8efd0b80 62// iCLASS has a slightly different timing compared to ISO15693. According to the picopass data sheet the tag response is expected 330us after
63// the reader command. This is measured from end of reader EOF to first modulation of the tag's SOF which starts with a 56,64us unmodulated period.
64// 330us = 140 ssp_clk cycles @ 423,75kHz when simulating.
65// 56,64us = 24 ssp_clk_cycles
66#define DELAY_ICLASS_VCD_TO_VICC_SIM 140
67#define TAG_SOF_UNMODULATED 24
68
cee5a30d 69//-----------------------------------------------------------------------------
70// The software UART that receives commands from the reader, and its state
71// variables.
72//-----------------------------------------------------------------------------
73static struct {
17505ce2 74 enum {
75 STATE_UNSYNCD,
76 STATE_START_OF_COMMUNICATION,
77 STATE_RECEIVING
78 } state;
79 uint16_t shiftReg;
80 int bitCnt;
81 int byteCnt;
82 int byteCntMax;
83 int posCnt;
84 int nOutOfCnt;
85 int OutOfCnt;
86 int syncBit;
87 int samples;
88 int highCnt;
89 int swapper;
90 int counter;
91 int bitBuffer;
92 int dropPosition;
93 uint8_t *output;
cee5a30d 94} Uart;
95
17505ce2 96static RAMFUNC int OutOfNDecoding(int bit) {
9f693930 97 //int error = 0;
cee5a30d 98 int bitright;
99
17505ce2 100 if (!Uart.bitBuffer) {
cee5a30d 101 Uart.bitBuffer = bit ^ 0xFF0;
44964fd1 102 return false;
17505ce2 103 } else {
cee5a30d 104 Uart.bitBuffer <<= 4;
105 Uart.bitBuffer ^= bit;
106 }
17505ce2 107
108 /*if (Uart.swapper) {
cee5a30d 109 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
110 Uart.byteCnt++;
111 Uart.swapper = 0;
17505ce2 112 if (Uart.byteCnt > 15) { return true; }
cee5a30d 113 }
114 else {
115 Uart.swapper = 1;
116 }*/
117
17505ce2 118 if (Uart.state != STATE_UNSYNCD) {
cee5a30d 119 Uart.posCnt++;
120
17505ce2 121 if ((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
cee5a30d 122 bit = 0x00;
17505ce2 123 } else {
cee5a30d 124 bit = 0x01;
125 }
17505ce2 126 if (((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
cee5a30d 127 bitright = 0x00;
17505ce2 128 } else {
cee5a30d 129 bitright = 0x01;
130 }
17505ce2 131 if (bit != bitright) {
132 bit = bitright;
133 }
134
cee5a30d 135
cee5a30d 136 // So, now we only have to deal with *bit*, lets see...
17505ce2 137 if (Uart.posCnt == 1) {
cee5a30d 138 // measurement first half bitperiod
17505ce2 139 if (!bit) {
cee5a30d 140 // Drop in first half means that we are either seeing
141 // an SOF or an EOF.
142
17505ce2 143 if (Uart.nOutOfCnt == 1) {
cee5a30d 144 // End of Communication
145 Uart.state = STATE_UNSYNCD;
146 Uart.highCnt = 0;
17505ce2 147 if (Uart.byteCnt == 0) {
cee5a30d 148 // Its not straightforward to show single EOFs
44964fd1 149 // So just leave it and do not return true
6a1f2d82 150 Uart.output[0] = 0xf0;
cee5a30d 151 Uart.byteCnt++;
17505ce2 152 } else {
44964fd1 153 return true;
cee5a30d 154 }
17505ce2 155 } else if (Uart.state != STATE_START_OF_COMMUNICATION) {
cee5a30d 156 // When not part of SOF or EOF, it is an error
157 Uart.state = STATE_UNSYNCD;
158 Uart.highCnt = 0;
9f693930 159 //error = 4;
cee5a30d 160 }
161 }
17505ce2 162 } else {
cee5a30d 163 // measurement second half bitperiod
164 // Count the bitslot we are in... (ISO 15693)
165 Uart.nOutOfCnt++;
17505ce2 166
167 if (!bit) {
168 if (Uart.dropPosition) {
169 if (Uart.state == STATE_START_OF_COMMUNICATION) {
9f693930 170 //error = 1;
17505ce2 171 } else {
9f693930 172 //error = 7;
cee5a30d 173 }
174 // It is an error if we already have seen a drop in current frame
175 Uart.state = STATE_UNSYNCD;
176 Uart.highCnt = 0;
17505ce2 177 } else {
cee5a30d 178 Uart.dropPosition = Uart.nOutOfCnt;
179 }
180 }
181
182 Uart.posCnt = 0;
183
17505ce2 184
185 if (Uart.nOutOfCnt == Uart.OutOfCnt && Uart.OutOfCnt == 4) {
cee5a30d 186 Uart.nOutOfCnt = 0;
17505ce2 187
188 if (Uart.state == STATE_START_OF_COMMUNICATION) {
189 if (Uart.dropPosition == 4) {
cee5a30d 190 Uart.state = STATE_RECEIVING;
191 Uart.OutOfCnt = 256;
17505ce2 192 } else if (Uart.dropPosition == 3) {
cee5a30d 193 Uart.state = STATE_RECEIVING;
194 Uart.OutOfCnt = 4;
195 //Uart.output[Uart.byteCnt] = 0xdd;
196 //Uart.byteCnt++;
17505ce2 197 } else {
cee5a30d 198 Uart.state = STATE_UNSYNCD;
199 Uart.highCnt = 0;
200 }
201 Uart.dropPosition = 0;
17505ce2 202 } else {
cee5a30d 203 // RECEIVING DATA
204 // 1 out of 4
17505ce2 205 if (!Uart.dropPosition) {
cee5a30d 206 Uart.state = STATE_UNSYNCD;
207 Uart.highCnt = 0;
9f693930 208 //error = 9;
17505ce2 209 } else {
cee5a30d 210 Uart.shiftReg >>= 2;
17505ce2 211
cee5a30d 212 // Swap bit order
213 Uart.dropPosition--;
17505ce2 214 //if (Uart.dropPosition == 1) { Uart.dropPosition = 2; }
215 //else if (Uart.dropPosition == 2) { Uart.dropPosition = 1; }
216
cee5a30d 217 Uart.shiftReg ^= ((Uart.dropPosition & 0x03) << 6);
218 Uart.bitCnt += 2;
219 Uart.dropPosition = 0;
220
17505ce2 221 if (Uart.bitCnt == 8) {
cee5a30d 222 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
223 Uart.byteCnt++;
cee5a30d 224 Uart.bitCnt = 0;
225 Uart.shiftReg = 0;
226 }
227 }
228 }
17505ce2 229 } else if (Uart.nOutOfCnt == Uart.OutOfCnt) {
cee5a30d 230 // RECEIVING DATA
231 // 1 out of 256
17505ce2 232 if (!Uart.dropPosition) {
cee5a30d 233 Uart.state = STATE_UNSYNCD;
234 Uart.highCnt = 0;
9f693930 235 //error = 3;
17505ce2 236 } else {
cee5a30d 237 Uart.dropPosition--;
238 Uart.output[Uart.byteCnt] = (Uart.dropPosition & 0xff);
239 Uart.byteCnt++;
cee5a30d 240 Uart.bitCnt = 0;
241 Uart.shiftReg = 0;
242 Uart.nOutOfCnt = 0;
243 Uart.dropPosition = 0;
244 }
245 }
246
17505ce2 247 /*if (error) {
cee5a30d 248 Uart.output[Uart.byteCnt] = 0xAA;
249 Uart.byteCnt++;
250 Uart.output[Uart.byteCnt] = error & 0xFF;
251 Uart.byteCnt++;
252 Uart.output[Uart.byteCnt] = 0xAA;
253 Uart.byteCnt++;
254 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
255 Uart.byteCnt++;
256 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
257 Uart.byteCnt++;
258 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
259 Uart.byteCnt++;
260 Uart.output[Uart.byteCnt] = 0xAA;
261 Uart.byteCnt++;
44964fd1 262 return true;
cee5a30d 263 }*/
264 }
265
17505ce2 266 } else {
cee5a30d 267 bit = Uart.bitBuffer & 0xf0;
268 bit >>= 4;
269 bit ^= 0x0F; // drops become 1s ;-)
17505ce2 270 if (bit) {
cee5a30d 271 // should have been high or at least (4 * 128) / fc
272 // according to ISO this should be at least (9 * 128 + 20) / fc
17505ce2 273 if (Uart.highCnt == 8) {
cee5a30d 274 // we went low, so this could be start of communication
275 // it turns out to be safer to choose a less significant
276 // syncbit... so we check whether the neighbour also represents the drop
277 Uart.posCnt = 1; // apparently we are busy with our first half bit period
278 Uart.syncBit = bit & 8;
279 Uart.samples = 3;
17505ce2 280 if (!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
281 else if (bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
282 if (!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
283 else if (bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
284 if (!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
285 if (Uart.syncBit && (Uart.bitBuffer & 8)) {
cee5a30d 286 Uart.syncBit = 8;
287
288 // the first half bit period is expected in next sample
289 Uart.posCnt = 0;
290 Uart.samples = 3;
291 }
17505ce2 292 } else if (bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
cee5a30d 293
294 Uart.syncBit <<= 4;
295 Uart.state = STATE_START_OF_COMMUNICATION;
296 Uart.bitCnt = 0;
297 Uart.byteCnt = 0;
cee5a30d 298 Uart.nOutOfCnt = 0;
299 Uart.OutOfCnt = 4; // Start at 1/4, could switch to 1/256
300 Uart.dropPosition = 0;
301 Uart.shiftReg = 0;
9f693930 302 //error = 0;
17505ce2 303 } else {
cee5a30d 304 Uart.highCnt = 0;
305 }
17505ce2 306 } else if (Uart.highCnt < 8) {
307 Uart.highCnt++;
cee5a30d 308 }
309 }
310
17505ce2 311 return false;
cee5a30d 312}
313
17505ce2 314
cee5a30d 315//=============================================================================
1e262141 316// Manchester
cee5a30d 317//=============================================================================
318
319static struct {
17505ce2 320 enum {
321 DEMOD_UNSYNCD,
cee5a30d 322 DEMOD_START_OF_COMMUNICATION,
323 DEMOD_START_OF_COMMUNICATION2,
324 DEMOD_START_OF_COMMUNICATION3,
325 DEMOD_SOF_COMPLETE,
326 DEMOD_MANCHESTER_D,
327 DEMOD_MANCHESTER_E,
328 DEMOD_END_OF_COMMUNICATION,
329 DEMOD_END_OF_COMMUNICATION2,
330 DEMOD_MANCHESTER_F,
17505ce2 331 DEMOD_ERROR_WAIT
332 } state;
333 int bitCount;
334 int posCount;
335 int syncBit;
336 uint16_t shiftReg;
337 int buffer;
338 int buffer2;
339 int buffer3;
340 int buff;
341 int samples;
342 int len;
cee5a30d 343 enum {
344 SUB_NONE,
345 SUB_FIRST_HALF,
346 SUB_SECOND_HALF,
347 SUB_BOTH
17505ce2 348 } sub;
349 uint8_t *output;
cee5a30d 350} Demod;
351
17505ce2 352static RAMFUNC int ManchesterDecoding(int v) {
cee5a30d 353 int bit;
354 int modulation;
355 int error = 0;
356
357 bit = Demod.buffer;
358 Demod.buffer = Demod.buffer2;
359 Demod.buffer2 = Demod.buffer3;
360 Demod.buffer3 = v;
361
17505ce2 362 if (Demod.buff < 3) {
cee5a30d 363 Demod.buff++;
44964fd1 364 return false;
cee5a30d 365 }
366
17505ce2 367 if (Demod.state==DEMOD_UNSYNCD) {
cee5a30d 368 Demod.output[Demod.len] = 0xfa;
369 Demod.syncBit = 0;
370 //Demod.samples = 0;
17505ce2 371 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
cee5a30d 372
17505ce2 373 if (bit & 0x08) {
cee5a30d 374 Demod.syncBit = 0x08;
375 }
376
17505ce2 377 if (bit & 0x04) {
378 if (Demod.syncBit) {
cee5a30d 379 bit <<= 4;
380 }
381 Demod.syncBit = 0x04;
382 }
383
17505ce2 384 if (bit & 0x02) {
385 if (Demod.syncBit) {
cee5a30d 386 bit <<= 2;
387 }
388 Demod.syncBit = 0x02;
389 }
390
17505ce2 391 if (bit & 0x01 && Demod.syncBit) {
cee5a30d 392 Demod.syncBit = 0x01;
393 }
17505ce2 394
395 if (Demod.syncBit) {
cee5a30d 396 Demod.len = 0;
397 Demod.state = DEMOD_START_OF_COMMUNICATION;
398 Demod.sub = SUB_FIRST_HALF;
399 Demod.bitCount = 0;
400 Demod.shiftReg = 0;
cee5a30d 401 Demod.samples = 0;
17505ce2 402 if (Demod.posCount) {
0ab9002f 403 switch (Demod.syncBit) {
cee5a30d 404 case 0x08: Demod.samples = 3; break;
405 case 0x04: Demod.samples = 2; break;
406 case 0x02: Demod.samples = 1; break;
407 case 0x01: Demod.samples = 0; break;
408 }
409 // SOF must be long burst... otherwise stay unsynced!!!
17505ce2 410 if (!(Demod.buffer & Demod.syncBit) || !(Demod.buffer2 & Demod.syncBit)) {
cee5a30d 411 Demod.state = DEMOD_UNSYNCD;
412 }
17505ce2 413 } else {
cee5a30d 414 // SOF must be long burst... otherwise stay unsynced!!!
17505ce2 415 if (!(Demod.buffer2 & Demod.syncBit) || !(Demod.buffer3 & Demod.syncBit)) {
cee5a30d 416 Demod.state = DEMOD_UNSYNCD;
417 error = 0x88;
418 }
419
420 }
421 error = 0;
422
423 }
17505ce2 424 } else {
0ab9002f 425 // state is DEMOD is in SYNC from here on.
cee5a30d 426 modulation = bit & Demod.syncBit;
427 modulation |= ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
cee5a30d 428
429 Demod.samples += 4;
430
0ab9002f 431 if (Demod.posCount == 0) {
cee5a30d 432 Demod.posCount = 1;
17505ce2 433 if (modulation) {
cee5a30d 434 Demod.sub = SUB_FIRST_HALF;
17505ce2 435 } else {
cee5a30d 436 Demod.sub = SUB_NONE;
437 }
17505ce2 438 } else {
cee5a30d 439 Demod.posCount = 0;
17505ce2 440 if (modulation) {
441 if (Demod.sub == SUB_FIRST_HALF) {
cee5a30d 442 Demod.sub = SUB_BOTH;
17505ce2 443 } else {
cee5a30d 444 Demod.sub = SUB_SECOND_HALF;
445 }
17505ce2 446 } else if (Demod.sub == SUB_NONE) {
447 if (Demod.state == DEMOD_SOF_COMPLETE) {
cee5a30d 448 Demod.output[Demod.len] = 0x0f;
449 Demod.len++;
cee5a30d 450 Demod.state = DEMOD_UNSYNCD;
44964fd1 451 return true;
17505ce2 452 } else {
cee5a30d 453 Demod.state = DEMOD_ERROR_WAIT;
454 error = 0x33;
455 }
cee5a30d 456 }
457
458 switch(Demod.state) {
459 case DEMOD_START_OF_COMMUNICATION:
17505ce2 460 if (Demod.sub == SUB_BOTH) {
cee5a30d 461 Demod.state = DEMOD_START_OF_COMMUNICATION2;
462 Demod.posCount = 1;
463 Demod.sub = SUB_NONE;
17505ce2 464 } else {
cee5a30d 465 Demod.output[Demod.len] = 0xab;
466 Demod.state = DEMOD_ERROR_WAIT;
467 error = 0xd2;
468 }
469 break;
470 case DEMOD_START_OF_COMMUNICATION2:
17505ce2 471 if (Demod.sub == SUB_SECOND_HALF) {
cee5a30d 472 Demod.state = DEMOD_START_OF_COMMUNICATION3;
17505ce2 473 } else {
cee5a30d 474 Demod.output[Demod.len] = 0xab;
475 Demod.state = DEMOD_ERROR_WAIT;
476 error = 0xd3;
477 }
478 break;
479 case DEMOD_START_OF_COMMUNICATION3:
17505ce2 480 if (Demod.sub == SUB_SECOND_HALF) {
cee5a30d 481 Demod.state = DEMOD_SOF_COMPLETE;
17505ce2 482 } else {
cee5a30d 483 Demod.output[Demod.len] = 0xab;
484 Demod.state = DEMOD_ERROR_WAIT;
485 error = 0xd4;
486 }
487 break;
488 case DEMOD_SOF_COMPLETE:
489 case DEMOD_MANCHESTER_D:
490 case DEMOD_MANCHESTER_E:
491 // OPPOSITE FROM ISO14443 - 11110000 = 0 (1 in 14443)
492 // 00001111 = 1 (0 in 14443)
17505ce2 493 if (Demod.sub == SUB_SECOND_HALF) { // SUB_FIRST_HALF
cee5a30d 494 Demod.bitCount++;
495 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
496 Demod.state = DEMOD_MANCHESTER_D;
17505ce2 497 } else if (Demod.sub == SUB_FIRST_HALF) { // SUB_SECOND_HALF
cee5a30d 498 Demod.bitCount++;
499 Demod.shiftReg >>= 1;
500 Demod.state = DEMOD_MANCHESTER_E;
17505ce2 501 } else if (Demod.sub == SUB_BOTH) {
cee5a30d 502 Demod.state = DEMOD_MANCHESTER_F;
17505ce2 503 } else {
cee5a30d 504 Demod.state = DEMOD_ERROR_WAIT;
505 error = 0x55;
506 }
507 break;
508
509 case DEMOD_MANCHESTER_F:
510 // Tag response does not need to be a complete byte!
17505ce2 511 if (Demod.len > 0 || Demod.bitCount > 0) {
512 if (Demod.bitCount > 1) { // was > 0, do not interpret last closing bit, is part of EOF
513 Demod.shiftReg >>= (9 - Demod.bitCount); // right align data
cee5a30d 514 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
515 Demod.len++;
cee5a30d 516 }
517
518 Demod.state = DEMOD_UNSYNCD;
44964fd1 519 return true;
17505ce2 520 } else {
cee5a30d 521 Demod.output[Demod.len] = 0xad;
522 Demod.state = DEMOD_ERROR_WAIT;
523 error = 0x03;
524 }
525 break;
526
527 case DEMOD_ERROR_WAIT:
528 Demod.state = DEMOD_UNSYNCD;
529 break;
530
531 default:
532 Demod.output[Demod.len] = 0xdd;
533 Demod.state = DEMOD_UNSYNCD;
534 break;
535 }
536
17505ce2 537 if (Demod.bitCount >= 8) {
cee5a30d 538 Demod.shiftReg >>= 1;
539 Demod.output[Demod.len] = (Demod.shiftReg & 0xff);
540 Demod.len++;
cee5a30d 541 Demod.bitCount = 0;
542 Demod.shiftReg = 0;
543 }
544
17505ce2 545 if (error) {
cee5a30d 546 Demod.output[Demod.len] = 0xBB;
547 Demod.len++;
548 Demod.output[Demod.len] = error & 0xFF;
549 Demod.len++;
550 Demod.output[Demod.len] = 0xBB;
551 Demod.len++;
552 Demod.output[Demod.len] = bit & 0xFF;
553 Demod.len++;
554 Demod.output[Demod.len] = Demod.buffer & 0xFF;
555 Demod.len++;
556 // Look harder ;-)
557 Demod.output[Demod.len] = Demod.buffer2 & 0xFF;
558 Demod.len++;
559 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
560 Demod.len++;
561 Demod.output[Demod.len] = 0xBB;
562 Demod.len++;
44964fd1 563 return true;
cee5a30d 564 }
565
566 }
567
568 } // end (state != UNSYNCED)
569
17505ce2 570 return false;
cee5a30d 571}
572
573//=============================================================================
1e262141 574// Finally, a `sniffer' for iClass communication
cee5a30d 575// Both sides of communication!
576//=============================================================================
577
578//-----------------------------------------------------------------------------
579// Record the sequence of commands sent by the reader to the tag, with
580// triggering so that we start recording at the point that the tag is moved
581// near the reader.
582//-----------------------------------------------------------------------------
17505ce2 583void RAMFUNC SnoopIClass(void) {
cee5a30d 584
17505ce2 585 // We won't start recording the frames that we acquire until we trigger;
586 // a good trigger condition to get started is probably when we see a
587 // response from the tag.
588 //int triggered = false; // false to wait first for card
cee5a30d 589
17505ce2 590 // The command (reader -> tag) that we're receiving.
cee5a30d 591 // The length of a received command will in most cases be no more than 18 bytes.
592 // So 32 should be enough!
f71f4deb 593 #define ICLASS_BUFFER_SIZE 32
594 uint8_t readerToTagCmd[ICLASS_BUFFER_SIZE];
17505ce2 595 // The response (tag -> reader) that we're receiving.
f71f4deb 596 uint8_t tagToReaderResponse[ICLASS_BUFFER_SIZE];
17505ce2 597
598 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
599
600 // free all BigBuf memory
f71f4deb 601 BigBuf_free();
17505ce2 602 // The DMA buffer, used to stream samples from the FPGA
603 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
604
44964fd1 605 set_tracing(true);
3000dc4e 606 clear_trace();
17505ce2 607 iso14a_set_trigger(false);
cee5a30d 608
f71f4deb 609 int lastRxCounter;
17505ce2 610 uint8_t *upTo;
611 int smpl;
612 int maxBehindBy = 0;
cee5a30d 613
17505ce2 614 // Count of samples received so far, so that we can include timing
615 // information in the trace buffer.
616 int samples = 0;
617 rsamples = 0;
cee5a30d 618
17505ce2 619 // Set up the demodulator for tag -> reader responses.
17cba269 620 Demod.output = tagToReaderResponse;
17505ce2 621 Demod.len = 0;
622 Demod.state = DEMOD_UNSYNCD;
cee5a30d 623
17505ce2 624 // Setup for the DMA.
625 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A);
626 upTo = dmaBuf;
627 lastRxCounter = DMA_BUFFER_SIZE;
628 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
cee5a30d 629
17505ce2 630 // And the reader -> tag commands
631 memset(&Uart, 0, sizeof(Uart));
17cba269 632 Uart.output = readerToTagCmd;
17505ce2 633 Uart.byteCntMax = 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
634 Uart.state = STATE_UNSYNCD;
cee5a30d 635
17505ce2 636 // And put the FPGA in the appropriate mode
637 // Signal field is off with the appropriate LED
638 LED_D_OFF();
639 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
640 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
cee5a30d 641
81012e67 642 uint32_t time_0 = GetCountSspClk();
55eaed8f
MHS
643 uint32_t time_start = 0;
644 uint32_t time_stop = 0;
81012e67 645
17505ce2 646 int div = 0;
647 //int div2 = 0;
648 int decbyte = 0;
649 int decbyter = 0;
cee5a30d 650
17505ce2 651 // And now we loop, receiving samples.
652 for (;;) {
653 LED_A_ON();
654 WDT_HIT();
655 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1);
656 if (behindBy > maxBehindBy) {
657 maxBehindBy = behindBy;
658 if (behindBy > (9 * DMA_BUFFER_SIZE / 10)) {
659 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
660 goto done;
661 }
cee5a30d 662 }
17505ce2 663 if (behindBy < 1) continue;
cee5a30d 664
17505ce2 665 LED_A_OFF();
666 smpl = upTo[0];
667 upTo++;
668 lastRxCounter -= 1;
669 if (upTo - dmaBuf > DMA_BUFFER_SIZE) {
670 upTo -= DMA_BUFFER_SIZE;
671 lastRxCounter += DMA_BUFFER_SIZE;
672 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
673 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
674 }
675
676 //samples += 4;
677 samples += 1;
678
679 if (smpl & 0xF) {
680 decbyte ^= (1 << (3 - div));
681 }
682
683 // FOR READER SIDE COMMUMICATION...
684
685 decbyter <<= 2;
686 decbyter ^= (smpl & 0x30);
687
688 div++;
689
690 if ((div + 1) % 2 == 0) {
691 smpl = decbyter;
692 if (OutOfNDecoding((smpl & 0xF0) >> 4)) {
693 rsamples = samples - Uart.samples;
694 time_stop = (GetCountSspClk()-time_0) << 4;
695 LED_C_ON();
696
697 //if (!LogTrace(Uart.output, Uart.byteCnt, rsamples, Uart.parityBits,true)) break;
698 //if (!LogTrace(NULL, 0, Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, 0, true)) break;
699 uint8_t parity[MAX_PARITY_SIZE];
700 GetParity(Uart.output, Uart.byteCnt, parity);
701 LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, parity, true);
702
703 /* And ready to receive another command. */
704 Uart.state = STATE_UNSYNCD;
705 /* And also reset the demod code, which might have been */
706 /* false-triggered by the commands from the reader. */
707 Demod.state = DEMOD_UNSYNCD;
708 LED_B_OFF();
709 Uart.byteCnt = 0;
710 } else {
711 time_start = (GetCountSspClk()-time_0) << 4;
712 }
713 decbyter = 0;
714 }
715
716 if (div > 3) {
717 smpl = decbyte;
718 if (ManchesterDecoding(smpl & 0x0F)) {
719 time_stop = (GetCountSspClk()-time_0) << 4;
720
721 rsamples = samples - Demod.samples;
722 LED_B_ON();
723
724 uint8_t parity[MAX_PARITY_SIZE];
725 GetParity(Demod.output, Demod.len, parity);
726 LogTrace(Demod.output, Demod.len, time_start, time_stop, parity, false);
727
728 // And ready to receive another response.
729 memset(&Demod, 0, sizeof(Demod));
730 Demod.output = tagToReaderResponse;
731 Demod.state = DEMOD_UNSYNCD;
732 LED_C_OFF();
733 } else {
734 time_start = (GetCountSspClk()-time_0) << 4;
735 }
736
737 div = 0;
738 decbyte = 0x00;
cee5a30d 739 }
cee5a30d 740
17505ce2 741 if (BUTTON_PRESS()) {
742 DbpString("cancelled_a");
743 goto done;
744 }
745 }
cee5a30d 746
17505ce2 747 DbpString("COMMAND FINISHED");
cee5a30d 748
17505ce2 749 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
3000dc4e 750 Dbprintf("%x %x %x", Uart.byteCntMax, BigBuf_get_traceLen(), (int)Uart.output[0]);
cee5a30d 751
752done:
17505ce2 753 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
754 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
3000dc4e 755 Dbprintf("%x %x %x", Uart.byteCntMax, BigBuf_get_traceLen(), (int)Uart.output[0]);
17505ce2 756 LEDsoff();
1e262141 757}
758
912a3e94 759void rotateCSN(uint8_t* originalCSN, uint8_t* rotatedCSN) {
17505ce2 760 int i;
761 for (i = 0; i < 8; i++) {
912a3e94 762 rotatedCSN[i] = (originalCSN[i] >> 3) | (originalCSN[(i+1)%8] << 5);
1e262141 763 }
764}
765
3d2c9c9b 766// Encode SOF only
17505ce2 767static void CodeIClassTagSOF() {
81012e67 768 ToSendReset();
645c960f 769 ToSend[++ToSendMax] = 0x1D;
1e262141 770 ToSendMax++;
771}
1e262141 772
17505ce2 773static void AppendCrc(uint8_t *data, int len) {
774 ComputeCrc14443(CRC_ICLASS, data, len, data+len, data+len+1);
775}
81cd0474 776
b67f7ec3 777
ff7bb4ef
MHS
778/**
779 * @brief Does the actual simulation
ff7bb4ef 780 */
17505ce2 781int doIClassSimulation(int simulationMode, uint8_t *reader_mac_buf) {
0ab9002f 782
b67f7ec3
MHS
783 // free eventually allocated BigBuf memory
784 BigBuf_free_keep_EM();
55eaed8f 785
ae60ceca 786 uint16_t page_size = 32 * 8;
787 uint8_t current_page = 0;
0ab9002f 788
ae60ceca 789 // maintain cipher states for both credit and debit key for each page
790 State cipher_state_KC[8];
791 State cipher_state_KD[8];
792 State *cipher_state = &cipher_state_KD[0];
8efd0b80 793
0ab9002f 794 uint8_t *emulator = BigBuf_get_EM_addr();
795 uint8_t *csn = emulator;
0ab9002f 796
1e262141 797 // CSN followed by two CRC bytes
ae60ceca 798 uint8_t anticoll_data[10];
799 uint8_t csn_data[10];
17505ce2 800 memcpy(csn_data, csn, sizeof(csn_data));
801 Dbprintf("Simulating CSN %02x%02x%02x%02x%02x%02x%02x%02x", csn[0], csn[1], csn[2], csn[3], csn[4], csn[5], csn[6], csn[7]);
1e262141 802
1e262141 803 // Construct anticollision-CSN
17505ce2 804 rotateCSN(csn_data, anticoll_data);
1e262141 805
806 // Compute CRC on both CSNs
0ab9002f 807 AppendCrc(anticoll_data, 8);
808 AppendCrc(csn_data, 8);
b67f7ec3 809
8efd0b80 810 uint8_t diversified_key_d[8] = { 0x00 };
811 uint8_t diversified_key_c[8] = { 0x00 };
ae60ceca 812 uint8_t *diversified_key = diversified_key_d;
8efd0b80 813
ae60ceca 814 // configuration block
815 uint8_t conf_block[10] = {0x12, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0xFF, 0x3C, 0x00, 0x00};
ae60ceca 816
b67f7ec3 817 // e-Purse
0ab9002f 818 uint8_t card_challenge_data[8] = { 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
ae60ceca 819
0ab9002f 820 if (simulationMode == ICLASS_SIM_MODE_FULL) {
ae60ceca 821 // initialize from page 0
822 memcpy(conf_block, emulator + 8 * 1, 8);
823 memcpy(card_challenge_data, emulator + 8 * 2, 8); // e-purse
824 memcpy(diversified_key_d, emulator + 8 * 3, 8); // Kd
825 memcpy(diversified_key_c, emulator + 8 * 4, 8); // Kc
b67f7ec3 826 }
ae60ceca 827
8efd0b80 828 AppendCrc(conf_block, 8);
829
0ab9002f 830 // save card challenge for sim2,4 attack
831 if (reader_mac_buf != NULL) {
832 memcpy(reader_mac_buf, card_challenge_data, 8);
833 }
1e262141 834
ae60ceca 835 if (conf_block[5] & 0x80) {
836 page_size = 256 * 8;
837 }
838
839 // From PicoPass DS:
840 // When the page is in personalization mode this bit is equal to 1.
841 // Once the application issuer has personalized and coded its dedicated areas, this bit must be set to 0:
842 // the page is then "in application mode".
843 bool personalization_mode = conf_block[7] & 0x80;
844
845 // chip memory may be divided in 8 pages
846 uint8_t max_page = conf_block[4] & 0x10 ? 0 : 7;
8efd0b80 847
ae60ceca 848 // Precalculate the cipher states, feeding it the CC
849 cipher_state_KD[0] = opt_doTagMAC_1(card_challenge_data, diversified_key_d);
850 cipher_state_KC[0] = opt_doTagMAC_1(card_challenge_data, diversified_key_c);
851 if (simulationMode == ICLASS_SIM_MODE_FULL) {
852 for (int i = 1; i < max_page; i++) {
853 uint8_t *epurse = emulator + i*page_size + 8*2;
854 uint8_t *Kd = emulator + i*page_size + 8*3;
855 uint8_t *Kc = emulator + i*page_size + 8*4;
856 cipher_state_KD[i] = opt_doTagMAC_1(epurse, Kd);
857 cipher_state_KC[i] = opt_doTagMAC_1(epurse, Kc);
858 }
859 }
8efd0b80 860
ff7bb4ef 861 int exitLoop = 0;
1e262141 862 // Reader 0a
863 // Tag 0f
864 // Reader 0c
865 // Tag anticoll. CSN
866 // Reader 81 anticoll. CSN
867 // Tag CSN
868
55eaed8f 869 uint8_t *modulated_response;
b19caaef 870 int modulated_response_size = 0;
17505ce2 871 uint8_t *trace_data = NULL;
55eaed8f 872 int trace_data_size = 0;
1e262141 873
645c960f 874 // Respond SOF -- takes 1 bytes
ae60ceca 875 uint8_t *resp_sof = BigBuf_malloc(1);
b67f7ec3 876 int resp_sof_Len;
1e262141 877
878 // Anticollision CSN (rotated CSN)
645c960f 879 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
0ab9002f 880 uint8_t *resp_anticoll = BigBuf_malloc(22);
b67f7ec3 881 int resp_anticoll_len;
1e262141 882
0ab9002f 883 // CSN (block 0)
645c960f 884 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
0ab9002f 885 uint8_t *resp_csn = BigBuf_malloc(22);
b67f7ec3 886 int resp_csn_len;
1e262141 887
0ab9002f 888 // configuration (block 1) picopass 2ks
889 uint8_t *resp_conf = BigBuf_malloc(22);
890 int resp_conf_len;
0ab9002f 891
892 // e-Purse (block 2)
b3cc5f29 893 // 18: Takes 2 bytes for SOF/EOF and 8 * 2 = 16 bytes (2 bytes/bit)
0ab9002f 894 uint8_t *resp_cc = BigBuf_malloc(18);
b67f7ec3 895 int resp_cc_len;
1e262141 896
a66f26da 897 // Kd, Kc (blocks 3 and 4). Cannot be read. Always respond with 0xff bytes only
898 uint8_t *resp_ff = BigBuf_malloc(22);
899 int resp_ff_len;
900 uint8_t ff_data[10] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00};
901 AppendCrc(ff_data, 8);
902
0ab9002f 903 // Application Issuer Area (block 5)
904 uint8_t *resp_aia = BigBuf_malloc(22);
905 int resp_aia_len;
906 uint8_t aia_data[10] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00};
907 AppendCrc(aia_data, 8);
908
f71f4deb 909 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
1e262141 910 int len;
911
1e262141 912 // Prepare card messages
1e262141 913
3d2c9c9b 914 // First card answer: SOF only
1e262141 915 CodeIClassTagSOF();
17505ce2 916 memcpy(resp_sof, ToSend, ToSendMax);
917 resp_sof_Len = ToSendMax;
1e262141 918
919 // Anticollision CSN
3d2c9c9b 920 CodeIso15693AsTag(anticoll_data, sizeof(anticoll_data));
17505ce2 921 memcpy(resp_anticoll, ToSend, ToSendMax);
922 resp_anticoll_len = ToSendMax;
1e262141 923
0ab9002f 924 // CSN (block 0)
3d2c9c9b 925 CodeIso15693AsTag(csn_data, sizeof(csn_data));
17505ce2 926 memcpy(resp_csn, ToSend, ToSendMax);
927 resp_csn_len = ToSendMax;
1e262141 928
0ab9002f 929 // Configuration (block 1)
ae60ceca 930 CodeIso15693AsTag(conf_block, sizeof(conf_block));
0ab9002f 931 memcpy(resp_conf, ToSend, ToSendMax);
932 resp_conf_len = ToSendMax;
933
934 // e-Purse (block 2)
3d2c9c9b 935 CodeIso15693AsTag(card_challenge_data, sizeof(card_challenge_data));
0ab9002f 936 memcpy(resp_cc, ToSend, ToSendMax);
937 resp_cc_len = ToSendMax;
938
a66f26da 939 // Kd, Kc (blocks 3 and 4)
940 CodeIso15693AsTag(ff_data, sizeof(ff_data));
941 memcpy(resp_ff, ToSend, ToSendMax);
942 resp_ff_len = ToSendMax;
943
0ab9002f 944 // Application Issuer Area (block 5)
3d2c9c9b 945 CodeIso15693AsTag(aia_data, sizeof(aia_data));
0ab9002f 946 memcpy(resp_aia, ToSend, ToSendMax);
947 resp_aia_len = ToSendMax;
1e262141 948
b19caaef 949 //This is used for responding to READ-block commands or other data which is dynamically generated
a66f26da 950 uint8_t *data_generic_trace = BigBuf_malloc(32 + 2); // 32 bytes data + 2byte CRC is max tag answer
951 uint8_t *data_response = BigBuf_malloc( (32 + 2) * 2 + 2);
e3dc1e4c 952
f83cc126 953 bool buttonPressed = false;
5b12974a 954 enum { IDLE, ACTIVATED, SELECTED, HALTED } chip_state = IDLE;
955
17505ce2 956 while (!exitLoop) {
0ab9002f 957 WDT_HIT();
3fe4ff4f 958
3d2c9c9b 959 uint32_t reader_eof_time = 0;
960 len = GetIso15693CommandFromReader(receivedCmd, MAX_FRAME_SIZE, &reader_eof_time);
961 if (len < 0) {
f83cc126 962 buttonPressed = true;
1e262141 963 break;
81cd0474 964 }
a66f26da 965
0ab9002f 966 // Now look at the reader command and provide appropriate responses
967 // default is no response:
968 modulated_response = NULL;
969 modulated_response_size = 0;
970 trace_data = NULL;
971 trace_data_size = 0;
a66f26da 972
5b12974a 973 if (receivedCmd[0] == ICLASS_CMD_ACTALL && len == 1) {
974 // Reader in anticollision phase
975 if (chip_state != HALTED) {
976 modulated_response = resp_sof;
977 modulated_response_size = resp_sof_Len;
5b12974a 978 chip_state = ACTIVATED;
979 }
0ab9002f 980
981 } else if (receivedCmd[0] == ICLASS_CMD_READ_OR_IDENTIFY && len == 1) { // identify
5b12974a 982 // Reader asks for anticollision CSN
983 if (chip_state == SELECTED || chip_state == ACTIVATED) {
984 modulated_response = resp_anticoll;
985 modulated_response_size = resp_anticoll_len;
986 trace_data = anticoll_data;
987 trace_data_size = sizeof(anticoll_data);
988 }
989
990 } else if (receivedCmd[0] == ICLASS_CMD_SELECT && len == 9) {
991 // Reader selects anticollision CSN.
992 // Tag sends the corresponding real CSN
993 if (chip_state == ACTIVATED || chip_state == SELECTED) {
994 if (!memcmp(receivedCmd+1, anticoll_data, 8)) {
995 modulated_response = resp_csn;
996 modulated_response_size = resp_csn_len;
997 trace_data = csn_data;
998 trace_data_size = sizeof(csn_data);
999 chip_state = SELECTED;
1000 } else {
1001 chip_state = IDLE;
1002 }
1003 } else if (chip_state == HALTED) {
1004 // RESELECT with CSN
1005 if (!memcmp(receivedCmd+1, csn_data, 8)) {
1006 modulated_response = resp_csn;
1007 modulated_response_size = resp_csn_len;
1008 trace_data = csn_data;
1009 trace_data_size = sizeof(csn_data);
1010 chip_state = SELECTED;
1011 }
1012 }
a66f26da 1013
0ab9002f 1014 } else if (receivedCmd[0] == ICLASS_CMD_READ_OR_IDENTIFY && len == 4) { // read block
1015 uint16_t blockNo = receivedCmd[1];
5b12974a 1016 if (chip_state == SELECTED) {
1017 if (simulationMode == ICLASS_SIM_MODE_EXIT_AFTER_MAC) {
1018 // provide defaults for blocks 0 ... 5
1019 switch (blockNo) {
1020 case 0: // csn (block 00)
1021 modulated_response = resp_csn;
1022 modulated_response_size = resp_csn_len;
1023 trace_data = csn_data;
1024 trace_data_size = sizeof(csn_data);
1025 break;
1026 case 1: // configuration (block 01)
1027 modulated_response = resp_conf;
1028 modulated_response_size = resp_conf_len;
ae60ceca 1029 trace_data = conf_block;
1030 trace_data_size = sizeof(conf_block);
5b12974a 1031 break;
1032 case 2: // e-purse (block 02)
1033 modulated_response = resp_cc;
1034 modulated_response_size = resp_cc_len;
1035 trace_data = card_challenge_data;
1036 trace_data_size = sizeof(card_challenge_data);
1037 // set epurse of sim2,4 attack
1038 if (reader_mac_buf != NULL) {
1039 memcpy(reader_mac_buf, card_challenge_data, 8);
1040 }
1041 break;
1042 case 3:
1043 case 4: // Kd, Kc, always respond with 0xff bytes
1044 modulated_response = resp_ff;
1045 modulated_response_size = resp_ff_len;
1046 trace_data = ff_data;
1047 trace_data_size = sizeof(ff_data);
1048 break;
1049 case 5: // Application Issuer Area (block 05)
1050 modulated_response = resp_aia;
1051 modulated_response_size = resp_aia_len;
1052 trace_data = aia_data;
1053 trace_data_size = sizeof(aia_data);
1054 break;
1055 // default: don't respond
1056 }
1057 } else if (simulationMode == ICLASS_SIM_MODE_FULL) {
1058 if (blockNo == 3 || blockNo == 4) { // Kd, Kc, always respond with 0xff bytes
a66f26da 1059 modulated_response = resp_ff;
1060 modulated_response_size = resp_ff_len;
1061 trace_data = ff_data;
1062 trace_data_size = sizeof(ff_data);
5b12974a 1063 } else { // use data from emulator memory
ae60ceca 1064 memcpy(data_generic_trace, emulator + current_page*page_size + 8*blockNo, 8);
5b12974a 1065 AppendCrc(data_generic_trace, 8);
1066 trace_data = data_generic_trace;
1067 trace_data_size = 10;
1068 CodeIso15693AsTag(trace_data, trace_data_size);
1069 memcpy(data_response, ToSend, ToSendMax);
1070 modulated_response = data_response;
1071 modulated_response_size = ToSendMax;
1072 }
0ab9002f 1073 }
5b12974a 1074 }
1075
1076 } else if ((receivedCmd[0] == ICLASS_CMD_READCHECK_KD
8ddb81a2 1077 || receivedCmd[0] == ICLASS_CMD_READCHECK_KC) && receivedCmd[1] == 0x02 && len == 2) {
5b12974a 1078 // Read e-purse (88 02 || 18 02)
1079 if (chip_state == SELECTED) {
ae60ceca 1080 if(receivedCmd[0] == ICLASS_CMD_READCHECK_KD){
1081 cipher_state = &cipher_state_KD[current_page];
1082 diversified_key = diversified_key_d;
1083 } else {
8efd0b80 1084 cipher_state = &cipher_state_KC[current_page];
ae60ceca 1085 diversified_key = diversified_key_c;
1086 }
5b12974a 1087 modulated_response = resp_cc;
1088 modulated_response_size = resp_cc_len;
1089 trace_data = card_challenge_data;
1090 trace_data_size = sizeof(card_challenge_data);
5b12974a 1091 }
1092
8efd0b80 1093 } else if ((receivedCmd[0] == ICLASS_CMD_CHECK_KC
8ddb81a2 1094 || receivedCmd[0] == ICLASS_CMD_CHECK_KD) && len == 9) {
5b12974a 1095 // Reader random and reader MAC!!!
1096 if (chip_state == SELECTED) {
1097 if (simulationMode == ICLASS_SIM_MODE_FULL) {
1098 //NR, from reader, is in receivedCmd+1
ae60ceca 1099 opt_doTagMAC_2(*cipher_state, receivedCmd+1, data_generic_trace, diversified_key);
a66f26da 1100 trace_data = data_generic_trace;
5b12974a 1101 trace_data_size = 4;
a66f26da 1102 CodeIso15693AsTag(trace_data, trace_data_size);
1103 memcpy(data_response, ToSend, ToSendMax);
1104 modulated_response = data_response;
1105 modulated_response_size = ToSendMax;
5b12974a 1106 //exitLoop = true;
1107 } else { // Not fullsim, we don't respond
1108 // We do not know what to answer, so lets keep quiet
1109 if (simulationMode == ICLASS_SIM_MODE_EXIT_AFTER_MAC) {
1110 if (reader_mac_buf != NULL) {
1111 // save NR and MAC for sim 2,4
1112 memcpy(reader_mac_buf + 8, receivedCmd + 1, 8);
1113 }
1114 exitLoop = true;
1115 }
a66f26da 1116 }
0ab9002f 1117 }
1118
5b12974a 1119 } else if (receivedCmd[0] == ICLASS_CMD_HALT && len == 1) {
1120 if (chip_state == SELECTED) {
1121 // Reader ends the session
ae60ceca 1122 modulated_response = resp_sof;
1123 modulated_response_size = resp_sof_Len;
5b12974a 1124 chip_state = HALTED;
1125 }
0ab9002f 1126
5b12974a 1127 } else if (simulationMode == ICLASS_SIM_MODE_FULL && receivedCmd[0] == ICLASS_CMD_READ4 && len == 4) { // 0x06
1128 //Read 4 blocks
1129 if (chip_state == SELECTED) {
ae60ceca 1130 uint8_t blockNo = receivedCmd[1];
1131 memcpy(data_generic_trace, emulator + current_page*page_size + blockNo*8, 8 * 4);
5b12974a 1132 AppendCrc(data_generic_trace, 8 * 4);
b19caaef 1133 trace_data = data_generic_trace;
5b12974a 1134 trace_data_size = 8 * 4 + 2;
3d2c9c9b 1135 CodeIso15693AsTag(trace_data, trace_data_size);
b67f7ec3
MHS
1136 memcpy(data_response, ToSend, ToSendMax);
1137 modulated_response = data_response;
1138 modulated_response_size = ToSendMax;
ff7bb4ef 1139 }
b67f7ec3 1140
5b12974a 1141 } else if (receivedCmd[0] == ICLASS_CMD_UPDATE && (len == 12 || len == 14)) {
0ab9002f 1142 // We're expected to respond with the data+crc, exactly what's already in the receivedCmd
1143 // receivedCmd is now UPDATE 1b | ADDRESS 1b | DATA 8b | Signature 4b or CRC 2b
5b12974a 1144 if (chip_state == SELECTED) {
8ddb81a2 1145 uint8_t blockNo = receivedCmd[1];
1146 if (blockNo == 2) { // update e-purse
1147 memcpy(card_challenge_data, receivedCmd+2, 8);
1148 CodeIso15693AsTag(card_challenge_data, sizeof(card_challenge_data));
1149 memcpy(resp_cc, ToSend, ToSendMax);
1150 resp_cc_len = ToSendMax;
ae60ceca 1151 cipher_state_KD[current_page] = opt_doTagMAC_1(card_challenge_data, diversified_key_d);
1152 cipher_state_KC[current_page] = opt_doTagMAC_1(card_challenge_data, diversified_key_c);
8ddb81a2 1153 if (simulationMode == ICLASS_SIM_MODE_FULL) {
ae60ceca 1154 memcpy(emulator + current_page*page_size + 8*2, card_challenge_data, 8);
8ddb81a2 1155 }
1156 } else if (blockNo == 3) { // update Kd
ae60ceca 1157 for (int i = 0; i < 8; i++) {
1158 if (personalization_mode) {
8efd0b80 1159 diversified_key_d[i] = receivedCmd[2 + i];
ae60ceca 1160 } else {
1161 diversified_key_d[i] ^= receivedCmd[2 + i];
8efd0b80 1162 }
8ddb81a2 1163 }
8efd0b80 1164 cipher_state_KD[current_page] = opt_doTagMAC_1(card_challenge_data, diversified_key_d);
8ddb81a2 1165 if (simulationMode == ICLASS_SIM_MODE_FULL) {
ae60ceca 1166 memcpy(emulator + current_page*page_size + 8*3, diversified_key_d, 8);
8ddb81a2 1167 }
8efd0b80 1168 } else if (blockNo == 4) { // update Kc
ae60ceca 1169 for (int i = 0; i < 8; i++) {
1170 if (personalization_mode) {
8efd0b80 1171 diversified_key_c[i] = receivedCmd[2 + i];
ae60ceca 1172 } else {
1173 diversified_key_c[i] ^= receivedCmd[2 + i];
8efd0b80 1174 }
8ddb81a2 1175 }
ae60ceca 1176 cipher_state_KC[current_page] = opt_doTagMAC_1(card_challenge_data, diversified_key_c);
8ddb81a2 1177 if (simulationMode == ICLASS_SIM_MODE_FULL) {
ae60ceca 1178 memcpy(emulator + current_page*page_size + 8*4, diversified_key_c, 8);
8ddb81a2 1179 }
1180 } else if (simulationMode == ICLASS_SIM_MODE_FULL) { // update any other data block
ae60ceca 1181 memcpy(emulator + current_page*page_size + 8*blockNo, receivedCmd+2, 8);
8efd0b80 1182 }
5b12974a 1183 memcpy(data_generic_trace, receivedCmd + 2, 8);
1184 AppendCrc(data_generic_trace, 8);
1185 trace_data = data_generic_trace;
1186 trace_data_size = 10;
1187 CodeIso15693AsTag(trace_data, trace_data_size);
1188 memcpy(data_response, ToSend, ToSendMax);
1189 modulated_response = data_response;
1190 modulated_response_size = ToSendMax;
1191 }
1192
1193 } else if (receivedCmd[0] == ICLASS_CMD_PAGESEL && len == 4) {
0ab9002f 1194 // Pagesel
ae60ceca 1195 // Chips with a single page will not answer to this command
8efd0b80 1196 // Otherwise, we should answer 8bytes (conf block 1) + 2bytes CRC
5b12974a 1197 if (chip_state == SELECTED) {
ae60ceca 1198 if (simulationMode == ICLASS_SIM_MODE_FULL && max_page > 0) {
1199 current_page = receivedCmd[1];
1200 memcpy(data_generic_trace, emulator + current_page*page_size + 8*1, 8);
1201 memcpy(diversified_key_d, emulator + current_page*page_size + 8*3, 8);
8efd0b80 1202 memcpy(diversified_key_c, emulator + current_page*page_size + 8*4, 8);
ae60ceca 1203 cipher_state = &cipher_state_KD[current_page];
1204 personalization_mode = data_generic_trace[7] & 0x80;
1205 AppendCrc(data_generic_trace, 8);
1206 trace_data = data_generic_trace;
1207 trace_data_size = 10;
1208 CodeIso15693AsTag(trace_data, trace_data_size);
8efd0b80 1209 memcpy(data_response, ToSend, ToSendMax);
ae60ceca 1210 modulated_response = data_response;
1211 modulated_response_size = ToSendMax;
1212 }
5b12974a 1213 }
0ab9002f 1214
e49d31c0 1215 } else if (receivedCmd[0] == 0x26 && len == 5) {
1216 // standard ISO15693 INVENTORY command. Ignore.
1217
17505ce2 1218 } else {
5b12974a 1219 // don't know how to handle this command
3d2c9c9b 1220 char debug_message[250]; // should be enough
1221 sprintf(debug_message, "Unhandled command (len = %d) received from reader:", len);
1222 for (int i = 0; i < len && strlen(debug_message) < sizeof(debug_message) - 3 - 1; i++) {
1223 sprintf(debug_message + strlen(debug_message), " %02x", receivedCmd[i]);
1224 }
1225 Dbprintf("%s", debug_message);
1e262141 1226 // Do not respond
1e262141 1227 }
1228
55eaed8f 1229 /**
8efd0b80 1230 A legit tag has about 273,4us delay between reader EOT and tag SOF.
55eaed8f 1231 **/
17505ce2 1232 if (modulated_response_size > 0) {
8efd0b80 1233 uint32_t response_time = reader_eof_time + DELAY_ICLASS_VCD_TO_VICC_SIM - TAG_SOF_UNMODULATED - DELAY_ARM_TO_READER_SIM;
1234 TransmitTo15693Reader(modulated_response, modulated_response_size, &response_time, 0, false);
3d2c9c9b 1235 LogTrace(trace_data, trace_data_size, response_time + DELAY_ARM_TO_READER_SIM, response_time + (modulated_response_size << 6) + DELAY_ARM_TO_READER_SIM, NULL, false);
81cd0474 1236 }
f83cc126 1237
81cd0474 1238 }
1e262141 1239
17505ce2 1240 if (buttonPressed)
f83cc126
MHS
1241 {
1242 DbpString("Button pressed");
1243 }
f83cc126 1244 return buttonPressed;
1e262141 1245}
1246
17505ce2 1247/**
1248 * @brief SimulateIClass simulates an iClass card.
1249 * @param arg0 type of simulation
1250 * - 0 uses the first 8 bytes in usb data as CSN
1251 * - 2 "dismantling iclass"-attack. This mode iterates through all CSN's specified
1252 * in the usb data. This mode collects MAC from the reader, in order to do an offline
1253 * attack on the keys. For more info, see "dismantling iclass" and proxclone.com.
1254 * - Other : Uses the default CSN (031fec8af7ff12e0)
1255 * @param arg1 - number of CSN's contained in datain (applicable for mode 2 only)
1256 * @param arg2
1257 * @param datain
1258 */
1259void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) {
8efd0b80 1260
ae60ceca 1261 LED_A_ON();
8efd0b80 1262
17505ce2 1263 uint32_t simType = arg0;
1264 uint32_t numberOfCSNS = arg1;
0ab9002f 1265
3d2c9c9b 1266 // setup hardware for simulation:
17505ce2 1267 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
3d2c9c9b 1268 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
a66f26da 1269 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
ae60ceca 1270 LED_D_OFF();
3d2c9c9b 1271 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
1272 StartCountSspClk();
e3dc1e4c 1273
17505ce2 1274 // Enable and clear the trace
1275 set_tracing(true);
1276 clear_trace();
1277 //Use the emulator memory for SIM
1278 uint8_t *emulator = BigBuf_get_EM_addr();
e3dc1e4c 1279
0ab9002f 1280 if (simType == ICLASS_SIM_MODE_CSN) {
17505ce2 1281 // Use the CSN from commandline
1282 memcpy(emulator, datain, 8);
0ab9002f 1283 doIClassSimulation(ICLASS_SIM_MODE_CSN, NULL);
1284 } else if (simType == ICLASS_SIM_MODE_CSN_DEFAULT) {
17505ce2 1285 //Default CSN
1286 uint8_t csn_crc[] = { 0x03, 0x1f, 0xec, 0x8a, 0xf7, 0xff, 0x12, 0xe0, 0x00, 0x00 };
1287 // Use the CSN from commandline
1288 memcpy(emulator, csn_crc, 8);
0ab9002f 1289 doIClassSimulation(ICLASS_SIM_MODE_CSN, NULL);
1290 } else if (simType == ICLASS_SIM_MODE_READER_ATTACK) {
17505ce2 1291 uint8_t mac_responses[USB_CMD_DATA_SIZE] = { 0 };
1292 Dbprintf("Going into attack mode, %d CSNS sent", numberOfCSNS);
1293 // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
0ab9002f 1294 // in order to collect MAC's from the reader. This can later be used in an offline-attack
17505ce2 1295 // in order to obtain the keys, as in the "dismantling iclass"-paper.
0ab9002f 1296 int i;
1297 for (i = 0; i < numberOfCSNS && i*16+16 <= USB_CMD_DATA_SIZE; i++) {
1298 // The usb data is 512 bytes, fitting 32 responses (8 byte CC + 4 Byte NR + 4 Byte MAC = 16 Byte response).
17505ce2 1299 memcpy(emulator, datain+(i*8), 8);
0ab9002f 1300 if (doIClassSimulation(ICLASS_SIM_MODE_EXIT_AFTER_MAC, mac_responses+i*16)) {
1301 // Button pressed
1302 break;
1e262141 1303 }
3d2c9c9b 1304 Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1305 datain[i*8+0], datain[i*8+1], datain[i*8+2], datain[i*8+3],
1306 datain[i*8+4], datain[i*8+5], datain[i*8+6], datain[i*8+7]);
1307 Dbprintf("NR,MAC: %02x %02x %02x %02x %02x %02x %02x %02x",
5b12974a 1308 mac_responses[i*16+ 8], mac_responses[i*16+ 9], mac_responses[i*16+10], mac_responses[i*16+11],
1309 mac_responses[i*16+12], mac_responses[i*16+13], mac_responses[i*16+14], mac_responses[i*16+15]);
1310 SpinDelay(100); // give the reader some time to prepare for next CSN
1e262141 1311 }
0ab9002f 1312 cmd_send(CMD_ACK, CMD_SIMULATE_TAG_ICLASS, i, 0, mac_responses, i*16);
1313 } else if (simType == ICLASS_SIM_MODE_FULL) {
17505ce2 1314 //This is 'full sim' mode, where we use the emulator storage for data.
0ab9002f 1315 doIClassSimulation(ICLASS_SIM_MODE_FULL, NULL);
17505ce2 1316 } else {
1317 // We may want a mode here where we hardcode the csns to use (from proxclone).
1318 // That will speed things up a little, but not required just yet.
1319 Dbprintf("The mode is not implemented, reserved for future use");
1e262141 1320 }
ae60ceca 1321
17505ce2 1322 Dbprintf("Done...");
1e262141 1323
ae60ceca 1324 LED_A_OFF();
1e262141 1325}
1326
17505ce2 1327
1e262141 1328/// THE READER CODE
1329
1330//-----------------------------------------------------------------------------
1331// Transmit the command (to the tag) that was placed in ToSend[].
1332//-----------------------------------------------------------------------------
17505ce2 1333static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait) {
1334 int c;
1335 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1336 AT91C_BASE_SSC->SSC_THR = 0x00;
1337 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A);
1338
1339 if (wait) {
1340 if (*wait < 10) *wait = 10;
1341
1342 for (c = 0; c < *wait;) {
1343 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1344 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1345 c++;
1346 }
1347 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1348 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1349 (void)r;
1350 }
1351 WDT_HIT();
1352 }
1353 }
1354
1355 uint8_t sendbyte;
1356 bool firstpart = true;
1357 c = 0;
1358 for (;;) {
1359 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1360
1361 // DOUBLE THE SAMPLES!
1362 if (firstpart) {
1363 sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4);
1364 } else {
1365 sendbyte = (cmd[c] & 0x0f) | (cmd[c] << 4);
1366 c++;
1367 }
1368 if (sendbyte == 0xff) {
1369 sendbyte = 0xfe;
1370 }
1371 AT91C_BASE_SSC->SSC_THR = sendbyte;
1372 firstpart = !firstpart;
1373
1374 if (c >= len) {
1375 break;
1376 }
1377 }
1378 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1379 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1380 (void)r;
1381 }
1382 WDT_HIT();
1383 }
1384 if (samples && wait) *samples = (c + *wait) << 3;
1e262141 1385}
1386
1387
1388//-----------------------------------------------------------------------------
1389// Prepare iClass reader command to send to FPGA
1390//-----------------------------------------------------------------------------
17505ce2 1391void CodeIClassCommand(const uint8_t *cmd, int len) {
1392 int i, j, k;
1393
1394 ToSendReset();
1395
1396 // Start of Communication: 1 out of 4
1397 ToSend[++ToSendMax] = 0xf0;
1398 ToSend[++ToSendMax] = 0x00;
1399 ToSend[++ToSendMax] = 0x0f;
1400 ToSend[++ToSendMax] = 0x00;
1401
1402 // Modulate the bytes
1403 for (i = 0; i < len; i++) {
1404 uint8_t b = cmd[i];
1405 for (j = 0; j < 4; j++) {
1406 for (k = 0; k < 4; k++) {
1407 if (k == (b & 3)) {
f784539d 1408 ToSend[++ToSendMax] = 0x0f;
17505ce2 1409 } else {
1410 ToSend[++ToSendMax] = 0x00;
1411 }
e3dc1e4c 1412 }
17505ce2 1413 b >>= 2;
1414 }
1415 }
1416
1417 // End of Communication
1418 ToSend[++ToSendMax] = 0x00;
1419 ToSend[++ToSendMax] = 0x00;
1420 ToSend[++ToSendMax] = 0xf0;
1421 ToSend[++ToSendMax] = 0x00;
1422
1423 // Convert from last character reference to length
1424 ToSendMax++;
1e262141 1425}
1426
17505ce2 1427static void ReaderTransmitIClass(uint8_t *frame, int len) {
6a1f2d82 1428 int wait = 0;
1429 int samples = 0;
1430
1431 // This is tied to other size changes
17505ce2 1432 CodeIClassCommand(frame, len);
6a1f2d82 1433
1434 // Select the card
1435 TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
17505ce2 1436 if (trigger)
6a1f2d82 1437 LED_A_ON();
1438
1439 // Store reader command in buffer
d9de20fa 1440 uint8_t par[MAX_PARITY_SIZE];
1441 GetParity(frame, len, par);
1442 LogTrace(frame, len, rsamples, rsamples, par, true);
1e262141 1443}
1444
1445//-----------------------------------------------------------------------------
1446// Wait a certain time for tag response
44964fd1 1447// If a response is captured return true
1448// If it takes too long return false
1e262141 1449//-----------------------------------------------------------------------------
17505ce2 1450static int GetIClassAnswer(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) {
1451 //uint8_t *buffer
1e262141 1452 // buffer needs to be 512 bytes
1453 int c;
1454
1455 // Set FPGA mode to "reader listen mode", no modulation (listen
1456 // only, since we are receiving, not transmitting).
1457 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1458
1459 // Now get the answer from the card
1460 Demod.output = receivedResponse;
1461 Demod.len = 0;
1462 Demod.state = DEMOD_UNSYNCD;
1463
1464 uint8_t b;
1465 if (elapsed) *elapsed = 0;
1466
44964fd1 1467 bool skip = false;
1e262141 1468
1469 c = 0;
17505ce2 1470 for (;;) {
1e262141 1471 WDT_HIT();
1472
17505ce2 1473 if (BUTTON_PRESS()) return false;
1e262141 1474
17505ce2 1475 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1e262141 1476 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1477 if (elapsed) (*elapsed)++;
1478 }
17505ce2 1479 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
a66f26da 1480 if (c < timeout) {
1481 c++;
1482 } else {
1483 return false;
17505ce2 1484 }
1e262141 1485 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1486 skip = !skip;
17505ce2 1487 if (skip) continue;
1488
1489 if (ManchesterDecoding(b & 0x0f)) {
1e262141 1490 *samples = c << 3;
44964fd1 1491 return true;
1e262141 1492 }
1493 }
1494 }
1495}
1496
17505ce2 1497static int ReaderReceiveIClass(uint8_t *receivedAnswer) {
1498 int samples = 0;
1499 if (!GetIClassAnswer(receivedAnswer, 160, &samples, 0)) {
1500 return false;
1501 }
1502 rsamples += samples;
1503 uint8_t parity[MAX_PARITY_SIZE];
1504 GetParity(receivedAnswer, Demod.len, parity);
1505 LogTrace(receivedAnswer, Demod.len, rsamples, rsamples, parity, false);
1506 if (samples == 0) return false;
1507 return Demod.len;
1e262141 1508}
1509
17505ce2 1510static void setupIclassReader() {
1511 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1512 // Reset trace buffer
1513 set_tracing(true);
1514 clear_trace();
1515
1516 // Setup SSC
1517 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A);
1518 // Start from off (no field generated)
1519 // Signal field is off with the appropriate LED
1520 LED_D_OFF();
1521 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1522 SpinDelay(200);
1523
1524 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1525
1526 // Now give it time to spin up.
1527 // Signal field is on with the appropriate LED
1528 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1529 SpinDelay(200);
1530 LED_A_ON();
aa41c605
MHS
1531
1532}
1533
17505ce2 1534static bool sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries) {
1535 while (retries-- > 0) {
c8dd9b09 1536 ReaderTransmitIClass(command, cmdsize);
17505ce2 1537 if (expected_size == ReaderReceiveIClass(resp)) {
aa53efc3 1538 return true;
c8dd9b09
MHS
1539 }
1540 }
aa53efc3 1541 return false;//Error
c8dd9b09
MHS
1542}
1543
1544/**
1545 * @brief Talks to an iclass tag, sends the commands to get CSN and CC.
1546 * @param card_data where the CSN and CC are stored for return
1547 * @return 0 = fail
1548 * 1 = Got CSN
1549 * 2 = Got CSN and CC
1550 */
17505ce2 1551static uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) {
c8dd9b09 1552 static uint8_t act_all[] = { 0x0a };
aa53efc3 1553 //static uint8_t identify[] = { 0x0c };
1554 static uint8_t identify[] = { 0x0c, 0x00, 0x73, 0x33 };
c8dd9b09 1555 static uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
aa53efc3 1556 static uint8_t readcheck_cc[]= { 0x88, 0x02 };
1557 if (use_credit_key)
1558 readcheck_cc[0] = 0x18;
1559 else
1560 readcheck_cc[0] = 0x88;
caaf9618 1561
f71f4deb 1562 uint8_t resp[ICLASS_BUFFER_SIZE];
c8dd9b09
MHS
1563
1564 uint8_t read_status = 0;
1565
1566 // Send act_all
1567 ReaderTransmitIClass(act_all, 1);
1568 // Card present?
17505ce2 1569 if (!ReaderReceiveIClass(resp)) return read_status;//Fail
8efd0b80 1570
c8dd9b09
MHS
1571 //Send Identify
1572 ReaderTransmitIClass(identify, 1);
1573 //We expect a 10-byte response here, 8 byte anticollision-CSN and 2 byte CRC
17505ce2 1574 uint8_t len = ReaderReceiveIClass(resp);
1575 if (len != 10) return read_status;//Fail
c8dd9b09
MHS
1576
1577 //Copy the Anti-collision CSN to our select-packet
17505ce2 1578 memcpy(&select[1], resp, 8);
c8dd9b09
MHS
1579 //Select the card
1580 ReaderTransmitIClass(select, sizeof(select));
1581 //We expect a 10-byte response here, 8 byte CSN and 2 byte CRC
17505ce2 1582 len = ReaderReceiveIClass(resp);
1583 if (len != 10) return read_status;//Fail
c8dd9b09
MHS
1584
1585 //Success - level 1, we got CSN
1586 //Save CSN in response data
17505ce2 1587 memcpy(card_data, resp, 8);
c8dd9b09
MHS
1588
1589 //Flag that we got to at least stage 1, read CSN
1590 read_status = 1;
1591
34e2af02 1592 // Card selected, now read e-purse (cc) (only 8 bytes no CRC)
c8dd9b09 1593 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
17505ce2 1594 if (ReaderReceiveIClass(resp) == 8) {
c8dd9b09 1595 //Save CC (e-purse) in response data
17505ce2 1596 memcpy(card_data+8, resp, 8);
caaf9618 1597 read_status++;
c8dd9b09
MHS
1598 }
1599
1600 return read_status;
1601}
17505ce2 1602
1603static uint8_t handshakeIclassTag(uint8_t *card_data) {
aa53efc3 1604 return handshakeIclassTag_ext(card_data, false);
1605}
c8dd9b09 1606
caaf9618 1607
1e262141 1608// Reader iClass Anticollission
1609void ReaderIClass(uint8_t arg0) {
1e262141 1610
17505ce2 1611 uint8_t card_data[6 * 8] = {0};
83602aff 1612 memset(card_data, 0xFF, sizeof(card_data));
17505ce2 1613 uint8_t last_csn[8] = {0,0,0,0,0,0,0,0};
34e2af02 1614 uint8_t resp[ICLASS_BUFFER_SIZE];
1615 memset(resp, 0xFF, sizeof(resp));
caaf9618 1616 //Read conf block CRC(0x01) => 0xfa 0x22
17505ce2 1617 uint8_t readConf[] = { ICLASS_CMD_READ_OR_IDENTIFY, 0x01, 0xfa, 0x22};
34e2af02 1618 //Read App Issuer Area block CRC(0x05) => 0xde 0x64
17505ce2 1619 uint8_t readAA[] = { ICLASS_CMD_READ_OR_IDENTIFY, 0x05, 0xde, 0x64};
caaf9618 1620
6ce0e538 1621 int read_status= 0;
caaf9618 1622 uint8_t result_status = 0;
34e2af02 1623 // flag to read until one tag is found successfully
6ce0e538 1624 bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE;
34e2af02 1625 // flag to only try 5 times to find one tag then return
6ce0e538 1626 bool try_once = arg0 & FLAG_ICLASS_READER_ONE_TRY;
34e2af02 1627 // if neither abort_after_read nor try_once then continue reading until button pressed.
1628
1629 bool use_credit_key = arg0 & FLAG_ICLASS_READER_CEDITKEY;
1630 // test flags for what blocks to be sure to read
1631 uint8_t flagReadConfig = arg0 & FLAG_ICLASS_READER_CONF;
1632 uint8_t flagReadCC = arg0 & FLAG_ICLASS_READER_CC;
1633 uint8_t flagReadAA = arg0 & FLAG_ICLASS_READER_AA;
1634
1635 set_tracing(true);
6ce0e538 1636 setupIclassReader();
1e262141 1637
17505ce2 1638 uint16_t tryCnt = 0;
979c7655 1639 bool userCancelled = BUTTON_PRESS() || usb_poll_validate_length();
17505ce2 1640 while (!userCancelled) {
979c7655 1641 // if only looking for one card try 2 times if we missed it the first time
17505ce2 1642 if (try_once && tryCnt > 2) {
1643 break;
1644 }
6ce0e538 1645 tryCnt++;
17505ce2 1646 if (!get_tracing()) {
c8dd9b09
MHS
1647 DbpString("Trace full");
1648 break;
1649 }
1650 WDT_HIT();
4ab4336a 1651
aa53efc3 1652 read_status = handshakeIclassTag_ext(card_data, use_credit_key);
2e9d4b3f 1653
17505ce2 1654 if (read_status == 0) continue;
1655 if (read_status == 1) result_status = FLAG_ICLASS_READER_CSN;
1656 if (read_status == 2) result_status = FLAG_ICLASS_READER_CSN | FLAG_ICLASS_READER_CC;
caaf9618
MHS
1657
1658 // handshakeIclass returns CSN|CC, but the actual block
1659 // layout is CSN|CONFIG|CC, so here we reorder the data,
1660 // moving CC forward 8 bytes
17505ce2 1661 memcpy(card_data+16, card_data+8, 8);
caaf9618 1662 //Read block 1, config
17505ce2 1663 if (flagReadConfig) {
1664 if (sendCmdGetResponseWithRetries(readConf, sizeof(readConf), resp, 10, 10)) {
caaf9618 1665 result_status |= FLAG_ICLASS_READER_CONF;
34e2af02 1666 memcpy(card_data+8, resp, 8);
aa53efc3 1667 } else {
1668 Dbprintf("Failed to dump config block");
caaf9618
MHS
1669 }
1670 }
c8dd9b09 1671
caaf9618 1672 //Read block 5, AA
17505ce2 1673 if (flagReadAA) {
1674 if (sendCmdGetResponseWithRetries(readAA, sizeof(readAA), resp, 10, 10)) {
caaf9618 1675 result_status |= FLAG_ICLASS_READER_AA;
17505ce2 1676 memcpy(card_data + (8*5), resp, 8);
aa53efc3 1677 } else {
1678 //Dbprintf("Failed to dump AA block");
caaf9618
MHS
1679 }
1680 }
1681
1682 // 0 : CSN
b67f7ec3 1683 // 1 : Configuration
caaf9618 1684 // 2 : e-purse
0ab9002f 1685 // 3 : kd / debit / aa2 (write-only)
1686 // 4 : kc / credit / aa1 (write-only)
1687 // 5 : AIA, Application issuer area
1688 //Then we can 'ship' back the 6 * 8 bytes of data,
b67f7ec3
MHS
1689 // with 0xFF:s in block 3 and 4.
1690
c8dd9b09 1691 LED_B_ON();
17505ce2 1692 //Send back to client, but don't bother if we already sent this -
979c7655 1693 // only useful if looping in arm (not try_once && not abort_after_read)
17505ce2 1694 if (memcmp(last_csn, card_data, 8) != 0) {
34e2af02 1695 // If caller requires that we get Conf, CC, AA, continue until we got it
17505ce2 1696 if ( (result_status ^ FLAG_ICLASS_READER_CSN ^ flagReadConfig ^ flagReadCC ^ flagReadAA) == 0) {
1697 cmd_send(CMD_ACK, result_status, 0, 0, card_data, sizeof(card_data));
1698 if (abort_after_read) {
f784539d 1699 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
c8dd9b09 1700 LED_A_OFF();
979c7655 1701 LED_B_OFF();
c8dd9b09
MHS
1702 return;
1703 }
1704 //Save that we already sent this....
1705 memcpy(last_csn, card_data, 8);
1706 }
caaf9618 1707
c8dd9b09
MHS
1708 }
1709 LED_B_OFF();
979c7655 1710 userCancelled = BUTTON_PRESS() || usb_poll_validate_length();
1711 }
1712 if (userCancelled) {
17505ce2 1713 cmd_send(CMD_ACK, 0xFF, 0, 0, card_data, 0);
979c7655 1714 } else {
17505ce2 1715 cmd_send(CMD_ACK, 0, 0, 0, card_data, 0);
6ce0e538 1716 }
3ac22ee1 1717 LED_A_OFF();
cee5a30d 1718}
1719
c3963755 1720void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
c8dd9b09 1721
cb29e00a 1722 uint8_t card_data[USB_CMD_DATA_SIZE]={0};
39d3ce5d
MHS
1723 uint16_t block_crc_LUT[255] = {0};
1724
17505ce2 1725 //Generate a lookup table for block crc
1726 for (int block = 0; block < 255; block++){
1727 char bl = block;
1728 block_crc_LUT[block] = iclass_crc16(&bl ,1);
39d3ce5d
MHS
1729 }
1730 //Dbprintf("Lookup table: %02x %02x %02x" ,block_crc_LUT[0],block_crc_LUT[1],block_crc_LUT[2]);
c8dd9b09 1731
c3963755 1732 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1733 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
17505ce2 1734
1735 uint16_t crc = 0;
1736 uint8_t cardsize = 0;
1737 uint8_t mem = 0;
1738
1739 static struct memory_t {
1740 int k16;
1741 int book;
1742 int k2;
1743 int lockauth;
1744 int keyaccess;
c3963755 1745 } memory;
17505ce2 1746
f71f4deb 1747 uint8_t resp[ICLASS_BUFFER_SIZE];
17505ce2 1748
1749 setupIclassReader();
44964fd1 1750 set_tracing(true);
c3963755 1751
17505ce2 1752 while (!BUTTON_PRESS()) {
1753
39d3ce5d
MHS
1754 WDT_HIT();
1755
17505ce2 1756 if (!get_tracing()) {
c3963755 1757 DbpString("Trace full");
1758 break;
1759 }
17505ce2 1760
c8dd9b09 1761 uint8_t read_status = handshakeIclassTag(card_data);
17505ce2 1762 if (read_status < 2) continue;
c8dd9b09
MHS
1763
1764 //for now replay captured auth (as cc not updated)
17505ce2 1765 memcpy(check+5, MAC, 4);
c8dd9b09 1766
17505ce2 1767 if (!sendCmdGetResponseWithRetries(check, sizeof(check), resp, 4, 5)) {
c8dd9b09
MHS
1768 Dbprintf("Error: Authentication Fail!");
1769 continue;
1770 }
1771
39d3ce5d
MHS
1772 //first get configuration block (block 1)
1773 crc = block_crc_LUT[1];
17505ce2 1774 read[1] = 1;
c8dd9b09
MHS
1775 read[2] = crc >> 8;
1776 read[3] = crc & 0xff;
1777
17505ce2 1778 if (!sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10)) {
39d3ce5d 1779 Dbprintf("Dump config (block 1) failed");
c8dd9b09
MHS
1780 continue;
1781 }
1782
17505ce2 1783 mem = resp[5];
1784 memory.k16 = (mem & 0x80);
1785 memory.book = (mem & 0x20);
1786 memory.k2 = (mem & 0x8);
1787 memory.lockauth = (mem & 0x2);
1788 memory.keyaccess = (mem & 0x1);
c8dd9b09
MHS
1789
1790 cardsize = memory.k16 ? 255 : 32;
1791 WDT_HIT();
cb29e00a 1792 //Set card_data to all zeroes, we'll fill it with data
17505ce2 1793 memset(card_data, 0x0, USB_CMD_DATA_SIZE);
1794 uint8_t failedRead = 0;
1795 uint32_t stored_data_length = 0;
c8dd9b09 1796 //then loop around remaining blocks
17505ce2 1797 for (int block = 0; block < cardsize; block++) {
1798 read[1] = block;
39d3ce5d 1799 crc = block_crc_LUT[block];
c8dd9b09
MHS
1800 read[2] = crc >> 8;
1801 read[3] = crc & 0xff;
1802
17505ce2 1803 if (sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10)) {
c8dd9b09 1804 Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
17505ce2 1805 block, resp[0], resp[1], resp[2],
c8dd9b09
MHS
1806 resp[3], resp[4], resp[5],
1807 resp[6], resp[7]);
1808
cb29e00a 1809 //Fill up the buffer
17505ce2 1810 memcpy(card_data+stored_data_length, resp, 8);
cb29e00a 1811 stored_data_length += 8;
17505ce2 1812 if (stored_data_length +8 > USB_CMD_DATA_SIZE) {
1813 //Time to send this off and start afresh
cb29e00a
MHS
1814 cmd_send(CMD_ACK,
1815 stored_data_length,//data length
1816 failedRead,//Failed blocks?
1817 0,//Not used ATM
1818 card_data, stored_data_length);
1819 //reset
1820 stored_data_length = 0;
1821 failedRead = 0;
1822 }
1823
17505ce2 1824 } else {
cb29e00a 1825 failedRead = 1;
17505ce2 1826 stored_data_length += 8;//Otherwise, data becomes misaligned
c8dd9b09 1827 Dbprintf("Failed to dump block %d", block);
c3963755 1828 }
1829 }
428d6221 1830
cb29e00a 1831 //Send off any remaining data
17505ce2 1832 if (stored_data_length > 0) {
cb29e00a
MHS
1833 cmd_send(CMD_ACK,
1834 stored_data_length,//data length
1835 failedRead,//Failed blocks?
1836 0,//Not used ATM
17505ce2 1837 card_data,
1838 stored_data_length);
cb29e00a 1839 }
c8dd9b09
MHS
1840 //If we got here, let's break
1841 break;
c3963755 1842 }
cb29e00a
MHS
1843 //Signal end of transmission
1844 cmd_send(CMD_ACK,
1845 0,//data length
1846 0,//Failed blocks?
1847 0,//Not used ATM
17505ce2 1848 card_data,
1849 0);
cb29e00a 1850
f784539d 1851 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
c3963755 1852 LED_A_OFF();
1853}
1854
aa53efc3 1855void iClass_Authentication(uint8_t *MAC) {
8ddb81a2 1856 uint8_t check[] = { ICLASS_CMD_CHECK_KD, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
aa53efc3 1857 uint8_t resp[ICLASS_BUFFER_SIZE];
17505ce2 1858 memcpy(check+5, MAC, 4);
aa53efc3 1859 bool isOK;
3ac22ee1 1860 isOK = sendCmdGetResponseWithRetries(check, sizeof(check), resp, 4, 6);
17505ce2 1861 cmd_send(CMD_ACK,isOK, 0, 0, 0, 0);
aa53efc3 1862}
17505ce2 1863
f784539d 1864static bool iClass_ReadBlock(uint8_t blockNo, uint8_t *readdata) {
3ac22ee1 1865 uint8_t readcmd[] = {ICLASS_CMD_READ_OR_IDENTIFY, blockNo, 0x00, 0x00}; //0x88, 0x00 // can i use 0C?
1866 char bl = blockNo;
1867 uint16_t rdCrc = iclass_crc16(&bl, 1);
1868 readcmd[2] = rdCrc >> 8;
1869 readcmd[3] = rdCrc & 0xff;
1870 uint8_t resp[] = {0,0,0,0,0,0,0,0,0,0};
1871 bool isOK = false;
912a3e94 1872
3ac22ee1 1873 //readcmd[1] = blockNo;
1874 isOK = sendCmdGetResponseWithRetries(readcmd, sizeof(readcmd), resp, 10, 10);
1875 memcpy(readdata, resp, sizeof(resp));
fecd8202 1876
aa53efc3 1877 return isOK;
1878}
fecd8202 1879
3ac22ee1 1880void iClass_ReadBlk(uint8_t blockno) {
1881 uint8_t readblockdata[] = {0,0,0,0,0,0,0,0,0,0};
aa53efc3 1882 bool isOK = false;
3ac22ee1 1883 isOK = iClass_ReadBlock(blockno, readblockdata);
1884 cmd_send(CMD_ACK, isOK, 0, 0, readblockdata, 8);
f784539d 1885 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
aa53efc3 1886}
fecd8202 1887
3ac22ee1 1888void iClass_Dump(uint8_t blockno, uint8_t numblks) {
1889 uint8_t readblockdata[] = {0,0,0,0,0,0,0,0,0,0};
aa53efc3 1890 bool isOK = false;
1891 uint8_t blkCnt = 0;
fecd8202 1892
aa53efc3 1893 BigBuf_free();
1894 uint8_t *dataout = BigBuf_malloc(255*8);
17505ce2 1895 if (dataout == NULL) {
aa53efc3 1896 Dbprintf("out of memory");
b8dd1ef6 1897 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1898 LED_D_OFF();
17505ce2 1899 cmd_send(CMD_ACK, 0, 1, 0, 0, 0);
b8dd1ef6 1900 LED_A_OFF();
aa53efc3 1901 return;
1902 }
17505ce2 1903 memset(dataout, 0xFF, 255*8);
fecd8202 1904
17505ce2 1905 for ( ; blkCnt < numblks; blkCnt++) {
3ac22ee1 1906 isOK = iClass_ReadBlock(blockno+blkCnt, readblockdata);
1907 if (!isOK || (readblockdata[0] == 0xBB || readblockdata[7] == 0xBB || readblockdata[2] == 0xBB)) { //try again
1908 isOK = iClass_ReadBlock(blockno+blkCnt, readblockdata);
aa53efc3 1909 if (!isOK) {
1910 Dbprintf("Block %02X failed to read", blkCnt+blockno);
1911 break;
1912 }
fecd8202 1913 }
17505ce2 1914 memcpy(dataout + (blkCnt*8), readblockdata, 8);
aa53efc3 1915 }
1916 //return pointer to dump memory in arg3
17505ce2 1917 cmd_send(CMD_ACK, isOK, blkCnt, BigBuf_max_traceLen(), 0, 0);
aa53efc3 1918 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1919 LEDsoff();
1920 BigBuf_free();
1921}
1922
17505ce2 1923static bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) {
671ff89f 1924 uint8_t write[] = { ICLASS_CMD_UPDATE, blockNo, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
3ac22ee1 1925 //uint8_t readblockdata[10];
1926 //write[1] = blockNo;
aa53efc3 1927 memcpy(write+2, data, 12); // data + mac
17505ce2 1928 char *wrCmd = (char *)(write+1);
671ff89f 1929 uint16_t wrCrc = iclass_crc16(wrCmd, 13);
1930 write[14] = wrCrc >> 8;
1931 write[15] = wrCrc & 0xff;
3ac22ee1 1932 uint8_t resp[] = {0,0,0,0,0,0,0,0,0,0};
671ff89f 1933 bool isOK = false;
1934
17505ce2 1935 isOK = sendCmdGetResponseWithRetries(write, sizeof(write), resp, sizeof(resp), 10);
671ff89f 1936 if (isOK) { //if reader responded correctly
3ac22ee1 1937 //Dbprintf("WriteResp: %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",resp[0],resp[1],resp[2],resp[3],resp[4],resp[5],resp[6],resp[7],resp[8],resp[9]);
17505ce2 1938 if (memcmp(write+2, resp, 8)) { //if response is not equal to write values
671ff89f 1939 if (blockNo != 3 && blockNo != 4) { //if not programming key areas (note key blocks don't get programmed with actual key data it is xor data)
1940 //error try again
17505ce2 1941 isOK = sendCmdGetResponseWithRetries(write, sizeof(write), resp, sizeof(resp), 10);
1942 }
fecd8202 1943 }
fecd8202 1944 }
aa53efc3 1945 return isOK;
1946}
1947
3ac22ee1 1948void iClass_WriteBlock(uint8_t blockNo, uint8_t *data) {
1949 bool isOK = iClass_WriteBlock_ext(blockNo, data);
aa53efc3 1950 if (isOK){
17505ce2 1951 Dbprintf("Write block [%02x] successful", blockNo);
aa53efc3 1952 } else {
17505ce2 1953 Dbprintf("Write block [%02x] failed", blockNo);
aa53efc3 1954 }
17505ce2 1955 cmd_send(CMD_ACK, isOK, 0, 0, 0, 0);
f784539d 1956 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
aa53efc3 1957}
1958
3ac22ee1 1959void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t *data) {
aa53efc3 1960 int i;
1961 int written = 0;
1962 int total_block = (endblock - startblock) + 1;
17505ce2 1963 for (i = 0; i < total_block; i++) {
aa53efc3 1964 // block number
17505ce2 1965 if (iClass_WriteBlock_ext(i+startblock, data + (i*12))){
1966 Dbprintf("Write block [%02x] successful", i + startblock);
aa53efc3 1967 written++;
1968 } else {
17505ce2 1969 if (iClass_WriteBlock_ext(i+startblock, data + (i*12))){
1970 Dbprintf("Write block [%02x] successful", i + startblock);
aa53efc3 1971 written++;
1972 } else {
17505ce2 1973 Dbprintf("Write block [%02x] failed", i + startblock);
aa53efc3 1974 }
1975 }
1976 }
1977 if (written == total_block)
1978 Dbprintf("Clone complete");
1979 else
17505ce2 1980 Dbprintf("Clone incomplete");
aa53efc3 1981
17505ce2 1982 cmd_send(CMD_ACK, 1, 0, 0, 0, 0);
aa53efc3 1983 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1984 LEDsoff();
1985}
Impressum, Datenschutz