free start pointer
[RRG-proxmark3.git] / armsrc / felica.c
blob55995cbb178eba428438ff7593f5c57c14d14868
1 #include "felica.h"
2 #include "proxmark3_arm.h"
3 #include "BigBuf.h"
4 #include "util.h"
5 #include "protocols.h"
6 #include "crc16.h"
7 #include "fpgaloader.h"
8 #include "string.h"
9 #include "commonutil.h"
10 #include "dbprint.h"
11 #include "ticks.h"
12 #include "iso18.h"
14 // FeliCa timings
15 // minimum time between the start bits of consecutive transfers from reader to tag: 6800 carrier (13.56MHz) cycles
16 #ifndef FELICA_REQUEST_GUARD_TIME
17 # define FELICA_REQUEST_GUARD_TIME (6800/16 + 1) // 426
18 #endif
19 // FRAME DELAY TIME 2672 carrier cycles
20 #ifndef FELICA_FRAME_DELAY_TIME
21 # define FELICA_FRAME_DELAY_TIME (2672/16 + 1) // 168
22 #endif
23 #ifndef DELAY_AIR2ARM_AS_READER
24 #define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16) // 91
25 #endif
26 #ifndef DELAY_ARM2AIR_AS_READER
27 #define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1) // 209
28 #endif
29 #define AddCrc(data, len) compute_crc(CRC_FELICA, (data), (len), (data)+(len)+1, (data)+(len))
31 static uint32_t felica_timeout;
32 static uint32_t felica_nexttransfertime;
33 static uint32_t felica_lasttime_prox2air_start;
35 static void iso18092_setup(uint8_t fpga_minor_mode);
36 static uint8_t felica_select_card(felica_card_select_t *card);
37 static void TransmitFor18092_AsReader(uint8_t *frame, int len, uint32_t *timing, uint8_t power, uint8_t highspeed);
38 static bool WaitForFelicaReply(uint16_t maxbytes);
40 static void iso18092_set_timeout(uint32_t timeout) {
41 felica_timeout = timeout + (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER) / (16 * 8) + 2;
44 static uint32_t iso18092_get_timeout(void) {
45 return felica_timeout - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER) / (16 * 8) - 2;
48 #ifndef FELICA_MAX_FRAME_SIZE
49 #define FELICA_MAX_FRAME_SIZE 260
50 #endif
52 //structure to hold outgoing NFC frame
53 static uint8_t frameSpace[FELICA_MAX_FRAME_SIZE + 4];
55 //structure to hold incoming NFC frame, used for ISO/IEC 18092-compatible frames
56 static struct {
57 enum {
58 STATE_UNSYNCD,
59 STATE_TRYING_SYNC,
60 STATE_GET_LENGTH,
61 STATE_GET_DATA,
62 STATE_GET_CRC,
63 STATE_FULL
64 } state;
66 uint16_t shiftReg; //for synchronization and offset calculation
67 int posCnt;
68 bool crc_ok;
69 int rem_len;
70 uint16_t len;
71 uint8_t byte_offset;
72 uint8_t *framebytes;
73 //should be enough. maxlen is 255, 254 for data, 2 for sync, 2 for crc
74 // 0,1 -> SYNC, 2 - len, 3-(len+1)->data, then crc
75 } FelicaFrame;
77 //b2 4d is SYNC, 45645 in 16-bit notation, 10110010 01001101 binary. Frame will not start filling until this is shifted in
78 //bit order in byte -reverse, I guess? [((bt>>0)&1),((bt>>1)&1),((bt>>2)&1),((bt>>3)&1),((bt>>4)&1),((bt>>5)&1),((bt>>6)&1),((bt>>7)&1)] -at least in the mode that I read those in
79 #ifndef SYNC_16BIT
80 # define SYNC_16BIT 0xB24D
81 #endif
83 static void FelicaFrameReset(void) {
84 FelicaFrame.state = STATE_UNSYNCD;
85 FelicaFrame.posCnt = 0;
86 FelicaFrame.crc_ok = false;
87 FelicaFrame.byte_offset = 0;
89 static void FelicaFrameinit(uint8_t *data) {
90 FelicaFrame.framebytes = data;
91 FelicaFrameReset();
94 //shift byte into frame, reversing it at the same time
95 static void shiftInByte(uint8_t bt) {
96 uint8_t j;
97 for (j = 0; j < FelicaFrame.byte_offset; j++) {
98 FelicaFrame.framebytes[FelicaFrame.posCnt] = (FelicaFrame.framebytes[FelicaFrame.posCnt] << 1) + (bt & 1);
99 bt >>= 1;
101 FelicaFrame.posCnt++;
102 FelicaFrame.rem_len--;
103 for (j = FelicaFrame.byte_offset; j < 8; j++) {
104 FelicaFrame.framebytes[FelicaFrame.posCnt] = (FelicaFrame.framebytes[FelicaFrame.posCnt] << 1) + (bt & 1);
105 bt >>= 1;
109 static void Process18092Byte(uint8_t bt) {
110 switch (FelicaFrame.state) {
111 case STATE_UNSYNCD: {
112 //almost any nonzero byte can be start of SYNC. SYNC should be preceded by zeros, but that is not always the case
113 if (bt > 0) {
114 FelicaFrame.shiftReg = reflect8(bt);
115 FelicaFrame.state = STATE_TRYING_SYNC;
117 break;
119 case STATE_TRYING_SYNC: {
120 if (bt == 0) {
121 //desync
122 FelicaFrame.shiftReg = bt;
123 FelicaFrame.state = STATE_UNSYNCD;
124 } else {
125 for (uint8_t i = 0; i < 8; i++) {
127 if (FelicaFrame.shiftReg == SYNC_16BIT) {
128 //SYNC done!
129 FelicaFrame.state = STATE_GET_LENGTH;
130 FelicaFrame.framebytes[0] = 0xb2;
131 FelicaFrame.framebytes[1] = 0x4d;
132 FelicaFrame.byte_offset = i;
133 //shift in remaining byte, slowly...
134 for (uint8_t j = i; j < 8; j++) {
135 FelicaFrame.framebytes[2] = (FelicaFrame.framebytes[2] << 1) + (bt & 1);
136 bt >>= 1;
139 FelicaFrame.posCnt = 2;
140 if (i == 0)
141 break;
143 FelicaFrame.shiftReg = (FelicaFrame.shiftReg << 1) + (bt & 1);
144 bt >>= 1;
147 //that byte was last byte of sync
148 if (FelicaFrame.shiftReg == SYNC_16BIT) {
149 //Force SYNC on next byte
150 FelicaFrame.state = STATE_GET_LENGTH;
151 FelicaFrame.framebytes[0] = 0xb2;
152 FelicaFrame.framebytes[1] = 0x4d;
153 FelicaFrame.byte_offset = 0;
154 FelicaFrame.posCnt = 1;
157 break;
159 case STATE_GET_LENGTH: {
160 shiftInByte(bt);
161 FelicaFrame.rem_len = FelicaFrame.framebytes[2] - 1;
162 FelicaFrame.len = FelicaFrame.framebytes[2] + 4; //with crc and sync
163 FelicaFrame.state = STATE_GET_DATA;
164 break;
166 case STATE_GET_DATA: {
167 shiftInByte(bt);
168 if (FelicaFrame.rem_len <= 0) {
169 FelicaFrame.state = STATE_GET_CRC;
170 FelicaFrame.rem_len = 2;
172 break;
174 case STATE_GET_CRC: {
175 shiftInByte(bt);
176 if (FelicaFrame.rem_len <= 0) {
177 FelicaFrame.rem_len = 0;
178 // skip sync 2bytes. IF ok, residue should be 0x0000
179 FelicaFrame.crc_ok = check_crc(CRC_FELICA, FelicaFrame.framebytes + 2, FelicaFrame.len - 2);
180 FelicaFrame.state = STATE_FULL;
182 break;
184 case STATE_FULL: //ignore byte. Don't forget to clear frame to receive next one...
185 default:
186 break;
190 /* Perform FeliCa polling card
191 * Currently does NOT do any collision handling.
192 * It expects 0-1 cards in the device's range.
193 * return 0 if selection was successful
195 static uint8_t felica_select_card(felica_card_select_t *card) {
197 // POLL command
198 // 0xB2 0x4B = sync code
199 // 0x06 = len
200 // 0x00 = rfu
201 // 0xff = system code service
202 // 0xff = system code service
203 // 0x00 = request code
204 // b7 = automatic switching of data rate
205 // b6-b2 = reserved
206 // b1 = fc/32 (414kbps)
207 // b0 = fc/64 (212kbps)
208 // 0x00 = timeslot
209 // 0x09 0x21 = crc
210 static uint8_t poll[10] = {0xb2, 0x4d, 0x06, FELICA_POLL_REQ, 0xFF, 0xFF, 0x00, 0x00, 0x09, 0x21};
211 int len = 10;
213 // We try 10 times, or if answer was received.
214 do {
215 // end-of-reception response packet data, wait approx. 501μs
216 // end-of-transmission command packet data, wait approx. 197μs
217 // polling card
218 TransmitFor18092_AsReader(poll, sizeof(poll), NULL, 1, 0);
220 // polling card, break if success
221 if (WaitForFelicaReply(1024) && FelicaFrame.framebytes[3] == FELICA_POLL_ACK)
222 break;
224 WDT_HIT();
226 } while (--len);
228 // timed-out
229 if (len == 0) {
230 if (DBGLEVEL >= DBG_DEBUG)
231 Dbprintf("Error: Time out card selection!");
232 return 1;
235 // wrong answer
236 if (FelicaFrame.framebytes[3] != FELICA_POLL_ACK) {
237 if (DBGLEVEL >= DBG_DEBUG)
238 Dbprintf("Error: Wrong answer selecting card!");
239 return 2;
242 // VALIDATE CRC residue is 0, hence if crc is a value it failed.
243 if (!check_crc(CRC_FELICA, FelicaFrame.framebytes + 2, FelicaFrame.len - 2)) {
244 if (DBGLEVEL >= DBG_DEBUG) {
245 Dbprintf("Error: CRC check failed!");
246 Dbprintf("CRC check was done on Frame: ");
247 Dbhexdump(FelicaFrame.len - 2, FelicaFrame.framebytes + 2, 0);
249 return 3;
252 if (DBGLEVEL >= DBG_DEBUG)
253 Dbprintf("Card selection successful!");
254 // copy UID
255 // idm 8
256 if (card) {
257 memcpy(card->IDm, FelicaFrame.framebytes + 4, 8);
258 memcpy(card->PMm, FelicaFrame.framebytes + 4 + 8, 8);
259 //memcpy(card->servicecode, FelicaFrame.framebytes + 4 + 8 + 8, 2);
260 memcpy(card->code, card->IDm, 2);
261 memcpy(card->uid, card->IDm + 2, 6);
262 memcpy(card->iccode, card->PMm, 2);
263 memcpy(card->mrt, card->PMm + 2, 6);
264 if (DBGLEVEL >= DBG_DEBUG) {
265 Dbprintf("Received Frame: ");
266 Dbhexdump(FelicaFrame.len, FelicaFrame.framebytes, 0);
269 // more status bytes?
270 return 0;
273 // poll-0: 0xb2,0x4d,0x06,0x00,0xff,0xff,0x00,0x00,0x09,0x21,
274 // resp: 0xb2,0x4d,0x12,0x01,0x01,0x2e,0x3d,0x17,0x26,0x47,0x80,0x95,0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00,0xb3,0x7f,
275 // poll-1 (reply with available system codes - NFC Tag3 specs, IIRC): 0xb2,0x4d,0x06,0x00,0xff,0xff,0x01,0x00,0x3a,0x10
276 // resp: 0xb2,0x4d,0x14,0x01, 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX, 0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00, 0x88,0xb4,0x0c,0xe2,
277 // page-req: 0xb2,0x4d,0x10,0x06, 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX, 0x01, 0x0b,0x00, 0x01, 0x80,0x00, 0x2e,0xb3,
278 // page-req: 0x06, IDm(8), ServiceNum(1),Slist(2*num) BLocknum (1) BLockids(2-3*num)
279 // page-resp: 0xb2,0x4d,0x1d,0x07, 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX, 0x00, 0x00, 0x01, 0x10,0x04,0x01,0x00,0x0d,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x23, 0xcb,0x6e,
281 // builds a readblock frame for felica lite(s). Using SERVICE: SERVICE_FELICA_LITE_READONLY
282 // Felica standard has a different file system, AFAIK,
283 // 8-byte IDm, number of blocks, blocks numbers
284 // number of blocks limited to 4 for FelicaLite(S)
285 static void BuildFliteRdblk(uint8_t *idm, int blocknum, uint16_t *blocks) {
286 if (blocknum > 4 || blocknum <= 0)
287 Dbprintf("Invalid number of blocks, %d != 4", blocknum);
289 uint8_t c = 0, i = 0;
291 // Sync bytes
292 frameSpace[c++] = 0xb2;
293 frameSpace[c++] = 0x4d;
295 c++; //set length later
297 frameSpace[c++] = FELICA_RDBLK_REQ; //command number
299 //card IDm, from poll
300 frameSpace[c++] = idm[0];
301 frameSpace[c++] = idm[1];
302 frameSpace[c++] = idm[2];
303 frameSpace[c++] = idm[3];
304 frameSpace[c++] = idm[4];
305 frameSpace[c++] = idm[5];
306 frameSpace[c++] = idm[6];
307 frameSpace[c++] = idm[7];
309 //number of services
310 frameSpace[c++] = 0x01;
312 //service code
313 frameSpace[c++] = (SERVICE_FELICA_LITE_READONLY >> 8);
314 frameSpace[c++] = SERVICE_FELICA_LITE_READONLY & 0xFF;
316 //number of blocks
317 frameSpace[c++] = blocknum;
319 for (i = 0; i < blocknum; i++) {
321 //3-byte block
322 if (blocks[i] >= 256) {
323 frameSpace[c++] = 0x00;
324 frameSpace[c++] = (blocks[i] >> 8); //block number, little endian....
325 frameSpace[c++] = (blocks[i] & 0xff);
326 } else {
327 frameSpace[c++] = 0x80;
328 frameSpace[c++] = blocks[i];
332 //set length
333 frameSpace[2] = c - 2;
334 //Add CRC
335 AddCrc(frameSpace + 2, c - 2);
338 static void TransmitFor18092_AsReader(uint8_t *frame, int len, uint32_t *timing, uint8_t power, uint8_t highspeed) {
339 uint16_t flags = FPGA_MAJOR_MODE_HF_ISO18092;
340 if (power)
341 flags |= FPGA_HF_ISO18092_FLAG_READER;
342 if (highspeed)
343 flags |= FPGA_HF_ISO18092_FLAG_424K;
345 FpgaWriteConfWord(flags);
347 uint32_t curr_transfer_time = ((MAX(felica_nexttransfertime, GetCountSspClk()) & 0xfffffff8) + 8);
349 while (GetCountSspClk() < curr_transfer_time) {};
351 felica_lasttime_prox2air_start = curr_transfer_time;
353 // preamble
354 // sending 0x00 0x00 0x00 0x00 0x00 0x00
355 uint16_t c = 0;
356 while (c < 6) {
357 // keep tx buffer in a defined state anyway.
358 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
359 AT91C_BASE_SSC->SSC_THR = 0x00;
360 c++;
363 // sending data with sync bytes
364 c = 0;
365 if (DBGLEVEL >= DBG_DEBUG) {
366 Dbprintf("Sending frame:");
367 Dbhexdump(len, frame, 0);
370 while (c < len) {
371 // Put byte into tx holding register as soon as it is ready
372 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
373 AT91C_BASE_SSC->SSC_THR = frame[c++];
377 /**/
378 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) {};
379 AT91C_BASE_SSC->SSC_THR = 0x00; //minimum delay
381 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) {};
382 AT91C_BASE_SSC->SSC_THR = 0x00; //spin
383 /**/
385 // log
386 LogTrace(
387 frame,
388 len,
389 (felica_lasttime_prox2air_start << 4) + DELAY_ARM2AIR_AS_READER,
390 ((felica_lasttime_prox2air_start + felica_lasttime_prox2air_start) << 4) + DELAY_ARM2AIR_AS_READER,
391 NULL,
392 true
395 felica_nexttransfertime = MAX(felica_nexttransfertime, felica_lasttime_prox2air_start + FELICA_REQUEST_GUARD_TIME);
398 // Wait for tag reply
399 // stop when button is pressed
400 // or return TRUE when command is captured
401 bool WaitForFelicaReply(uint16_t maxbytes) {
402 if (DBGLEVEL >= DBG_DEBUG)
403 Dbprintf("WaitForFelicaReply Start");
404 uint32_t c = 0;
405 // power, no modulation
406 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO18092 | FPGA_HF_ISO18092_FLAG_READER | FPGA_HF_ISO18092_FLAG_NOMOD);
407 FelicaFrameReset();
409 // clear RXRDY:
410 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
411 (void)b;
413 uint32_t timeout = iso18092_get_timeout();
415 for (;;) {
416 WDT_HIT();
417 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) {
418 b = (uint8_t)(AT91C_BASE_SSC->SSC_RHR);
419 Process18092Byte(b);
420 if (FelicaFrame.state == STATE_FULL) {
421 felica_nexttransfertime = MAX(felica_nexttransfertime,
422 (GetCountSspClk() & 0xfffffff8) - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER) / 16 + FELICA_FRAME_DELAY_TIME);
424 LogTrace(
425 FelicaFrame.framebytes,
426 FelicaFrame.len,
427 ((GetCountSspClk() & 0xfffffff8) << 4) - DELAY_AIR2ARM_AS_READER - timeout,
428 ((GetCountSspClk() & 0xfffffff8) << 4) - DELAY_AIR2ARM_AS_READER,
429 NULL,
430 false
432 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("All bytes received! STATE_FULL");
433 return true;
434 } else if (c++ > timeout && (FelicaFrame.state == STATE_UNSYNCD || FelicaFrame.state == STATE_TRYING_SYNC)) {
435 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Error: Timeout! STATE_UNSYNCD");
436 return false;
442 // Set up FeliCa communication (similar to iso14443a_setup)
443 // field is setup for "Sending as Reader"
444 static void iso18092_setup(uint8_t fpga_minor_mode) {
445 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Start iso18092_setup");
447 LEDsoff();
448 FpgaDownloadAndGo(FPGA_BITSTREAM_HF_FELICA);
450 // allocate command receive buffer
451 BigBuf_free();
452 BigBuf_Clear_ext(false);
454 // Initialize Demod and Uart structs
455 // DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
456 FelicaFrameinit(BigBuf_malloc(FELICA_MAX_FRAME_SIZE));
458 felica_nexttransfertime = 2 * DELAY_ARM2AIR_AS_READER;
459 iso18092_set_timeout(2120); // 106 * 20ms maximum start-up time of card
461 init_table(CRC_FELICA);
463 // connect Demodulated Signal to ADC:
464 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
466 // Set up the synchronous serial port
467 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO18092);
469 // LSB transfer. Remember to set it back to MSB with
470 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
472 // Signal field is on with the appropriate LED
473 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO18092 | fpga_minor_mode);
475 //20.4 ms generate field, start sending polling command afterwars.
476 SpinDelay(100);
478 // Start the timer
479 StartCountSspClk();
481 LED_D_ON();
484 static void felica_reset_frame_mode(void) {
485 switch_off();
486 //Resetting Frame mode (First set in fpgaloader.c)
487 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
491 //-----------------------------------------------------------------------------
492 // RAW FeliCa commands. Send out commands and store answers.
493 //-----------------------------------------------------------------------------
494 // arg0 FeliCa flags
495 // arg1 len of commandbytes
496 // d.asBytes command bytes to send
497 void felica_sendraw(PacketCommandNG *c) {
498 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("FeliCa_sendraw Enter");
500 felica_command_t param = c->oldarg[0];
501 size_t len = c->oldarg[1] & 0xffff;
502 uint8_t *cmd = c->data.asBytes;
503 uint32_t arg0;
505 felica_card_select_t card;
507 if ((param & FELICA_CONNECT))
508 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Clear trace");
509 clear_trace();
511 set_tracing(true);
512 iso18092_setup(FPGA_HF_ISO18092_FLAG_READER | FPGA_HF_ISO18092_FLAG_NOMOD);
514 if ((param & FELICA_CONNECT)) {
515 // notify client selecting status.
516 // if failed selecting, turn off antenna and quite.
517 if (!(param & FELICA_NO_SELECT)) {
518 arg0 = felica_select_card(&card);
519 reply_mix(CMD_ACK, arg0, sizeof(card.uid), 0, &card, sizeof(felica_card_select_t));
520 if (arg0 > 0) {
521 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("Error: Failed selecting card! ");
522 felica_reset_frame_mode();
523 return;
526 } else {
527 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("No card selection");
530 if ((param & FELICA_RAW)) {
532 // 2 sync, 1 len, 2crc == 5
533 uint8_t *buf = BigBuf_malloc(len + 5);
534 // add sync bits
535 buf[0] = 0xb2;
536 buf[1] = 0x4d;
537 buf[2] = len;
539 // copy command
540 memcpy(buf + 2, cmd, len);
542 if ((param & FELICA_APPEND_CRC)) {
543 // Don't append crc on empty bytearray...
544 if (len > 0) {
545 AddCrc(buf, len);
548 if (DBGLEVEL >= DBG_DEBUG) {
549 Dbprintf("Transmit Frame (no CRC shown):");
550 Dbhexdump(len, buf, 0);
551 Dbprintf("Buffer Length: %i", buf[2] + 4);
553 TransmitFor18092_AsReader(buf, buf[2] + 4, NULL, 1, 0);
554 arg0 = WaitForFelicaReply(1024);
555 if (DBGLEVEL >= DBG_DEBUG) {
556 Dbprintf("Received Frame Code: %d", arg0);
557 Dbhexdump(FelicaFrame.len, FelicaFrame.framebytes, 0);
560 uint32_t result = reply_mix(CMD_ACK, FelicaFrame.len, arg0, 0, FelicaFrame.framebytes, FelicaFrame.len);
561 if (result) {
562 Dbprintf("Reply to Client Error Code: %i", result);
565 if ((param & FELICA_NO_DISCONNECT)) {
566 Dbprintf("Disconnect");
568 if (DBGLEVEL >= DBG_DEBUG)
569 Dbprintf("FeliCa_sendraw Exit");
570 felica_reset_frame_mode();
571 return;
574 void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip) {
576 clear_trace();
577 set_tracing(true);
578 iso18092_setup(FPGA_HF_ISO18092_FLAG_NOMOD);
580 LED_D_ON();
582 int retval = PM3_SUCCESS;
583 int remFrames = (samplesToSkip) ? samplesToSkip : 0;
584 int trigger_cnt = 0;
585 uint32_t timeout = iso18092_get_timeout();
586 bool isReaderFrame = true;
588 uint8_t flip = 0;
589 uint16_t checker = 0;
590 for (;;) {
592 WDT_HIT();
594 // since simulation is a tight time critical loop,
595 // we only check for user request to end at iteration 3000, 9000.
596 if (flip == 3) {
597 if (data_available()) {
598 retval = PM3_EOPABORTED;
599 break;
601 flip = 0;
604 if (checker >= 3000) {
606 if (BUTTON_PRESS()) {
607 retval = PM3_EOPABORTED;
608 break;
610 flip++;
611 checker = 0;
613 ++checker;
615 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) {
617 uint8_t dist = (uint8_t)(AT91C_BASE_SSC->SSC_RHR);
618 Process18092Byte(dist);
620 if ((dist >= 178) && (++trigger_cnt > triggersToSkip)) {
621 Dbprintf("triggers To skip kicked %d", dist);
622 break;
624 if (FelicaFrame.state == STATE_FULL) {
625 if ((FelicaFrame.framebytes[3] % 2) == 0) {
626 isReaderFrame = true; // All Reader Frames are even and all Tag frames are odd
627 } else {
628 isReaderFrame = false;
630 remFrames--;
631 if (remFrames <= 0) {
632 Dbprintf("Stop Sniffing - samples To skip reached!");
633 break;
635 LogTrace(FelicaFrame.framebytes,
636 FelicaFrame.len,
637 ((GetCountSspClk() & 0xfffffff8) << 4) - DELAY_AIR2ARM_AS_READER - timeout,
638 ((GetCountSspClk() & 0xfffffff8) << 4) - DELAY_AIR2ARM_AS_READER,
639 NULL,
640 isReaderFrame
642 FelicaFrameReset();
646 switch_off();
647 //reset framing
648 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
650 Dbprintf("Felica sniffing done, tracelen: %i", BigBuf_get_traceLen());
651 reply_ng(CMD_HF_FELICA_SNIFF, retval, NULL, 0);
652 LED_D_OFF();
655 #define R_POLL0_LEN 0x16
656 #define R_POLL1_LEN 0x18
657 #define R_READBLK_LEN 0x21
658 //simulate NFC Tag3 card - for now only poll response works
659 // second half (4 bytes) of NDEF2 goes into nfcid2_0, first into nfcid2_1
660 void felica_sim_lite(uint8_t *uid) {
662 // prepare our 3 responses...
663 uint8_t resp_poll0[R_POLL0_LEN] = { 0xb2, 0x4d, 0x12, FELICA_POLL_ACK, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x00, 0x00, 0x00, 0x01, 0x43, 0x00, 0xb3, 0x7f};
664 uint8_t resp_poll1[R_POLL1_LEN] = { 0xb2, 0x4d, 0x14, FELICA_POLL_ACK, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x00, 0x00, 0x00, 0x01, 0x43, 0x00, 0x88, 0xb4, 0xb3, 0x7f};
665 uint8_t resp_readblk[R_READBLK_LEN] = { 0xb2, 0x4d, 0x1d, FELICA_RDBLK_ACK, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x10, 0x04, 0x01, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x23, 0xcb, 0x6e};
667 // NFC tag 3/ ISo technically. Many overlapping standards
668 DbpString("Felica Lite-S simulation start");
669 Dbprintf("NDEF2 UID: %02x %02x %02x %02x %02x %02x %02x %02x",
670 uid[0], uid[1], uid[2], uid[3], uid[4], uid[5], uid[6], uid[7]
673 // fill in blanks
674 for (uint8_t i = 0; i < 8; i++) {
675 resp_poll0[i + 4] = uid[i];
676 resp_poll1[i + 4] = uid[i];
677 resp_readblk[i + 4] = uid[i];
680 // calculate and set CRC
681 AddCrc(resp_poll0, resp_poll0[2]);
682 AddCrc(resp_poll1, resp_poll1[2]);
683 AddCrc(resp_readblk, resp_readblk[2]);
685 iso18092_setup(FPGA_HF_ISO18092_FLAG_NOMOD);
687 int retval = PM3_SUCCESS;
688 int curlen = 0;
689 uint8_t *curresp = NULL;
690 bool listenmode = true;
691 // uint32_t frtm = GetCountSspClk();
693 uint8_t flip = 0;
694 uint16_t checker = 0;
695 for (;;) {
697 WDT_HIT();
699 // since simulation is a tight time critical loop,
700 // we only check for user request to end at iteration 3000, 9000.
701 if (flip == 3) {
702 if (data_available()) {
703 retval = PM3_EOPABORTED;
704 break;
706 flip = 0;
709 if (checker >= 3000) {
711 if (BUTTON_PRESS()) {
712 retval = PM3_EOPABORTED;
713 break;
715 flip++;
716 checker = 0;
718 ++checker;
720 WDT_HIT();
722 if (listenmode) {
723 // waiting for request...
724 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) {
726 uint8_t dist = (uint8_t)(AT91C_BASE_SSC->SSC_RHR);
727 // frtm = GetCountSspClk();
728 Process18092Byte(dist);
730 if (FelicaFrame.state == STATE_FULL) {
732 if (FelicaFrame.crc_ok) {
734 if (FelicaFrame.framebytes[2] == 6 && FelicaFrame.framebytes[3] == 0) {
736 // polling... there are two types of polling we answer to
737 if (FelicaFrame.framebytes[6] == 0) {
738 curresp = resp_poll0;
739 curlen = R_POLL0_LEN;
740 listenmode = false;
742 if (FelicaFrame.framebytes[6] == 1) {
743 curresp = resp_poll1;
744 curlen = R_POLL1_LEN;
745 listenmode = true;
749 if (FelicaFrame.framebytes[2] > 5 && FelicaFrame.framebytes[3] == 0x06) {
750 // we should rebuild it depending on page size, but...
751 // Let's see first
752 curresp = resp_readblk;
753 curlen = R_READBLK_LEN;
754 listenmode = false;
756 // clear frame
757 FelicaFrameReset();
758 } else {
759 // frame invalid, clear it out to allow for the next one
760 FelicaFrameReset();
767 if (listenmode == false) {
768 // trying to answer... here to start answering immediately.
769 // this one is a bit finicky. Seems that being a bit late is better than earlier
770 // TransmitFor18092_AsReader(curresp, curlen, frtm+512, 0, 0);
771 TransmitFor18092_AsReader(curresp, curlen, NULL, 0, 0);
773 // switch back
774 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO18092 | FPGA_HF_ISO18092_FLAG_NOMOD);
776 FelicaFrameReset();
777 listenmode = true;
778 curlen = 0;
779 curresp = NULL;
783 switch_off();
785 // reset framing
786 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
788 Dbprintf("FeliCa Lite-S emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
789 reply_ng(CMD_HF_FELICALITE_SIMULATE, retval, NULL, 0);
792 #define RES_SVC_LEN 11 + 3
794 void felica_dump_lite_s(void) {
795 uint8_t ndef[8];
796 uint8_t poll[10] = { 0xb2, 0x4d, 0x06, FELICA_POLL_REQ, 0xff, 0xff, 0x00, 0x00, 0x09, 0x21};
797 uint16_t liteblks[28] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x90, 0x91, 0x92, 0xa0};
799 // setup device.
800 iso18092_setup(FPGA_HF_ISO18092_FLAG_READER | FPGA_HF_ISO18092_FLAG_NOMOD);
802 uint8_t blknum;
803 bool isOK = false;
804 uint16_t cnt = 0, cntfails = 0;
805 uint8_t *dest = BigBuf_get_addr();
807 while (!BUTTON_PRESS() && !data_available()) {
808 WDT_HIT();
809 // polling?
810 //TransmitFor18092_AsReader(poll, 10, GetCountSspClk()+512, 1, 0);
811 TransmitFor18092_AsReader(poll, 10, NULL, 1, 0);
813 if (WaitForFelicaReply(512) && FelicaFrame.framebytes[3] == FELICA_POLL_ACK) {
814 // copy 8bytes to ndef.
815 memcpy(ndef, FelicaFrame.framebytes + 4, 8);
816 // for (c=0; c < 8; c++)
817 // ndef[c] = FelicaFrame.framebytes[c+4];
819 for (blknum = 0; blknum < ARRAYLEN(liteblks);) {
820 // block to read.
821 BuildFliteRdblk(ndef, 1, &liteblks[blknum]);
823 //TransmitFor18092_AsReader(frameSpace, frameSpace[2]+4, GetCountSspClk()+512, 1, 0);
827 TransmitFor18092_AsReader(frameSpace, frameSpace[2] + 4, NULL, 1, 0);
828 // read block
829 if (WaitForFelicaReply(1024) && FelicaFrame.framebytes[3] == FELICA_RDBLK_ACK) {
831 dest[cnt++] = liteblks[blknum];
833 uint8_t *fb = FelicaFrame.framebytes;
834 dest[cnt++] = fb[12];
835 dest[cnt++] = fb[13];
837 //memcpy(dest+cnt, FelicaFrame.framebytes + 15, 16);
838 //cnt += 16;
839 for (uint8_t j = 0; j < 16; j++)
840 dest[cnt++] = fb[15 + j];
842 blknum++;
843 cntfails = 0;
845 // // print raw log.
846 // Dbprintf("LEN %u | Dump bytes count %u ", FelicaFrame.len, cnt);
847 Dbhexdump(FelicaFrame.len, FelicaFrame.framebytes + 15, 0);
848 } else {
849 cntfails++;
850 if (cntfails > 12) {
851 blknum++;
852 cntfails = 0;
857 isOK = true;
858 break;
861 switch_off();
863 //Resetting Frame mode (First set in fpgaloader.c)
864 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
866 //setting tracelen - important! it was set by buffer overflow before
867 set_tracelen(cnt);
868 reply_mix(CMD_ACK, isOK, cnt, 0, 0, 0);