fixes entering bootload messages to be less scary
[RRG-proxmark3.git] / client / src / cmdhf14b.c
blobd2785a517afa7e360015d8c24e6f985b1d9ef41f
1 //-----------------------------------------------------------------------------
2 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // See LICENSE.txt for the text of the license.
15 //-----------------------------------------------------------------------------
16 // High frequency ISO14443B commands
17 //-----------------------------------------------------------------------------
19 #include "cmdhf14b.h"
20 #include <ctype.h>
21 #include "iso14b.h"
22 #include "fileutils.h"
23 #include "cmdparser.h" // command_t
24 #include "commonutil.h" // ARRAYLEN
25 #include "comms.h" // clearCommandBuffer
26 #include "emv/emvcore.h" // TLVPrintFromBuffer
27 #include "cmdtrace.h"
28 #include "cliparser.h"
29 #include "crc16.h"
30 #include "cmdhf14a.h"
31 #include "protocols.h" // definitions of ISO14B/7816 protocol
32 #include "iso7816/apduinfo.h" // GetAPDUCodeDescription
33 #include "nfc/ndef.h" // NDEFRecordsDecodeAndPrint
34 #include "aidsearch.h"
35 #include "fileutils.h" // saveFile
36 #include "iclass_cmd.h" // picopass defines
37 #include "cmdhf.h" // handle HF plot
39 #define MAX_14B_TIMEOUT_MS (4949U)
41 // client side time out, waiting for device to ask tag.
42 #define TIMEOUT 1000
44 // client side time out, waiting for device to ask tag a APDU to answer
45 #define APDU_TIMEOUT 2000
47 // for static arrays
48 #define ST25TB_SR_BLOCK_SIZE 4
51 // SR memory sizes
52 #define SR_SIZE_512 1
53 #define SR_SIZE_4K 2
54 // ST235 memory sizes
55 #define ST25_SIZE_512 3
56 #define ST25_SIZE_2K 4
57 #define ST25_SIZE_4K 5
60 typedef struct {
61 const char *desc;
62 const char *apdu;
63 const uint8_t apdulen;
64 } transport_14b_apdu_t;
67 // iso14b apdu input frame length
68 static uint16_t apdu_frame_length = 0;
69 //static uint16_t ats_fsc[] = {16, 24, 32, 40, 48, 64, 96, 128, 256};
70 static bool apdu_in_framing_enable = true;
72 static int CmdHelp(const char *Cmd);
74 static int switch_off_field_14b(void) {
75 SetISODEPState(ISODEP_INACTIVE);
76 iso14b_raw_cmd_t packet = {
77 .flags = ISO14B_DISCONNECT,
78 .timeout = 0,
79 .rawlen = 0,
81 clearCommandBuffer();
82 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
83 return PM3_SUCCESS;
86 static int clear_trace_14b(void) {
87 iso14b_raw_cmd_t packet = {
88 .flags = ISO14B_CLEARTRACE,
89 .timeout = 0,
90 .rawlen = 0,
92 clearCommandBuffer();
93 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
94 return PM3_SUCCESS;
97 static void hf14b_aid_search(bool verbose) {
99 json_t *root = AIDSearchInit(verbose);
100 if (root == NULL) {
101 switch_off_field_14b();
102 return;
105 PrintAndLogEx(INFO, "-------------------- " _CYAN_("AID Search") " --------------------");
107 bool found = false;
108 bool leave_signal_on = true;
109 bool activate_field = true;
110 for (size_t elmindx = 0; elmindx < json_array_size(root); elmindx++) {
112 if (kbd_enter_pressed()) {
113 break;
116 json_t *data = AIDSearchGetElm(root, elmindx);
117 uint8_t vaid[200] = {0};
118 int vaidlen = 0;
120 if ((AIDGetFromElm(data, vaid, sizeof(vaid), &vaidlen) == false) || (vaidlen == 0)) {
121 continue;
125 // COMPUTE APDU
126 uint8_t apdu_data[PM3_CMD_DATA_SIZE] = {0};
127 int apdu_len = 0;
128 sAPDU_t apdu = (sAPDU_t) {0x00, 0xa4, 0x04, 0x00, vaidlen, vaid};
130 if (APDUEncodeS(&apdu, false, 0x00, apdu_data, &apdu_len)) {
131 PrintAndLogEx(ERR, "APDU encoding error");
132 return;
135 PrintAndLogEx(DEBUG, ">>>> %s", sprint_hex(apdu_data, apdu_len));
137 int resultlen = 0;
138 uint8_t result[1024] = {0};
139 int res = exchange_14b_apdu(apdu_data, apdu_len, activate_field, leave_signal_on, result, sizeof(result), &resultlen, -1);
140 activate_field = false;
141 if (res) {
142 continue;
145 uint16_t sw = get_sw(result, resultlen);
147 uint8_t dfname[200] = {0};
148 size_t dfnamelen = 0;
149 if (resultlen > 3) {
150 struct tlvdb *tlv = tlvdb_parse_multi(result, resultlen);
151 if (tlv) {
152 // 0x84 Dedicated File (DF) Name
153 const struct tlv *dfnametlv = tlvdb_get_tlv(tlvdb_find_full(tlv, 0x84));
154 if (dfnametlv) {
155 dfnamelen = dfnametlv->len;
156 memcpy(dfname, dfnametlv->value, dfnamelen);
158 tlvdb_free(tlv);
162 if (sw == ISO7816_OK || sw == ISO7816_INVALID_DF || sw == ISO7816_FILE_TERMINATED) {
163 if (sw == ISO7816_OK) {
164 if (verbose) {
165 PrintAndLogEx(SUCCESS, "Application ( " _GREEN_("ok") " )");
167 } else {
168 if (verbose) {
169 PrintAndLogEx(WARNING, "Application ( " _RED_("blocked") " )");
173 PrintAIDDescriptionBuf(root, vaid, vaidlen, verbose);
175 if (dfnamelen) {
176 if (dfnamelen == vaidlen) {
177 if (memcmp(dfname, vaid, vaidlen) == 0) {
178 if (verbose) {
179 PrintAndLogEx(INFO, "(DF) Name found and equal to AID");
181 } else {
182 PrintAndLogEx(INFO, "(DF) Name not equal to AID: %s :", sprint_hex(dfname, dfnamelen));
183 PrintAIDDescriptionBuf(root, dfname, dfnamelen, verbose);
185 } else {
186 PrintAndLogEx(INFO, "(DF) Name not equal to AID: %s :", sprint_hex(dfname, dfnamelen));
187 PrintAIDDescriptionBuf(root, dfname, dfnamelen, verbose);
189 } else {
190 if (verbose) {
191 PrintAndLogEx(INFO, "(DF) Name not found");
195 if (verbose) {
196 PrintAndLogEx(SUCCESS, "----------------------------------------------------");
198 found = true;
201 switch_off_field_14b();
202 if (verbose == false && found) {
203 PrintAndLogEx(INFO, "----------------------------------------------------");
207 static bool wait_14b_response(bool only_first, uint8_t *datalen, uint8_t *data) {
209 /* We have scenarios.
210 A - only select
211 B - only normal respose
212 C - both select and response
215 PacketResponseNG resp;
216 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
217 PrintAndLogEx(WARNING, "timeout while waiting for reply (first)");
218 return false;
221 if (resp.status == PM3_ETEAROFF) {
222 PrintAndLogEx(INFO, "Writing tear off triggered");
223 return true;
226 if (resp.status != PM3_SUCCESS) {
227 PrintAndLogEx(DEBUG, "first response failed... %d", resp.status);
228 return false;
231 // treat first reponse as same.
232 if (only_first) {
234 if (datalen) {
235 *datalen = resp.length;
238 if (data) {
239 memcpy(data, resp.data.asBytes, resp.length);
241 return true;
244 // wait a second time.
245 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
246 PrintAndLogEx(WARNING, "timeout while waiting for reply");
247 return false;
250 if (resp.status != PM3_SUCCESS) {
251 PrintAndLogEx(DEBUG, "second response failed... %d", resp.status);
252 return false;
255 if (datalen) {
256 *datalen = resp.length;
258 if (data) {
259 memcpy(data, resp.data.asBytes, resp.length);
262 return true;
265 static bool wait_cmd_14b(bool verbose, bool is_select, uint32_t timeout) {
267 PacketResponseNG resp;
268 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, MAX(TIMEOUT, timeout)) == false) {
269 PrintAndLogEx(WARNING, "timeout while waiting for reply");
270 return false;
273 if (resp.status == PM3_ETEAROFF) {
274 PrintAndLogEx(INFO, "Writing tear off triggered");
275 return true;
278 if (is_select) {
279 if (resp.status == PM3_ECARDEXCHANGE) {
280 PrintAndLogEx(INFO, "no response from tag");
281 return false;
283 if (resp.status != PM3_SUCCESS) {
284 if (verbose) {
285 PrintAndLogEx(INFO, "failed status value... %d", resp.status);
287 return false;
291 uint16_t len = resp.length;
292 uint8_t *data = resp.data.asBytes;
294 // handle select responses OK
295 if (is_select && verbose) {
296 PrintAndLogEx(SUCCESS, "received " _YELLOW_("%u") " bytes", len);
297 PrintAndLogEx(SUCCESS, "%s", sprint_hex(data, len));
298 return true;
301 // handle raw bytes responses
302 if (verbose) {
303 if (len >= 3) {
304 bool crc = check_crc(CRC_14443_B, data, len);
306 PrintAndLogEx(SUCCESS, "received " _YELLOW_("%u") " bytes", len);
307 PrintAndLogEx(SUCCESS, "%s[ " _YELLOW_("%02X %02X") " ] ( %s )",
308 sprint_hex(data, len - 2),
309 data[len - 2],
310 data[len - 1],
311 (crc) ? _GREEN_("ok") : _RED_("fail")
313 } else if (len == 0) {
314 PrintAndLogEx(INFO, "no response from tag");
315 } else {
316 PrintAndLogEx(SUCCESS, "%s", sprint_hex(data, len));
319 return true;
322 static bool get_14b_UID(uint8_t *d, iso14b_type_t *found_type) {
324 // sanity checks
325 if (d == NULL || found_type == NULL) {
326 return false;
329 *found_type = ISO14B_NONE;
331 iso14b_raw_cmd_t packet = {
332 .flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT),
333 .timeout = 0,
334 .rawlen = 0,
337 PacketResponseNG resp;
338 clearCommandBuffer();
339 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
340 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT)) {
342 if (resp.status == PM3_SUCCESS) {
343 memcpy(d, resp.data.asBytes, sizeof(iso14b_card_select_t));
345 iso14b_card_select_t *card = (iso14b_card_select_t *)d;
346 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
347 if (memcmp(card->uid, empty, card->uidlen) == 0) {
348 return false;
350 *found_type = ISO14B_SR;
351 return true;
355 // test 14b standard
356 packet.flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT);
358 clearCommandBuffer();
359 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
360 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT)) {
362 if (resp.status == PM3_SUCCESS) {
363 memcpy(d, resp.data.asBytes, sizeof(iso14b_card_select_t));
364 *found_type = ISO14B_STANDARD;
365 return true;
369 // test CT
370 packet.flags = (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_DISCONNECT);
371 clearCommandBuffer();
372 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
373 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT)) {
375 if (resp.status == PM3_SUCCESS) {
376 memcpy(d, resp.data.asBytes, sizeof(iso14b_cts_card_select_t));
377 *found_type = ISO14B_CT;
378 return true;
382 PrintAndLogEx(WARNING, "timeout while waiting for reply");
383 return false;
386 /* extract uid from filename
387 * filename must match '^hf-14b-[0-9A-F]{16}'
389 uint8_t *get_uid_from_filename(const char *filename) {
391 static uint8_t uid[8];
392 memset(uid, 0, 8);
394 if (strlen(filename) < 23) {
395 PrintAndLogEx(ERR, "can't get uid from filename '%s'. Expected format is hf-14b-<uid>...", filename);
396 return uid;
399 char *found = strstr(filename, "hf-14b-");
400 if (found == NULL) {
401 PrintAndLogEx(ERR, "can't get uid from filename '%s'. Expected format is hf-14b-<uid>...", filename);
402 return uid;
405 // extract uid part from filename
406 char uidinhex[17] = {0};
407 strncpy(uidinhex, found + 7, 16);
409 uidinhex[16] = '\0';
410 int len = hex_to_bytes(uidinhex, uid, 8);
411 if (len == 8) {
412 return SwapEndian64(uid, 8, 8);
413 } else {
414 PrintAndLogEx(ERR, "get_uid_from_filename failed: hex_to_bytes returned %d", len);
415 memset(uid, 0, 8);
417 return uid;
420 // print full atqb info
421 // bytes
422 // 0,1,2,3 = application data
423 // 4 = bit rate capacity
424 // 5 = max frame size / -4 info
425 // 6 = FWI / Coding options
426 static int print_atqb_resp(uint8_t *data, uint8_t cid) {
427 //PrintAndLogEx(SUCCESS, " UID: %s", sprint_hex(data+1,4));
428 PrintAndLogEx(SUCCESS, " App Data: %s", sprint_hex(data, 4));
429 PrintAndLogEx(SUCCESS, " Protocol: %s", sprint_hex(data + 4, 3));
430 uint8_t BitRate = data[4];
431 if (!BitRate) PrintAndLogEx(SUCCESS, " Bit Rate: 106 kbit/s only PICC <-> PCD");
432 if (BitRate & 0x10) PrintAndLogEx(SUCCESS, " Bit Rate: 212 kbit/s PICC -> PCD supported");
433 if (BitRate & 0x20) PrintAndLogEx(SUCCESS, " Bit Rate: 424 kbit/s PICC -> PCD supported");
434 if (BitRate & 0x40) PrintAndLogEx(SUCCESS, " Bit Rate: 847 kbit/s PICC -> PCD supported");
435 if (BitRate & 0x01) PrintAndLogEx(SUCCESS, " Bit Rate: 212 kbit/s PICC <- PCD supported");
436 if (BitRate & 0x02) PrintAndLogEx(SUCCESS, " Bit Rate: 424 kbit/s PICC <- PCD supported");
437 if (BitRate & 0x04) PrintAndLogEx(SUCCESS, " Bit Rate: 847 kbit/s PICC <- PCD supported");
438 if (BitRate & 0x80) PrintAndLogEx(SUCCESS, " Same bit rate <-> required");
440 uint16_t maxFrame = data[5] >> 4;
441 if (maxFrame < 5) maxFrame = 8 * maxFrame + 16;
442 else if (maxFrame == 5) maxFrame = 64;
443 else if (maxFrame == 6) maxFrame = 96;
444 else if (maxFrame == 7) maxFrame = 128;
445 else if (maxFrame == 8) maxFrame = 256;
446 else maxFrame = 257;
448 PrintAndLogEx(SUCCESS, "Max Frame Size: %u%s bytes", maxFrame, (maxFrame == 257) ? "+ RFU" : "");
450 uint8_t protocolT = data[5] & 0xF;
451 PrintAndLogEx(SUCCESS, " Protocol Type: Protocol is %scompliant with ISO/IEC 14443-4", (protocolT) ? "" : "not ");
453 uint8_t fwt = data[6] >> 4;
454 if (fwt < 15) {
455 uint32_t etus = (32 << fwt);
456 uint32_t fwt_time = (302 << fwt);
457 PrintAndLogEx(SUCCESS, "Frame Wait Integer: %u - %u ETUs | %u us", fwt, etus, fwt_time);
458 } else {
459 PrintAndLogEx(SUCCESS, "Frame Wait Integer: %u - RFU", fwt);
462 PrintAndLogEx(SUCCESS, " App Data Code: Application is %s", (data[6] & 4) ? "Standard" : "Proprietary");
463 PrintAndLogEx(SUCCESS, " Frame Options: NAD is %ssupported", (data[6] & 2) ? "" : "not ");
464 PrintAndLogEx(SUCCESS, " Frame Options: CID is %ssupported", (data[6] & 1) ? "" : "not ");
465 PrintAndLogEx(SUCCESS, "Tag :");
466 PrintAndLogEx(SUCCESS, " Max Buf Length: %u (MBLI) %s", cid >> 4, (cid & 0xF0) ? "" : "chained frames not supported");
467 PrintAndLogEx(SUCCESS, " CID : %u", cid & 0x0f);
468 return PM3_SUCCESS;
471 // get SRx chip model (from UID) // from ST Microelectronics
472 static const char *get_st_chip_model(uint8_t id) {
473 switch (id) {
474 case 0x0:
475 return "SRIX4K (Special)";
476 case 0x2:
477 return "SR176";
478 case 0x3:
479 return "SRIX4K";
480 case 0x4:
481 return "SRIX512";
482 case 0x6:
483 return "SRI512";
484 case 0x7:
485 return "SRI4K";
486 case 0xC:
487 return "SRT512";
488 default :
489 return "";
494 static const char *get_st25_chip_model(uint8_t id) {
495 switch (id) {
496 case 0x1B:
497 return "ST25TB512-AC";
498 case 0x33:
499 return "ST25TB512-AT";
500 case 0x3F:
501 return "ST25TB02K";
502 case 0x1F:
503 return "ST25TB04K";
504 default:
505 return "";
510 #define ST_LOCK_INFO_EMPTY " "
511 static const char *get_st_lock_info(uint8_t model, const uint8_t *lockbytes, uint8_t blk) {
512 if (blk > 15) {
513 return ST_LOCK_INFO_EMPTY;
516 uint8_t mask = 0;
517 switch (model) {
518 case 0x0: // SRIX4K special
519 case 0x3: // SRIx4K
520 case 0x7: { // SRI4K
521 //only need data[3]
522 switch (blk) {
523 case 7:
524 case 8:
525 mask = 0x01;
526 break;
527 case 9:
528 mask = 0x02;
529 break;
530 case 10:
531 mask = 0x04;
532 break;
533 case 11:
534 mask = 0x08;
535 break;
536 case 12:
537 mask = 0x10;
538 break;
539 case 13:
540 mask = 0x20;
541 break;
542 case 14:
543 mask = 0x40;
544 break;
545 case 15:
546 mask = 0x80;
547 break;
548 default:
549 return ST_LOCK_INFO_EMPTY;
551 if ((lockbytes[1] & mask) == 0) {
552 return _RED_("1");
554 return ST_LOCK_INFO_EMPTY;
556 case 0x4: // SRIX512
557 case 0x6: // SRI512
558 case 0xC: { // SRT512
559 //need data[2] and data[3]
560 uint8_t b = 1;
561 switch (blk) {
562 case 0:
563 mask = 0x01;
564 break;
565 case 1:
566 mask = 0x02;
567 break;
568 case 2:
569 mask = 0x04;
570 break;
571 case 3:
572 mask = 0x08;
573 break;
574 case 4:
575 mask = 0x10;
576 break;
577 case 5:
578 mask = 0x20;
579 break;
580 case 6:
581 mask = 0x40;
582 break;
583 case 7:
584 mask = 0x80;
585 break;
586 case 8:
587 mask = 0x01;
588 b = 0;
589 break;
590 case 9:
591 mask = 0x02;
592 b = 0;
593 break;
594 case 10:
595 mask = 0x04;
596 b = 0;
597 break;
598 case 11:
599 mask = 0x08;
600 b = 0;
601 break;
602 case 12:
603 mask = 0x10;
604 b = 0;
605 break;
606 case 13:
607 mask = 0x20;
608 b = 0;
609 break;
610 case 14:
611 mask = 0x40;
612 b = 0;
613 break;
614 case 15:
615 mask = 0x80;
616 b = 0;
617 break;
619 if ((lockbytes[b] & mask) == 0) {
620 return _RED_("1");
622 return ST_LOCK_INFO_EMPTY;
624 case 0x2: { // SR176
625 //need data[2]
626 switch (blk) {
627 case 0:
628 case 1:
629 mask = 0x1;
630 break;
631 case 2:
632 case 3:
633 mask = 0x2;
634 break;
635 case 4:
636 case 5:
637 mask = 0x4;
638 break;
639 case 6:
640 case 7:
641 mask = 0x8;
642 break;
643 case 8:
644 case 9:
645 mask = 0x10;
646 break;
647 case 10:
648 case 11:
649 mask = 0x20;
650 break;
651 case 12:
652 case 13:
653 mask = 0x40;
654 break;
655 case 14:
656 case 15:
657 mask = 0x80;
658 break;
660 // iceman: this is opposite! need sample to test with.
661 if ((lockbytes[0] & mask)) {
662 return _RED_("1");
664 return ST_LOCK_INFO_EMPTY;
666 default:
667 break;
669 return ST_LOCK_INFO_EMPTY;
672 static uint8_t get_st_chipid(const uint8_t *uid) {
673 return uid[5] >> 2;
677 static uint8_t get_st25_chipid(const uint8_t *uid) {
678 return uid[5];
682 static uint8_t get_st_cardsize(const uint8_t *uid) {
683 uint8_t chipid = get_st_chipid(uid);
684 switch (chipid) {
685 case 0x0:
686 case 0x3:
687 case 0x7:
688 return SR_SIZE_4K;
689 case 0x4:
690 case 0x6:
691 case 0xC:
692 return SR_SIZE_512;
693 default:
694 return 0;
700 static uint8_t get_st25_cardsize(const uint8_t *uid) {
701 uint8_t chipid = get_st25_chipid(uid);
702 switch (chipid) {
703 case 0x1B:
704 case 0x33:
705 return ST25_SIZE_512;
706 case 0x1F:
707 return ST25_SIZE_4K;
708 case 0x3F:
709 return ST25_SIZE_2K;
710 default:
711 return 0;
716 // print UID info from SRx chips (ST Microelectronics)
717 static void print_st_general_info(uint8_t *data, uint8_t len) {
718 //uid = first 8 bytes in data
719 uint8_t mfgid = data[6];
720 uint8_t chipid = get_st_chipid(data);
721 PrintAndLogEx(NORMAL, "");
722 PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(SwapEndian64(data, 8, 8), len));
723 PrintAndLogEx(SUCCESS, " MFG: %02X, " _YELLOW_("%s"), mfgid, getTagInfo(mfgid));
724 PrintAndLogEx(SUCCESS, "Chip: %02X, " _YELLOW_("%s"), chipid, get_st_chip_model(chipid));
727 // print UID info from ASK CT chips
728 static void print_ct_general_info(void *vcard) {
729 iso14b_cts_card_select_t card;
730 memcpy(&card, (iso14b_cts_card_select_t *)vcard, sizeof(iso14b_cts_card_select_t));
732 uint32_t uid32 = MemLeToUint4byte(card.uid);
733 PrintAndLogEx(NORMAL, "");
734 PrintAndLogEx(SUCCESS, "ASK C-Ticket");
735 PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s") " ( " _YELLOW_("%010u") " )", sprint_hex(card.uid, sizeof(card.uid)), uid32);
736 PrintAndLogEx(SUCCESS, " Product Code: %02X", card.pc);
737 PrintAndLogEx(SUCCESS, " Facility Code: %02X", card.fc);
738 PrintAndLogEx(NORMAL, "");
741 static void print_hdr(void) {
742 PrintAndLogEx(NORMAL, "");
743 PrintAndLogEx(INFO, " block# | data |lck| ascii");
744 PrintAndLogEx(INFO, "---------+-------------+---+------");
747 static void print_footer(void) {
748 PrintAndLogEx(INFO, "---------+-------------+---+------");
749 PrintAndLogEx(NORMAL, "");
753 static void print_ct_blocks(uint8_t *data, size_t len) {
755 size_t blocks = len / ST25TB_SR_BLOCK_SIZE;
757 print_hdr();
759 for (int i = 0; i <= blocks; i++) {
760 PrintAndLogEx(INFO,
761 "%3d/0x%02X | %s | %s | %s",
764 sprint_hex(data + (i * 4), 4),
765 " ",
766 sprint_ascii(data + (i * 4), 4)
769 print_footer();
773 static void print_sr_blocks(uint8_t *data, size_t len, const uint8_t *uid, bool dense_output) {
775 size_t blocks = (len / ST25TB_SR_BLOCK_SIZE) - 1 ;
776 uint8_t *systemblock = data + blocks * ST25TB_SR_BLOCK_SIZE ;
777 uint8_t chipid = get_st_chipid(uid);
779 PrintAndLogEx(NORMAL, "");
780 PrintAndLogEx(INFO, "-------- " _CYAN_("%s tag memory") " ---------", get_st_chip_model(chipid));
781 PrintAndLogEx(DEBUG, "systemblock... " _YELLOW_("%s"), sprint_hex(systemblock, ST25TB_SR_BLOCK_SIZE));
782 PrintAndLogEx(DEBUG, " otp lock... " _YELLOW_("%02x %02x"), *systemblock, *(systemblock + 1));
784 print_hdr();
786 bool in_repeated_block = false;
789 for (int i = 0; i < blocks; i++) {
791 // suppress repeating blocks, truncate as such that the first and last block with the same data is shown
792 // but the blocks in between are replaced with a single line of "......" if dense_output is enabled
793 uint8_t *blk = data + (i * ST25TB_SR_BLOCK_SIZE);
794 if (dense_output &&
795 (i > 3) &&
796 (i < (blocks - 1)) &&
797 (in_repeated_block == false) &&
798 (memcmp(blk, blk - ST25TB_SR_BLOCK_SIZE, ST25TB_SR_BLOCK_SIZE) == 0) &&
799 (memcmp(blk, blk + ST25TB_SR_BLOCK_SIZE, ST25TB_SR_BLOCK_SIZE) == 0) &&
800 (memcmp(blk, blk + (ST25TB_SR_BLOCK_SIZE * 2), ST25TB_SR_BLOCK_SIZE) == 0)
802 // we're in a user block that isn't the first user block nor last two user blocks,
803 // and the current block data is the same as the previous and next two block
804 in_repeated_block = true;
805 PrintAndLogEx(INFO, " ......");
806 } else if (in_repeated_block &&
807 (memcmp(blk, blk + ST25TB_SR_BLOCK_SIZE, ST25TB_SR_BLOCK_SIZE) || i == blocks)
809 // in a repeating block, but the next block doesn't match anymore, or we're at the end block
810 in_repeated_block = false;
813 if (in_repeated_block == false) {
814 PrintAndLogEx(INFO,
815 "%3d/0x%02X | %s| %s | %s",
818 sprint_hex(data + (i * ST25TB_SR_BLOCK_SIZE), ST25TB_SR_BLOCK_SIZE),
819 get_st_lock_info(chipid, systemblock, i),
820 sprint_ascii(data + (i * ST25TB_SR_BLOCK_SIZE), ST25TB_SR_BLOCK_SIZE)
825 PrintAndLogEx(INFO,
826 "%3d/0x%02X | %s| %s | %s",
827 0xFF,
828 0xFF,
829 sprint_hex(systemblock, ST25TB_SR_BLOCK_SIZE),
830 get_st_lock_info(chipid, systemblock, 0xFF),
831 sprint_ascii(systemblock, ST25TB_SR_BLOCK_SIZE)
834 print_footer();
837 // iceman, calypso?
838 // 05 00 00 = find one tag in field
839 // 1d xx xx xx xx 00 08 01 00 = attrib xx=UID (resp 10 [f9 e0])
840 // 0200a40400 (resp 02 67 00 [29 5b])
841 // 0200a4040c07a0000002480300 (resp 02 67 00 [29 5b])
842 // 0200a4040c07a0000002480200 (resp 02 67 00 [29 5b])
843 // 0200a4040006a0000000010100 (resp 02 6a 82 [4b 4c])
844 // 0200a4040c09d27600002545500200 (resp 02 67 00 [29 5b])
845 // 0200a404000cd2760001354b414e4d30310000 (resp 02 6a 82 [4b 4c])
846 // 0200a404000ca000000063504b43532d313500 (resp 02 6a 82 [4b 4c])
847 // 0200a4040010a000000018300301000000000000000000 (resp 02 6a 82 [4b 4c])
849 static int CmdHF14BList(const char *Cmd) {
850 return CmdTraceListAlias(Cmd, "hf 14b", "14b -c");
853 static int CmdHF14BSim(const char *Cmd) {
855 CLIParserContext *ctx;
856 CLIParserInit(&ctx, "hf 14b sim",
857 "Simulate a ISO/IEC 14443 type B tag with 4 byte UID / PUPI",
858 "hf 14b sim -u 11AA33BB"
861 void *argtable[] = {
862 arg_param_begin,
863 arg_str1("u", "uid", "hex", "4byte UID/PUPI"),
864 arg_param_end
866 CLIExecWithReturn(ctx, Cmd, argtable, false);
868 uint8_t pupi[4];
869 int n = 0;
870 int res = CLIParamHexToBuf(arg_get_str(ctx, 1), pupi, sizeof(pupi), &n);
871 CLIParserFree(ctx);
873 if (res) {
874 PrintAndLogEx(FAILED, "failed to read pupi");
875 return PM3_EINVARG;
878 PrintAndLogEx(INFO, "Simulate with PUPI : " _GREEN_("%s"), sprint_hex_inrow(pupi, sizeof(pupi)));
879 PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " to abort simulation");
880 clearCommandBuffer();
881 SendCommandNG(CMD_HF_ISO14443B_SIMULATE, pupi, sizeof(pupi));
882 return PM3_SUCCESS;
885 static int CmdHF14BSniff(const char *Cmd) {
887 CLIParserContext *ctx;
888 CLIParserInit(&ctx, "hf 14b sniff",
889 "Sniff the communication between reader and tag.\n"
890 "Use `hf 14b list` to view collected data.",
891 "hf 14b sniff"
894 void *argtable[] = {
895 arg_param_begin,
896 arg_param_end
898 CLIExecWithReturn(ctx, Cmd, argtable, true);
899 CLIParserFree(ctx);
901 PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " to abort sniffing");
903 PacketResponseNG resp;
904 clearCommandBuffer();
905 SendCommandNG(CMD_HF_ISO14443B_SNIFF, NULL, 0);
906 WaitForResponse(CMD_HF_ISO14443B_SNIFF, &resp);
907 PrintAndLogEx(HINT, "Try `" _YELLOW_("hf 14b list") "` to view captured tracelog");
908 PrintAndLogEx(HINT, "Try `" _YELLOW_("trace save -h") "` to save tracelog for later analysing");
909 return PM3_SUCCESS;
912 static int CmdHF14BRaw(const char *Cmd) {
913 CLIParserContext *ctx;
914 CLIParserInit(&ctx, "hf 14b raw",
915 "Sends raw bytes to card. Activates field by default",
916 "hf 14b raw -cks --data 0200a40400 -> standard select, apdu 0200a4000 (7816)\n"
917 "hf 14b raw -ck --sr --data 0200a40400 -> SRx select\n"
918 "hf 14b raw -ck --cts --data 0200a40400 -> C-ticket select\n"
921 void *argtable[] = {
922 arg_param_begin,
923 arg_lit0("a", NULL, "active signal field ON without select"),
924 arg_lit0("c", "crc", "calculate and append CRC"),
925 arg_lit0("k", "keep", "leave the signal field ON after receive response"),
927 arg_str0("d", "data", "<hex>", "data, bytes to send"),
928 arg_lit0("r", NULL, "do not read response from card"),
929 arg_int0("t", "timeout", "<dec>", "timeout in ms"),
931 arg_lit0("s", "std", "use ISO14B select"),
932 arg_lit0(NULL, "sr", "use SRx ST select"),
933 arg_lit0(NULL, "cts", "use ASK C-ticket select"),
934 arg_lit0(NULL, "xrx", "use Fuji/Xerox select"),
935 arg_lit0(NULL, "pico", "use Picopass select"),
937 arg_lit0("v", "verbose", "verbose output"),
938 arg_param_end
940 CLIExecWithReturn(ctx, Cmd, argtable, false);
942 bool activate_field = arg_get_lit(ctx, 1);
943 bool add_crc = arg_get_lit(ctx, 2);
944 bool keep_field_on = arg_get_lit(ctx, 3);
946 uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
947 int datalen = 0;
948 CLIParamHexToBuf(arg_get_str(ctx, 4), data, sizeof(data), &datalen);
950 bool read_reply = (arg_get_lit(ctx, 5) == false);
951 int user_timeout = arg_get_int_def(ctx, 6, -1);
952 bool select_std = arg_get_lit(ctx, 7);
953 bool select_sr = arg_get_lit(ctx, 8);
954 bool select_cts = arg_get_lit(ctx, 9);
955 bool select_xrx = arg_get_lit(ctx, 10);
956 bool select_pico = arg_get_lit(ctx, 11);
957 bool verbose = arg_get_lit(ctx, 12);
958 CLIParserFree(ctx);
960 // FLAGS for device side
961 uint32_t flags = 0;
963 if (activate_field) {
964 flags |= ISO14B_CONNECT;
967 if (add_crc) {
968 flags |= ISO14B_APPEND_CRC;
971 if (select_std) {
972 flags |= (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_CLEARTRACE);
973 if (verbose) {
974 PrintAndLogEx(INFO, "using ISO14443-B select");
976 } else if (select_sr) {
977 flags |= (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_CLEARTRACE);
978 if (verbose) {
979 PrintAndLogEx(INFO, "using ST/SRx select");
981 } else if (select_cts) {
982 flags |= (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_CLEARTRACE);
983 if (verbose) {
984 PrintAndLogEx(INFO, "using ASK/C-ticket select");
986 } else if (select_xrx) {
987 flags |= (ISO14B_CONNECT | ISO14B_SELECT_XRX | ISO14B_CLEARTRACE);
988 if (verbose) {
989 PrintAndLogEx(INFO, "using Fuji/Xerox select");
991 } else if (select_pico) {
992 flags |= (ISO14B_CONNECT | ISO14B_SELECT_PICOPASS | ISO14B_CLEARTRACE);
993 if (verbose) {
994 PrintAndLogEx(INFO, "using Picopass select");
998 uint32_t time_wait = 0;
999 if (user_timeout > 0) {
1001 flags |= ISO14B_SET_TIMEOUT;
1003 if (user_timeout > MAX_14B_TIMEOUT_MS) {
1004 user_timeout = MAX_14B_TIMEOUT_MS;
1005 PrintAndLogEx(INFO, "set timeout to 4.9 seconds. The max we can wait for response");
1008 // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us)
1009 time_wait = (uint32_t)((13560 / 128) * user_timeout);
1010 if (verbose)
1011 PrintAndLogEx(INFO, " new raw timeout : %u ETU ( %u ms )", time_wait, user_timeout);
1014 if (keep_field_on == false) {
1015 flags |= ISO14B_DISCONNECT;
1018 if (datalen > 0) {
1019 flags |= ISO14B_RAW;
1022 // Max buffer is PM3_CMD_DATA_SIZE
1023 datalen = (datalen > PM3_CMD_DATA_SIZE) ? PM3_CMD_DATA_SIZE : datalen;
1025 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + datalen);
1026 if (packet == NULL) {
1027 PrintAndLogEx(FAILED, "failed to allocate memory");
1028 return PM3_EMALLOC;
1031 packet->flags = flags;
1032 packet->timeout = time_wait;
1033 packet->rawlen = datalen;
1034 memcpy(packet->raw, data, datalen);
1036 clearCommandBuffer();
1037 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1038 free(packet);
1040 if (read_reply == false) {
1041 clearCommandBuffer();
1042 return PM3_SUCCESS;
1045 bool success = true;
1047 // Select, device will send back iso14b_card_select_t, don't print it.
1048 if (select_std) {
1049 success = wait_cmd_14b(verbose, true, user_timeout);
1050 if (verbose && success) {
1051 PrintAndLogEx(SUCCESS, "Got response for standard select");
1055 if (select_sr) {
1056 success = wait_cmd_14b(verbose, true, user_timeout);
1057 if (verbose && success) {
1058 PrintAndLogEx(SUCCESS, "Got response for ST/SRx select");
1062 if (select_cts) {
1063 success = wait_cmd_14b(verbose, true, user_timeout);
1064 if (verbose && success) {
1065 PrintAndLogEx(SUCCESS, "Got response for ASK/C-ticket select");
1069 if (select_xrx) {
1070 success = wait_cmd_14b(verbose, true, user_timeout);
1071 if (verbose && success) {
1072 PrintAndLogEx(SUCCESS, "Got response for Fuji/Xerox select");
1076 if (select_pico) {
1077 success = wait_cmd_14b(verbose, true, user_timeout);
1078 if (verbose && success) {
1079 PrintAndLogEx(SUCCESS, "Got response for Picopass select");
1083 // get back response from the raw bytes you sent.
1084 if (success && datalen > 0) {
1085 wait_cmd_14b(true, false, user_timeout);
1088 return PM3_SUCCESS;
1091 // 14b get and print Full Info (as much as we know)
1092 static bool HF14B_Std_Info(bool verbose, bool do_aid_search) {
1093 // 14b get and print UID only (general info)
1094 iso14b_raw_cmd_t packet = {
1095 .flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT),
1096 .timeout = 0,
1097 .rawlen = 0,
1100 clearCommandBuffer();
1101 PacketResponseNG resp;
1102 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1103 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1104 if (verbose) {
1105 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1107 switch_off_field_14b();
1108 return false;
1111 switch (resp.status) {
1112 case PM3_SUCCESS: {
1114 iso14b_card_select_t card;
1115 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1117 PrintAndLogEx(NORMAL, "");
1118 PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------");
1119 PrintAndLogEx(SUCCESS, " UID : " _GREEN_("%s"), sprint_hex(card.uid, card.uidlen));
1120 PrintAndLogEx(SUCCESS, " ATQB : %s", sprint_hex(card.atqb, sizeof(card.atqb)));
1121 PrintAndLogEx(SUCCESS, " CHIPID : %02X", card.chipid);
1122 print_atqb_resp(card.atqb, card.cid);
1124 if (do_aid_search) {
1125 hf14b_aid_search(verbose);
1128 return true;
1130 case PM3_ELENGTH:
1131 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 STD ATTRIB fail");
1132 break;
1133 case PM3_ECRC:
1134 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 STD CRC fail");
1135 break;
1136 default:
1137 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b STD select failed");
1138 break;
1141 return false;
1144 // SRx get and print full info (needs more info...)
1145 static bool HF14B_ST_Info(bool verbose, bool do_aid_search) {
1147 iso14b_raw_cmd_t packet = {
1148 .flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT),
1149 .timeout = 0,
1150 .rawlen = 0,
1153 clearCommandBuffer();
1154 PacketResponseNG resp;
1155 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1156 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1157 if (verbose) {
1158 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1160 return false;
1163 if (resp.status != PM3_SUCCESS) {
1164 return false;
1167 iso14b_card_select_t card;
1168 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1170 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1171 if ((card.uidlen != 8) || (memcmp(card.uid, empty, card.uidlen) == 0)) {
1172 return false;
1175 print_st_general_info(card.uid, card.uidlen);
1177 if (do_aid_search) {
1178 hf14b_aid_search(verbose);
1180 return true;
1183 // menu command to get and print all info known about any known 14b tag
1184 static int CmdHF14Binfo(const char *Cmd) {
1185 CLIParserContext *ctx;
1186 CLIParserInit(&ctx, "hf 14b info",
1187 "Tag information for ISO/IEC 14443 type B based tags",
1188 "hf 14b info\n"
1191 void *argtable[] = {
1192 arg_param_begin,
1193 arg_lit0("s", "aidsearch", "checks if AIDs from aidlist.json is present on the card and prints information about found AIDs"),
1194 arg_lit0("v", "verbose", "verbose output"),
1195 arg_param_end
1197 CLIExecWithReturn(ctx, Cmd, argtable, true);
1198 bool do_aid_search = arg_get_lit(ctx, 1);
1199 bool verbose = arg_get_lit(ctx, 2);
1200 CLIParserFree(ctx);
1201 return infoHF14B(verbose, do_aid_search);
1204 // #define ISO14443B_READ_BLK 0x08
1205 // #define ISO14443B_WRITE_BLK 0x09
1207 static int read_sr_block(uint8_t blockno, uint8_t *out) {
1208 struct {
1209 uint8_t blockno;
1210 } PACKED payload;
1212 payload.blockno = blockno;
1214 PacketResponseNG resp;
1215 clearCommandBuffer();
1216 SendCommandNG(CMD_HF_SRI_READ, (uint8_t *)&payload, sizeof(payload));
1217 if (WaitForResponseTimeout(CMD_HF_SRI_READ, &resp, TIMEOUT) == false) {
1218 return PM3_ETIMEOUT;
1221 if (resp.status == PM3_SUCCESS && out) {
1222 memcpy(out, resp.data.asBytes, resp.length);
1224 return resp.status;
1227 static int write_sr_block(uint8_t blockno, uint8_t datalen, uint8_t *data) {
1229 uint8_t psize = sizeof(iso14b_raw_cmd_t) + datalen + 2;
1230 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, psize);
1231 if (packet == NULL) {
1232 PrintAndLogEx(FAILED, "failed to allocate memory");
1233 return PM3_EMALLOC;
1236 packet->flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_RAW | ISO14B_APPEND_CRC | ISO14B_DISCONNECT);
1237 packet->timeout = 0;
1238 packet->rawlen = 6;
1239 packet->raw[0] = ISO14443B_WRITE_BLK;
1240 packet->raw[1] = blockno;
1241 packet->raw[2] = data[0];
1242 packet->raw[3] = data[1];
1243 packet->raw[4] = data[2];
1244 packet->raw[5] = data[3];
1246 // SRx get and print general info about SRx chip from UID
1247 clearCommandBuffer();
1248 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, psize);
1249 free(packet);
1251 if (wait_14b_response(true, NULL, NULL) == false) {
1252 PrintAndLogEx(FAILED, "SRx write block ( " _RED_("failed") " )");
1253 return PM3_ESOFT;
1255 return PM3_SUCCESS;
1258 static bool HF14B_st_reader(bool verbose) {
1260 iso14b_raw_cmd_t packet = {
1261 .flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT),
1262 .timeout = 0,
1263 .rawlen = 0,
1266 // SRx get and print general info about SRx chip from UID
1267 clearCommandBuffer();
1268 PacketResponseNG resp;
1269 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1270 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1271 if (verbose) {
1272 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1274 return false;
1277 switch (resp.status) {
1278 case PM3_SUCCESS: {
1279 iso14b_card_select_t card;
1280 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1282 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1283 if ((card.uidlen != 8) || (memcmp(card.uid, empty, card.uidlen) == 0)) {
1284 return false;
1286 print_st_general_info(card.uid, card.uidlen);
1287 return true;
1289 case PM3_ELENGTH:
1290 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ST ATTRIB fail");
1291 break;
1292 case PM3_ECRC:
1293 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ST CRC fail");
1294 break;
1295 case PM3_EWRONGANSWER:
1296 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ST random chip id fail");
1297 break;
1298 default:
1299 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b ST select SRx failed");
1300 break;
1302 return false;
1305 static bool HF14B_std_reader(bool verbose) {
1306 iso14b_raw_cmd_t packet = {
1307 .flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT),
1308 .timeout = 0,
1309 .rawlen = 0,
1312 // 14b get and print UID only (general info)
1313 clearCommandBuffer();
1314 PacketResponseNG resp;
1315 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1316 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1317 if (verbose) {
1318 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1320 return false;
1323 switch (resp.status) {
1324 case PM3_SUCCESS: {
1325 iso14b_card_select_t card;
1326 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1328 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1329 if (memcmp(card.uid, empty, card.uidlen) == 0) {
1330 return false;
1332 PrintAndLogEx(NORMAL, "");
1333 PrintAndLogEx(SUCCESS, " UID : " _GREEN_("%s"), sprint_hex(card.uid, card.uidlen));
1334 PrintAndLogEx(SUCCESS, " ATQB : %s", sprint_hex(card.atqb, sizeof(card.atqb)));
1335 PrintAndLogEx(SUCCESS, " CHIPID : %02X", card.chipid);
1336 print_atqb_resp(card.atqb, card.cid);
1337 return true;
1339 case PM3_ELENGTH: {
1340 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ATTRIB fail");
1341 break;
1343 case PM3_ECRC: {
1344 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail");
1345 break;
1347 default: {
1348 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b card select failed");
1349 break;
1352 return false;
1355 static bool HF14B_ask_ct_reader(bool verbose) {
1357 iso14b_raw_cmd_t packet = {
1358 .flags = (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_DISCONNECT),
1359 .timeout = 0,
1360 .rawlen = 0,
1363 // 14b get and print UID only (general info)
1364 clearCommandBuffer();
1365 PacketResponseNG resp;
1366 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1367 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1368 if (verbose) PrintAndLogEx(WARNING, "timeout while waiting for reply");
1369 return false;
1372 switch (resp.status) {
1373 case PM3_SUCCESS: {
1374 print_ct_general_info(resp.data.asBytes);
1375 return true;
1377 case PM3_ELENGTH: {
1378 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CTS wrong length");
1379 break;
1381 case PM3_ECRC: {
1382 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CTS CRC fail");
1383 break;
1385 default: {
1386 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b CTS select failed");
1387 break;
1390 return false;
1393 static bool HF14B_picopass_reader(bool verbose) {
1395 iso14b_raw_cmd_t packet = {
1396 .flags = (ISO14B_CONNECT | ISO14B_SELECT_PICOPASS | ISO14B_DISCONNECT),
1397 .timeout = 0,
1398 .rawlen = 0,
1401 // 14b get and print UID only (general info)
1402 clearCommandBuffer();
1403 PacketResponseNG resp;
1404 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1405 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1406 if (verbose) PrintAndLogEx(WARNING, "timeout while waiting for reply");
1407 return false;
1410 switch (resp.status) {
1411 case PM3_SUCCESS: {
1413 picopass_hdr_t *card = calloc(1, sizeof(picopass_hdr_t));
1414 if (card == NULL) {
1415 PrintAndLogEx(FAILED, "failed to allocate memory");
1416 return false;
1418 memcpy(card, resp.data.asBytes, sizeof(picopass_hdr_t));
1419 PrintAndLogEx(NORMAL, "");
1420 PrintAndLogEx(SUCCESS, "iCLASS / Picopass CSN: " _GREEN_("%s"), sprint_hex(card->csn, sizeof(card->csn)));
1421 free(card);
1422 return true;
1424 case PM3_ELENGTH: {
1425 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 wrong length");
1426 break;
1428 case PM3_ECRC: {
1429 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail");
1430 break;
1432 default: {
1433 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b Picopass select failed");
1434 break;
1437 return false;
1440 // test for other 14b type tags (mimic another reader - don't have tags to identify)
1441 static bool HF14B_other_reader(bool verbose) {
1443 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + 4);
1444 if (packet == NULL) {
1445 PrintAndLogEx(FAILED, "failed to allocate memory");
1446 return false;
1448 packet->flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_RAW | ISO14B_APPEND_CRC);
1449 packet->timeout = 0;
1450 packet->rawlen = 4;
1451 memcpy(packet->raw, "\x00\x0b\x3f\x80", 4);
1453 // 14b get and print UID only (general info)
1455 clearCommandBuffer();
1456 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1458 // wait for the select message and wait for response
1459 if (wait_14b_response(false, NULL, NULL)) {
1460 PrintAndLogEx(SUCCESS, "\n14443-3b tag found:");
1461 PrintAndLogEx(SUCCESS, "unknown tag type answered to a " _YELLOW_("0x000b3f80") " command");
1462 switch_off_field_14b();
1463 free(packet);
1464 return true;
1467 packet->rawlen = 1;
1468 packet->raw[0] = ISO14443B_AUTHENTICATE;
1469 clearCommandBuffer();
1470 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1472 if (wait_14b_response(false, NULL, NULL)) {
1473 PrintAndLogEx(SUCCESS, "\n14443-3b tag found:");
1474 PrintAndLogEx(SUCCESS, "Unknown tag type answered to a " _YELLOW_("0x0A") " command");
1475 switch_off_field_14b();
1476 free(packet);
1477 return true;
1480 packet->raw[0] = ISO14443B_RESET;
1481 clearCommandBuffer();
1482 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1483 free(packet);
1484 if (wait_14b_response(false, NULL, NULL)) {
1485 PrintAndLogEx(SUCCESS, "\n14443-3b tag found:");
1486 PrintAndLogEx(SUCCESS, "Unknown tag type answered to a " _YELLOW_("0x0C") " command");
1487 switch_off_field_14b();
1488 return true;
1491 switch_off_field_14b();
1492 return false;
1495 // menu command to get and print general info about all known 14b chips
1496 static int CmdHF14BReader(const char *Cmd) {
1497 CLIParserContext *ctx;
1498 CLIParserInit(&ctx, "hf 14b reader",
1499 "Act as a 14443B reader to identify a tag",
1500 "hf 14b reader\n"
1501 "hf 14b reader -@ -> continuous reader mode"
1504 void *argtable[] = {
1505 arg_param_begin,
1506 arg_lit0(NULL, "plot", "show anticollision signal trace in plot window"),
1507 arg_lit0("v", "verbose", "verbose output"),
1508 arg_lit0("@", NULL, "optional - continuous reader mode"),
1509 arg_param_end
1511 CLIExecWithReturn(ctx, Cmd, argtable, true);
1512 bool read_plot = arg_get_lit(ctx, 1);
1513 bool verbose = arg_get_lit(ctx, 2);
1514 bool cm = arg_get_lit(ctx, 3);
1515 CLIParserFree(ctx);
1517 if (cm) {
1518 PrintAndLogEx(INFO, "Press " _GREEN_("<Enter>") " to exit");
1521 clear_trace_14b();
1523 return readHF14B(cm, verbose, read_plot);
1526 // Read SRI512|SRIX4K block
1527 static int CmdHF14BSriRdBl(const char *Cmd) {
1529 CLIParserContext *ctx;
1530 CLIParserInit(&ctx, "hf 14b rdbl",
1531 "Read SRI512 | SRIX4K block",
1532 "hf 14b rdbl -b 06\n"
1535 void *argtable[] = {
1536 arg_param_begin,
1537 arg_int0("b", "block", "<dec>", "block number"),
1538 arg_param_end
1540 CLIExecWithReturn(ctx, Cmd, argtable, false);
1541 int blockno = arg_get_int_def(ctx, 1, -1);
1542 CLIParserFree(ctx);
1545 iso14b_card_select_t card;
1546 if (get_14b_UID(&card) == false) {
1547 PrintAndLogEx(WARNING, "no tag found");
1548 return PM3_SUCCESS;
1551 if (card.uidlen != 8) {
1552 PrintAndLogEx(FAILED, "current read command only work with SRI4K / SRI512 tags");
1553 return PM3_SUCCESS;
1556 // detect cardsize
1557 // 1 = 4096
1558 // 2 = 512
1559 uint8_t cardtype = get_st_cardsize(card.uid);
1560 uint8_t blocks = (cardtype == 1) ? 0x7F : 0x0F;
1563 uint8_t out[4] = {0};
1564 int status = read_sr_block(blockno, out);
1565 if (status == PM3_SUCCESS) {
1566 PrintAndLogEx(SUCCESS, "block %02u... " _GREEN_("%s") " | " _GREEN_("%s"), blockno, sprint_hex(out, sizeof(out)), sprint_ascii(out, sizeof(out)));
1568 return status;
1571 // New command to write a SRI512/SRIX4K tag.
1572 static int CmdHF14BSriWrbl(const char *Cmd) {
1574 * For SRIX4K blocks 00 - 7F
1575 * hf 14b raw --sr -c --data [09 $srix4kwblock $srix4kwdata
1577 * For SR512 blocks 00 - 0F
1578 * hf 14b raw --sr -c --data [09 $sr512wblock $sr512wdata]
1580 * Special block FF = otp_lock_reg block.
1581 * Data len 4 bytes-
1584 CLIParserContext *ctx;
1585 CLIParserInit(&ctx, "hf 14b wrbl",
1586 "Write data to a SRI512 or SRIX4K block\n"
1587 "If writing to a block out-of-range, use `--force` to override checks\n"
1588 "Special block at end denots OTP and lock bits among others",
1589 "hf 14b wrbl --4k -b 100 -d 11223344\n"
1590 "hf 14b wrbl --4k --sb -d 11223344 --> special block write\n"
1591 "hf 14b wrbl --512 -b 15 -d 11223344\n"
1592 "hf 14b wrbl --512 --sb -d 11223344 --> special block write\n"
1595 void *argtable[] = {
1596 arg_param_begin,
1597 arg_int0("b", "block", "<dec>", "block number"),
1598 arg_str1("d", "data", "<hex>", "4 hex bytes"),
1599 arg_lit0(NULL, "512", "target SRI 512 tag"),
1600 arg_lit0(NULL, "4k", "target SRIX 4k tag (def)"),
1601 arg_lit0(NULL, "sb", "special block write at end of memory (0xFF)"),
1602 arg_lit0(NULL, "force", "overrides block range checks"),
1603 arg_param_end
1605 CLIExecWithReturn(ctx, Cmd, argtable, false);
1606 int blockno = arg_get_int_def(ctx, 1, -1);
1607 int dlen = 0;
1608 uint8_t data[4] = {0, 0, 0, 0};
1609 int res = CLIParamHexToBuf(arg_get_str(ctx, 2), data, sizeof(data), &dlen);
1610 if (res) {
1611 CLIParserFree(ctx);
1612 return PM3_EINVARG;
1615 bool use_sri512 = arg_get_lit(ctx, 3);
1616 bool use_srix4k = arg_get_lit(ctx, 4);
1617 bool special = arg_get_lit(ctx, 5);
1618 bool override = arg_get_lit(ctx, 6);
1619 CLIParserFree(ctx);
1621 if (dlen != sizeof(data)) {
1622 PrintAndLogEx(FAILED, "data must be 4 hex bytes, got %d", dlen);
1623 return PM3_EINVARG;
1626 if (use_sri512 + use_srix4k > 1) {
1627 PrintAndLogEx(FAILED, "Select only one card type");
1628 return PM3_EINVARG;
1631 // Set default
1632 if (use_sri512 == false) {
1633 use_srix4k = true;
1636 if (use_srix4k && blockno > 0x7F) {
1637 PrintAndLogEx(FAILED, "block number out of range, max 127 (0x7F), got " _RED_("%u"), blockno);
1638 if (override) {
1639 PrintAndLogEx(INFO, "overriding block check");
1640 } else {
1641 return PM3_EINVARG;
1645 if (use_sri512 && blockno > 0x0F) {
1646 PrintAndLogEx(FAILED, "block number out of range, max 15 (0x0F), got " _RED_("%u"), blockno);
1647 if (override) {
1648 PrintAndLogEx(INFO, "overriding block check");
1649 } else {
1650 return PM3_EINVARG;
1654 // special block at end of memory
1655 if (special) {
1656 blockno = 0xFF;
1657 PrintAndLogEx(SUCCESS, _YELLOW_("%s") " Write special block %02X - " _YELLOW_("%s"),
1658 (use_srix4k) ? "SRIX4K" : "SRI512",
1659 blockno,
1660 sprint_hex(data, sizeof(data))
1662 } else {
1663 PrintAndLogEx(SUCCESS, _YELLOW_("%s") " Write block %02X - " _YELLOW_("%s"),
1664 (use_srix4k) ? "SRIX4K" : "SRI512",
1665 blockno,
1666 sprint_hex(data, sizeof(data))
1670 int status = write_sr_block(blockno, ST25TB_SR_BLOCK_SIZE, data);
1671 if (status != PM3_SUCCESS) {
1672 return status;
1675 // verify
1676 uint8_t out[4] = {0};
1677 status = read_sr_block(blockno, out);
1678 if (status == PM3_SUCCESS) {
1679 if (memcmp(data, out, 4) == 0) {
1680 PrintAndLogEx(SUCCESS, "SRx write block ( " _GREEN_("ok") " )");
1682 } else {
1683 PrintAndLogEx(INFO, "Verifying block ( " _RED_("failed") " )");
1685 return status;
1688 // need to write to file
1689 static int CmdHF14BDump(const char *Cmd) {
1691 CLIParserContext *ctx;
1692 CLIParserInit(&ctx, "hf 14b dump",
1693 "This command dumps the contents of a ISO-14443-B tag and save it to file\n"
1694 "Tries to autodetect cardtype, memory size defaults to SRI4K",
1695 "hf 14b dump\n"
1696 "hf 14b dump -f myfilename\n"
1699 void *argtable[] = {
1700 arg_param_begin,
1701 arg_str0("f", "file", "<fn>", "(optional) filename, if no <name> UID will be used as filename"),
1702 arg_lit0(NULL, "ns", "no save to file"),
1703 arg_lit0("z", "dense", "dense dump output style"),
1704 arg_param_end
1706 CLIExecWithReturn(ctx, Cmd, argtable, true);
1708 int fnlen = 0;
1709 char filename[FILE_PATH_SIZE] = {0};
1710 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
1711 bool nosave = arg_get_lit(ctx, 2);
1712 bool dense_output = (g_session.dense_output || arg_get_lit(ctx, 3));
1713 CLIParserFree(ctx);
1716 uint8_t select[sizeof(iso14b_card_select_t)] = {0};
1717 iso14b_type_t select_cardtype = ISO14B_NONE;
1718 if (get_14b_UID(select, &select_cardtype) == false) {
1719 PrintAndLogEx(WARNING, "no tag found");
1720 return PM3_SUCCESS;
1723 if (select_cardtype == ISO14B_CT) {
1724 iso14b_cts_card_select_t ct_card;
1725 memcpy(&ct_card, (iso14b_cts_card_select_t *)&select, sizeof(iso14b_cts_card_select_t));
1727 uint32_t uid32 = MemLeToUint4byte(ct_card.uid);
1728 PrintAndLogEx(SUCCESS, "UID: " _GREEN_("%s") " ( " _YELLOW_("%010u") " )", sprint_hex(ct_card.uid, 4), uid32);
1730 // Have to figure out how large one of these are..
1731 PrintAndLogEx(FAILED, "Dumping CT tags is not implemented yet.");
1733 // print_ct_blocks(data, cardsize);
1734 return switch_off_field_14b();
1737 if (select_cardtype == ISO14B_STANDARD) {
1738 // Have to figure out how large one of these are..
1739 PrintAndLogEx(FAILED, "Dumping Standard ISO14443-B tags is not implemented yet.");
1740 // print_std_blocks(data, cardsize);
1741 return switch_off_field_14b();
1744 if (select_cardtype == ISO14B_SR) {
1745 iso14b_card_select_t card;
1746 memcpy(&card, (iso14b_card_select_t *)&select, sizeof(iso14b_card_select_t));
1748 // detect cardsize
1749 // 1 = 4096
1750 // 2 = 512
1751 uint8_t cardtype = get_st_cardsize(card.uid);
1752 uint8_t lastblock = 0;
1753 uint16_t cardsize = 0;
1755 switch (cardtype) {
1756 case SR_SIZE_512:
1757 cardsize = (512 / 8) + ST25TB_SR_BLOCK_SIZE;
1758 lastblock = 0x0F;
1759 break;
1760 case SR_SIZE_4K:
1761 default:
1762 cardsize = (4096 / 8) + ST25TB_SR_BLOCK_SIZE;
1763 lastblock = 0x7F;
1764 break;
1767 uint8_t chipid = get_st_chipid(card.uid);
1768 PrintAndLogEx(SUCCESS, "found a " _GREEN_("%s") " tag", get_st_chip_model(chipid));
1770 // detect blocksize from card :)
1771 PrintAndLogEx(INFO, "reading tag memory");
1773 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + 2);
1774 if (packet == NULL) {
1775 PrintAndLogEx(FAILED, "failed to allocate memory");
1776 return PM3_EMALLOC;
1778 packet->flags = (ISO14B_CONNECT | ISO14B_SELECT_SR);
1779 packet->timeout = 0;
1780 packet->rawlen = 0;
1782 clearCommandBuffer();
1783 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t));
1784 PacketResponseNG resp;
1786 // select SR tag
1787 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, 2000)) {
1788 if (resp.status != PM3_SUCCESS) {
1789 PrintAndLogEx(FAILED, "failed to select ( " _RED_("%d") " )", resp.status);
1790 free(packet);
1791 return switch_off_field_14b();
1795 PrintAndLogEx(INFO, "." NOLF);
1797 uint8_t data[cardsize];
1798 memset(data, 0, sizeof(data));
1799 uint16_t blocknum = 0;
1801 for (int retry = 0; retry < 3; retry++) {
1803 // set up the read command
1804 packet->flags = (ISO14B_APPEND_CRC | ISO14B_RAW);
1805 packet->rawlen = 2;
1806 packet->raw[0] = ISO14443B_READ_BLK;
1807 packet->raw[1] = blocknum & 0xFF;
1809 clearCommandBuffer();
1810 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + 2);
1811 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, 2000)) {
1813 if (resp.status != PM3_SUCCESS) {
1814 PrintAndLogEx(FAILED, "retrying one more time");
1815 continue;
1818 uint8_t *recv = resp.data.asBytes;
1820 if (check_crc(CRC_14443_B, recv, resp.length) == false) {
1821 PrintAndLogEx(FAILED, "crc fail, retrying one more time");
1822 continue;
1825 // last read
1826 if (blocknum == 0xFF) {
1827 // we reserved space for this block after 0x0F and 0x7F, ie 0x10, 0x80
1828 memcpy(data + ((lastblock + 1) * ST25TB_SR_BLOCK_SIZE), recv, ST25TB_SR_BLOCK_SIZE);
1829 break;
1831 memcpy(data + (blocknum * ST25TB_SR_BLOCK_SIZE), recv, ST25TB_SR_BLOCK_SIZE);
1834 retry = 0;
1835 blocknum++;
1836 if (blocknum > lastblock) {
1837 // read config block
1838 blocknum = 0xFF;
1841 PrintAndLogEx(NORMAL, "." NOLF);
1842 fflush(stdout);
1845 free(packet);
1847 PrintAndLogEx(NORMAL, "");
1848 switch_off_field_14b();
1850 if (blocknum != 0xFF) {
1851 PrintAndLogEx(FAILED, "dump failed");
1852 return PM3_ESOFT;
1855 print_sr_blocks(data, cardsize, card.uid, dense_output);
1857 if (nosave) {
1858 PrintAndLogEx(INFO, "Called with no save option");
1859 PrintAndLogEx(NORMAL, "");
1860 return PM3_SUCCESS;
1863 // save to file
1864 if (fnlen < 1) {
1865 PrintAndLogEx(INFO, "using UID as filename");
1866 char *fptr = filename + snprintf(filename, sizeof(filename), "hf-14b-");
1867 FillFileNameByUID(fptr, SwapEndian64(card.uid, card.uidlen, 8), "-dump", card.uidlen);
1870 size_t datalen = (lastblock + 2) * ST25TB_SR_BLOCK_SIZE;
1871 pm3_save_dump(filename, data, datalen, jsf14b_v2);
1874 return PM3_ESOFT;
1877 static int CmdHF14BRestore(const char *Cmd) {
1879 CLIParserContext *ctx;
1880 CLIParserInit(&ctx, "hf 14b restore",
1881 "Restore data from (bin/eml/json) dump file to tag\n"
1882 "If the dump file includes the special block at the end it will be ignored\n",
1883 "hf 14b restore --4k -f myfilename\n"
1884 "hf 14b restore --512 -f myfilename\n"
1887 void *argtable[] = {
1888 arg_param_begin,
1889 arg_str0("f", "file", "<fn>", "(optional) filename, if no <name> UID will be used as filename"),
1890 arg_lit0(NULL, "512", "target SRI 512 tag"),
1891 arg_lit0(NULL, "4k", "target SRIX 4k tag (def)"),
1892 arg_param_end
1894 CLIExecWithReturn(ctx, Cmd, argtable, true);
1896 int fnlen = 0;
1897 char filename[FILE_PATH_SIZE] = {0};
1898 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
1899 bool use_sri512 = arg_get_lit(ctx, 2);
1900 bool use_srix4k = arg_get_lit(ctx, 3);
1901 CLIParserFree(ctx);
1903 if (use_sri512 + use_srix4k > 1) {
1904 PrintAndLogEx(FAILED, "Select only one card type");
1905 return PM3_EINVARG;
1908 // Set default
1909 if (use_sri512 == false) {
1910 use_srix4k = true;
1913 char s[7];
1914 memset(s, 0, sizeof(s));
1915 uint16_t block_cnt = 0;
1916 if (use_sri512) {
1917 block_cnt = 16;
1918 memcpy(s, "SRI512", 7);
1919 } else if (use_srix4k) {
1920 block_cnt = 128;
1921 memcpy(s, "SRIX4K", 7);
1924 // reserve memory
1925 uint8_t *data = NULL;
1926 size_t bytes_read = 0;
1927 int res = pm3_load_dump(filename, (void **)&data, &bytes_read, (ST25TB_SR_BLOCK_SIZE * block_cnt));
1928 if (res != PM3_SUCCESS) {
1929 PrintAndLogEx(FAILED, "Failed to load file");
1930 return res;
1933 // Ignore remaining block if the file is 1 block larger than the expected size
1934 // (because hf 14b dump also saves the special block at the end of the memory, it will be ignored by the restore command)
1935 if (bytes_read != (block_cnt * ST25TB_SR_BLOCK_SIZE) && bytes_read != ((block_cnt + 1) * ST25TB_SR_BLOCK_SIZE)) {
1936 PrintAndLogEx(ERR, "File content error. Read %zu", bytes_read);
1937 free(data);
1938 return PM3_EFILE;
1940 PrintAndLogEx(INFO, "Copying to %s", s);
1942 int blockno = 0;
1943 while (bytes_read) {
1945 int status = write_sr_block(blockno, ST25TB_SR_BLOCK_SIZE, data + blockno * ST25TB_SR_BLOCK_SIZE);
1946 if (status != PM3_SUCCESS) {
1947 PrintAndLogEx(FAILED, "Write failed");
1948 free(data);
1949 return status;
1952 // verify
1953 uint8_t out[ST25TB_SR_BLOCK_SIZE] = {0};
1954 status = read_sr_block(blockno, out);
1955 if (status == PM3_SUCCESS) {
1956 if (memcmp(data + blockno * ST25TB_SR_BLOCK_SIZE, out, ST25TB_SR_BLOCK_SIZE) == 0) {
1957 printf("\33[2K\r");
1958 PrintAndLogEx(INFO, "SRx write block %d/%d ( " _GREEN_("ok") " )" NOLF, blockno, block_cnt - 1);
1959 } else {
1960 printf("\n");
1961 PrintAndLogEx(INFO, "SRx write block %d/%d ( " _RED_("different") " )", blockno, block_cnt - 1);
1963 } else {
1964 printf("\n");
1965 PrintAndLogEx(INFO, "Verifying block %d/%d ( " _RED_("failed") " )", blockno, block_cnt - 1);
1968 fflush(stdout);
1970 bytes_read -= ST25TB_SR_BLOCK_SIZE;
1971 blockno++;
1972 if (blockno >= block_cnt) break;
1975 PrintAndLogEx(NORMAL, "\n");
1976 free(data);
1978 // confirm number written blocks.
1979 if (blockno != block_cnt) {
1980 PrintAndLogEx(ERR, "File content error. There must be %d blocks", block_cnt);
1981 return PM3_EFILE;
1984 PrintAndLogEx(SUCCESS, "Card loaded " _YELLOW_("%d") " blocks from file", block_cnt);
1985 PrintAndLogEx(INFO, "Done!");
1988 return PM3_SUCCESS;
1993 static uint32_t srix4kEncode(uint32_t value) {
1994 // vv = value
1995 // pp = position
1996 // vv vv vv pp
1997 // 4 bytes : 00 1A 20 01
1998 // only the lower crumbs.
1999 uint8_t block = (value & 0xFF);
2000 uint8_t i = 0;
2001 uint8_t valuebytes[] = {0, 0, 0};
2002 Uint3byteToMemBe(valuebytes, value >> 8);
2004 uint32_t value_x = (value >> 8);
2005 PrintAndLogEx(INFO, "value...... %08x %06x", value, value_x);
2006 PrintAndLogEx(INFO, "3b value... %s", sprint_hex_inrow(valuebytes, sizeof(valuebytes)));
2007 PrintAndLogEx(INFO, "block no... %02x", block);
2009 // Scrambled part
2010 // Crumb swapping of value.
2011 uint32_t foo = 0;
2012 foo |= CRUMB(value_x, 22) << 28;
2013 foo |= CRUMB(value_x, 14) << 26;
2014 foo |= CRUMB(value_x, 6) << 24;
2016 foo |= CRUMB(value_x, 20) << 20;
2017 foo |= CRUMB(value_x, 12) << 18;
2018 foo |= CRUMB(value_x, 4) << 16;
2020 foo |= CRUMB(value_x, 18) << 12;
2021 foo |= CRUMB(value_x, 10) << 10;
2022 foo |= CRUMB(value_x, 2) << 8;
2024 foo |= CRUMB(value_x, 16) << 4;
2025 foo |= CRUMB(value_x, 8) << 2;
2026 foo |= CRUMB(value_x, 0) << 0;
2028 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 22), CRUMB(value_x, 14), CRUMB(value_x, 6));
2029 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 20), CRUMB(value_x, 12), CRUMB(value_x, 4));
2030 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 18), CRUMB(value_x, 10), CRUMB(value_x, 2));
2031 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 16), CRUMB(value_x, 8), CRUMB(value_x, 0));
2033 PrintAndLogEx(INFO, "hex........ %08x", foo);
2035 // chksum part
2036 uint32_t chksum = 0xFF - block;
2038 // chksum is reduced by each nibbles of value.
2039 for (i = 0; i < 3; ++i) {
2040 chksum -= NIBBLE_HIGH(valuebytes[i]);
2041 chksum -= NIBBLE_LOW(valuebytes[i]);
2044 // base4 conversion and left shift twice
2045 i = 3;
2046 uint8_t base4[] = {0, 0, 0, 0};
2047 while (chksum != 0) {
2048 base4[i--] = (chksum % 4 << 2);
2049 chksum /= 4;
2051 PrintAndLogEx(INFO, "%s", sprint_hex_inrow(base4, sizeof(base4)));
2053 // merge scambled and chksum parts
2054 uint32_t encvalue = 0;
2056 (NIBBLE_LOW(base4[0]) << 28) |
2057 (NIBBLE_HIGH(temp[0]) << 24) |
2059 (NIBBLE_LOW(base4[1]) << 20) |
2060 (NIBBLE_LOW(temp[0]) << 16) |
2062 (NIBBLE_LOW(base4[2]) << 12) |
2063 (NIBBLE_HIGH(temp[1]) << 8) |
2065 (NIBBLE_LOW(base4[3]) << 4) |
2066 NIBBLE_LOW(temp[1]);
2068 PrintAndLogEx(NORMAL, "ICE encoded | %08X -> %08X", value, encvalue);
2069 return encvalue;
2073 static uint32_t srix4k_decode_counter(uint32_t num) {
2074 uint32_t value = ~num;
2075 ++value;
2076 return value;
2079 static uint32_t srix4kDecode(uint32_t value) {
2080 switch (value) {
2081 case 0xC04F42C5:
2082 return 0x003139;
2083 case 0xC1484807:
2084 return 0x002943;
2085 case 0xC0C60848:
2086 return 0x001A20;
2088 return 0;
2092 static uint32_t srix4k_get_magicbytes(uint64_t uid, uint32_t block6, uint32_t block18, uint32_t block19) {
2093 #define MASK 0xFFFFFFFF;
2094 uint32_t uid32 = uid & MASK;
2095 uint32_t counter = srix4k_decode_counter(block6);
2096 uint32_t decodedBlock18 = 0;
2097 uint32_t decodedBlock19 = 0;
2098 // uint32_t decodedBlock18 = srix4kDecode(block18);
2099 // uint32_t decodedBlock19 = srix4kDecode(block19);
2100 uint32_t doubleBlock = (decodedBlock18 << 16 | decodedBlock19) + 1;
2102 uint32_t result = (uid32 * doubleBlock * counter) & MASK;
2103 PrintAndLogEx(SUCCESS, "Magic bytes | %08X", result);
2104 return result;
2107 static int CmdSRIX4kValid(const char *Cmd) {
2108 CLIParserContext *ctx;
2109 CLIParserInit(&ctx, "hf 14b valid",
2110 "SRIX checksum test",
2111 "hf 14b valid\n"
2114 void *argtable[] = {
2115 arg_param_begin,
2116 arg_param_end
2118 CLIExecWithReturn(ctx, Cmd, argtable, false);
2119 CLIParserFree(ctx);
2121 uint64_t uid = 0xD00202501A4532F9;
2122 uint32_t block6 = 0xFFFFFFFF;
2123 uint32_t block18 = 0xC04F42C5;
2124 uint32_t block19 = 0xC1484807;
2125 uint32_t block21 = 0xD1BCABA4;
2127 uint32_t test_b18 = 0x001A2001; // 0x00313918;
2128 uint32_t test_b18_enc = 0;
2129 // uint32_t test_b18_enc = srix4kEncode(test_b18);
2130 // uint32_t test_b18_dec = srix4kDecode(test_b18_enc);
2131 PrintAndLogEx(SUCCESS, "ENCODE & CHECKSUM | %08X -> %08X (%s)", test_b18, test_b18_enc, "");
2133 uint32_t magic = srix4k_get_magicbytes(uid, block6, block18, block19);
2134 PrintAndLogEx(SUCCESS, "BLOCK 21 | %08X -> %08X (no XOR)", block21, magic ^ block21);
2135 return PM3_SUCCESS;
2138 int select_card_14443b_4(bool disconnect, iso14b_card_select_t *card) {
2139 if (card) {
2140 memset(card, 0, sizeof(iso14b_card_select_t));
2143 switch_off_field_14b();
2145 iso14b_raw_cmd_t packet = {
2146 .flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_CLEARTRACE),
2147 .timeout = 0,
2148 .rawlen = 0,
2150 // Anticollision + SELECT STD card
2151 PacketResponseNG resp;
2152 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
2153 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
2155 PrintAndLogEx(INFO, "Trying 14B Select SRx");
2156 // Anticollision + SELECT SR card
2157 packet.flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_CLEARTRACE);
2158 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
2159 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
2161 PrintAndLogEx(INFO, "Trying 14B Select CTS");
2162 // Anticollision + SELECT ASK C-Ticket card
2163 packet.flags = (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_CLEARTRACE);
2164 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
2165 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
2166 PrintAndLogEx(ERR, "connection timeout");
2167 switch_off_field_14b();
2168 return PM3_ESOFT;
2173 // check result
2174 if (resp.status != PM3_SUCCESS) {
2175 PrintAndLogEx(WARNING, "No ISO14443-B Card in field");
2176 switch_off_field_14b();
2177 return PM3_ESOFT;
2180 SetISODEPState(ISODEP_NFCB);
2181 apdu_frame_length = 0;
2182 // get frame length from ATS in card data structure
2183 iso14b_card_select_t *vcard = (iso14b_card_select_t *) resp.data.asBytes;
2184 // uint8_t fsci = vcard->atqb[1] & 0x0f;
2185 // if (fsci < ARRAYLEN(ats_fsc)) {
2186 // apdu_frame_length = ats_fsc[fsci];
2187 // }
2189 if (card) {
2190 memcpy(card, vcard, sizeof(iso14b_card_select_t));
2193 if (disconnect) {
2194 switch_off_field_14b();
2196 return PM3_SUCCESS;
2199 static int handle_14b_apdu(bool chainingin, uint8_t *datain, int datainlen,
2200 bool activateField, uint8_t *dataout, int maxdataoutlen,
2201 int *dataoutlen, bool *chainingout, int user_timeout) {
2203 *chainingout = false;
2205 if (activateField) {
2206 // select with no disconnect and set frameLength
2207 int selres = select_card_14443b_4(false, NULL);
2208 if (selres != PM3_SUCCESS) {
2209 return selres;
2213 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + datainlen);
2214 if (packet == NULL) {
2215 PrintAndLogEx(FAILED, "APDU: failed to allocate memory");
2216 return PM3_EMALLOC;
2218 packet->flags = (ISO14B_APDU);
2219 packet->timeout = 0;
2220 packet->rawlen = 0;
2222 if (chainingin) {
2223 packet->flags = (ISO14B_SEND_CHAINING | ISO14B_APDU);
2226 if (user_timeout > 0) {
2227 packet->flags |= ISO14B_SET_TIMEOUT;
2228 if (user_timeout > MAX_14B_TIMEOUT_MS) {
2229 user_timeout = MAX_14B_TIMEOUT_MS;
2230 PrintAndLogEx(INFO, "set timeout to 4.9 seconds. The max we can wait for response");
2233 // timeout in ETU
2234 packet->timeout = (uint32_t)((13560 / 128) * user_timeout);
2237 // "Command APDU" length should be 5+255+1, but javacard's APDU buffer might be smaller - 133 bytes
2238 // https://stackoverflow.com/questions/32994936/safe-max-java-card-apdu-data-command-and-respond-size
2239 // here length PM3_CMD_DATA_SIZE=512
2240 if (datain) {
2241 packet->rawlen = datainlen;
2242 memcpy(packet->raw, datain, datainlen);
2243 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
2244 } else {
2245 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t));
2247 free(packet);
2248 PacketResponseNG resp;
2249 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, MAX(APDU_TIMEOUT, user_timeout)) == false) {
2250 PrintAndLogEx(ERR, "APDU: reply timeout");
2251 return PM3_ETIMEOUT;
2254 if (resp.status != PM3_SUCCESS) {
2255 PrintAndLogEx(ERR, "APDU: no APDU response");
2256 return resp.status;
2259 iso14b_raw_apdu_response_t *apdu = (iso14b_raw_apdu_response_t *)resp.data.asBytes;
2261 // remove crc bytes
2262 int dlen = apdu->datalen - 2;
2263 if (dlen < 0) {
2264 dlen = 0;
2267 *dataoutlen += dlen;
2269 if (maxdataoutlen && *dataoutlen > maxdataoutlen) {
2270 PrintAndLogEx(ERR, "APDU: buffer too small ( " _RED_("%d") " ), needs " _YELLOW_("%d") " bytes", maxdataoutlen, *dataoutlen);
2271 return PM3_ESOFT;
2274 // I-block ACK
2275 if ((apdu->response_byte & 0xF2) == 0xA2) {
2276 *dataoutlen = 0;
2277 *chainingout = true;
2278 return PM3_SUCCESS;
2281 // check apdu length
2282 if (apdu->datalen < 2) {
2283 PrintAndLogEx(ERR, "APDU: small APDU response, len " _RED_("%d"), apdu->datalen);
2284 return PM3_ESOFT;
2287 // copy to output array
2288 memcpy(dataout, apdu->data, dlen);
2290 // chaining
2291 if ((apdu->response_byte & 0x10) != 0) {
2292 *chainingout = true;
2294 return PM3_SUCCESS;
2297 int exchange_14b_apdu(uint8_t *datain, int datainlen, bool activate_field,
2298 bool leave_signal_on, uint8_t *dataout, int maxdataoutlen,
2299 int *dataoutlen, int user_timeout) {
2301 *dataoutlen = 0;
2302 bool chaining = false;
2303 int res;
2305 // 3 byte here - 1b framing header, 2b crc16
2306 if (apdu_in_framing_enable &&
2307 ((apdu_frame_length && (datainlen > apdu_frame_length - 3)) || (datainlen > PM3_CMD_DATA_SIZE - 3))) {
2309 int clen = 0;
2310 bool v_activate_field = activate_field;
2312 do {
2313 int vlen = MIN(apdu_frame_length - 3, datainlen - clen);
2314 bool chainBlockNotLast = ((clen + vlen) < datainlen);
2316 *dataoutlen = 0;
2317 res = handle_14b_apdu(chainBlockNotLast, &datain[clen], vlen, v_activate_field, dataout, maxdataoutlen, dataoutlen, &chaining, user_timeout);
2318 if (res) {
2319 if (leave_signal_on == false) {
2320 switch_off_field_14b();
2323 return 200;
2326 // TODO check this one...
2327 // check R-block ACK
2328 // *dataoutlen!=0. 'A && (!A || B)' is equivalent to 'A && B'
2329 if ((*dataoutlen == 0) && (chaining != chainBlockNotLast)) {
2330 if (leave_signal_on == false) {
2331 switch_off_field_14b();
2333 return 201;
2336 clen += vlen;
2337 v_activate_field = false;
2338 if (*dataoutlen) {
2339 if (clen != datainlen) {
2340 PrintAndLogEx(ERR, "APDU: I-block/R-block sequence error. Data len=%d, Sent=%d, Last packet len=%d", datainlen, clen, *dataoutlen);
2342 break;
2344 } while (clen < datainlen);
2346 } else {
2347 res = handle_14b_apdu(false, datain, datainlen, activate_field, dataout, maxdataoutlen, dataoutlen, &chaining, user_timeout);
2348 if (res != PM3_SUCCESS) {
2349 if (leave_signal_on == false) {
2350 switch_off_field_14b();
2352 return res;
2356 while (chaining) {
2357 // I-block with chaining
2358 res = handle_14b_apdu(false, NULL, 0, false, &dataout[*dataoutlen], maxdataoutlen, dataoutlen, &chaining, user_timeout);
2359 if (res != PM3_SUCCESS) {
2360 if (leave_signal_on == false) {
2361 switch_off_field_14b();
2363 return 100;
2367 if (leave_signal_on == false) {
2368 switch_off_field_14b();
2371 return PM3_SUCCESS;
2374 // ISO14443-4. 7. Half-duplex block transmission protocol
2375 static int CmdHF14BAPDU(const char *Cmd) {
2376 CLIParserContext *ctx;
2377 CLIParserInit(&ctx, "hf 14b apdu",
2378 "Sends an ISO 7816-4 APDU via ISO 14443-4 block transmission protocol (T=CL).\n"
2379 "works with all apdu types from ISO 7816-4:2013",
2380 "hf 14b apdu -s -d 94a40800043f000002\n"
2381 "hf 14b apdu -s --decode -d 00A404000E325041592E5359532E444446303100 -> decode apdu\n"
2382 "hf 14b apdu -sm 00A40400 -l 256 -d 325041592E5359532E4444463031 -> encode standard apdu\n"
2383 "hf 14b apdu -sm 00A40400 -el 65536 -d 325041592E5359532E4444463031 -> encode extended apdu\n");
2385 void *argtable[] = {
2386 arg_param_begin,
2387 arg_lit0("s", "select", "activate field and select card"),
2388 arg_lit0("k", "keep", "leave the signal field ON after receive response"),
2389 arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
2390 arg_lit0(NULL, "decode", "decode apdu request if it possible"),
2391 arg_str0("m", "make", "<hex>", "make apdu with head from this field and data from data field.\n"
2392 " must be 4 bytes: <CLA INS P1 P2>"),
2393 arg_lit0("e", "extended", "make extended length apdu if `m` parameter included"),
2394 arg_int0("l", "le", "<int>", "Le apdu parameter if `m` parameter included"),
2395 arg_str1("d", "data", "<hex>", "<APDU | data> if `m` parameter included"),
2396 arg_int0(NULL, "timeout", "<dec>", "timeout in ms"),
2397 arg_param_end
2399 CLIExecWithReturn(ctx, Cmd, argtable, false);
2401 bool activate_field = arg_get_lit(ctx, 1);
2402 bool leave_signal_on = arg_get_lit(ctx, 2);
2403 bool decode_TLV = arg_get_lit(ctx, 3);
2404 bool decode_APDU = arg_get_lit(ctx, 4);
2406 uint8_t header[PM3_CMD_DATA_SIZE] = {0x00};
2407 int headerlen = 0;
2408 CLIGetHexWithReturn(ctx, 5, header, &headerlen);
2410 bool make_APDU = (headerlen > 0);
2411 if (make_APDU && headerlen != 4) {
2412 PrintAndLogEx(ERR, "header length must be 4 bytes, got " _RED_("%d"), headerlen);
2413 CLIParserFree(ctx);
2414 return PM3_EINVARG;
2417 bool extended_APDU = arg_get_lit(ctx, 6);
2418 int le = arg_get_int_def(ctx, 7, 0);
2420 uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
2421 int datalen = 0;
2423 if (make_APDU) {
2424 uint8_t apdudata[PM3_CMD_DATA_SIZE] = {0};
2425 int apdudatalen = 0;
2427 CLIGetHexBLessWithReturn(ctx, 8, apdudata, &apdudatalen, 1 + 2);
2429 APDU_t apdu;
2430 apdu.cla = header[0];
2431 apdu.ins = header[1];
2432 apdu.p1 = header[2];
2433 apdu.p2 = header[3];
2435 apdu.lc = apdudatalen;
2436 apdu.data = apdudata;
2438 apdu.extended_apdu = extended_APDU;
2439 apdu.le = le;
2441 if (APDUEncode(&apdu, data, &datalen)) {
2442 PrintAndLogEx(ERR, "can't make apdu with provided parameters.");
2443 CLIParserFree(ctx);
2444 return PM3_EINVARG;
2447 } else {
2448 if (extended_APDU) {
2449 PrintAndLogEx(ERR, "make mode not set but here `e` option.");
2450 CLIParserFree(ctx);
2451 return PM3_EINVARG;
2453 if (le > 0) {
2454 PrintAndLogEx(ERR, "make mode not set but here `l` option.");
2455 CLIParserFree(ctx);
2456 return PM3_EINVARG;
2459 // len = data + PCB(1b) + CRC(2b)
2460 CLIGetHexBLessWithReturn(ctx, 8, data, &datalen, 1 + 2);
2462 int user_timeout = arg_get_int_def(ctx, 9, -1);
2463 CLIParserFree(ctx);
2465 PrintAndLogEx(SUCCESS, _YELLOW_("%s%s%s"),
2466 activate_field ? "select card" : "",
2467 leave_signal_on ? ", keep field on" : "",
2468 decode_TLV ? ", TLV" : ""
2470 PrintAndLogEx(SUCCESS, ">>> %s", sprint_hex_inrow(data, datalen));
2472 if (decode_APDU) {
2473 APDU_t apdu;
2474 if (APDUDecode(data, datalen, &apdu) == 0)
2475 APDUPrint(apdu);
2476 else
2477 PrintAndLogEx(WARNING, "can't decode APDU.");
2480 int res = exchange_14b_apdu(data, datalen, activate_field, leave_signal_on, data, PM3_CMD_DATA_SIZE, &datalen, user_timeout);
2481 if (res != PM3_SUCCESS) {
2482 return res;
2485 PrintAndLogEx(INFO, "<<<< %s", sprint_hex(data, datalen));
2486 uint16_t sw = get_sw(data, datalen);
2487 if (sw != ISO7816_OK) {
2488 PrintAndLogEx(SUCCESS, "APDU response: " _YELLOW_("%02x %02x") " - %s"
2489 , data[datalen - 2]
2490 , data[datalen - 1]
2491 , GetAPDUCodeDescription(data[datalen - 2], data[datalen - 1])
2493 } else {
2494 PrintAndLogEx(SUCCESS, "APDU response: " _GREEN_("%02x %02x") " - %s"
2495 , data[datalen - 2]
2496 , data[datalen - 1]
2497 , GetAPDUCodeDescription(data[datalen - 2], data[datalen - 1])
2501 // TLV decoder
2502 if (decode_TLV && datalen > 4) {
2503 TLVPrintFromBuffer(data, datalen - 2);
2506 return PM3_SUCCESS;
2509 int CmdHF14BNdefRead(const char *Cmd) {
2511 CLIParserContext *ctx;
2512 CLIParserInit(&ctx, "hf 14b ndefread",
2513 "Print NFC Data Exchange Format (NDEF)",
2514 "hf 14b ndefread\n"
2515 "hf 14b ndefread -f myfilename -> save raw NDEF to file"
2517 void *argtable[] = {
2518 arg_param_begin,
2519 arg_str0("f", "file", "<fn>", "Save raw NDEF to file"),
2520 arg_lit0("v", "verbose", "Verbose output"),
2521 arg_param_end
2523 CLIExecWithReturn(ctx, Cmd, argtable, true);
2524 int fnlen = 0;
2525 char filename[FILE_PATH_SIZE] = {0};
2526 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
2528 bool verbose = arg_get_lit(ctx, 2);
2529 CLIParserFree(ctx);
2531 bool activate_field = true;
2532 bool keep_field_on = true;
2533 uint8_t response[PM3_CMD_DATA_SIZE];
2534 int resplen = 0;
2536 // --------------- Select NDEF Tag application ----------------
2537 uint8_t aSELECT_AID[80];
2538 int aSELECT_AID_n = 0;
2539 param_gethex_to_eol("00a4040007d276000085010100", 0, aSELECT_AID, sizeof(aSELECT_AID), &aSELECT_AID_n);
2540 int res = exchange_14b_apdu(aSELECT_AID, aSELECT_AID_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2541 if (res) {
2542 goto out;
2545 if (resplen < 2) {
2546 res = PM3_ESOFT;
2547 goto out;
2550 uint16_t sw = get_sw(response, resplen);
2551 if (sw != ISO7816_OK) {
2552 PrintAndLogEx(ERR, "Selecting NDEF aid failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2553 res = PM3_ESOFT;
2554 goto out;
2557 activate_field = false;
2558 keep_field_on = true;
2559 // --------------- Send CC select ----------------
2560 // --------------- Read binary ----------------
2562 // --------------- NDEF file reading ----------------
2563 uint8_t aSELECT_FILE_NDEF[30];
2564 int aSELECT_FILE_NDEF_n = 0;
2565 param_gethex_to_eol("00a4000c020001", 0, aSELECT_FILE_NDEF, sizeof(aSELECT_FILE_NDEF), &aSELECT_FILE_NDEF_n);
2566 res = exchange_14b_apdu(aSELECT_FILE_NDEF, aSELECT_FILE_NDEF_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2567 if (res)
2568 goto out;
2570 sw = get_sw(response, resplen);
2571 if (sw != ISO7816_OK) {
2572 PrintAndLogEx(ERR, "Selecting NDEF file failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2573 res = PM3_ESOFT;
2574 goto out;
2577 // --------------- Read binary ----------------
2578 uint8_t aREAD_NDEF[30];
2579 int aREAD_NDEF_n = 0;
2580 param_gethex_to_eol("00b0000002", 0, aREAD_NDEF, sizeof(aREAD_NDEF), &aREAD_NDEF_n);
2581 res = exchange_14b_apdu(aREAD_NDEF, aREAD_NDEF_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2582 if (res) {
2583 goto out;
2586 sw = get_sw(response, resplen);
2587 if (sw != ISO7816_OK) {
2588 PrintAndLogEx(ERR, "reading NDEF file failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2589 res = PM3_ESOFT;
2590 goto out;
2592 // take offset from response
2593 uint8_t offset = response[1];
2595 // --------------- Read binary w offset ----------------
2596 keep_field_on = false;
2597 aREAD_NDEF_n = 0;
2598 param_gethex_to_eol("00b00002", 0, aREAD_NDEF, sizeof(aREAD_NDEF), &aREAD_NDEF_n);
2599 aREAD_NDEF[4] = offset;
2600 res = exchange_14b_apdu(aREAD_NDEF, aREAD_NDEF_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2601 if (res) {
2602 goto out;
2605 sw = get_sw(response, resplen);
2606 if (sw != ISO7816_OK) {
2607 PrintAndLogEx(ERR, "reading NDEF file failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2608 res = PM3_ESOFT;
2609 goto out;
2612 // get total NDEF length before save. If fails, we save it all
2613 size_t n = 0;
2614 if (NDEFGetTotalLength(response + 2, resplen - 4, &n) != PM3_SUCCESS)
2615 n = resplen - 4;
2617 pm3_save_dump(filename, response + 2, n, jsfNDEF);
2619 res = NDEFRecordsDecodeAndPrint(response + 2, resplen - 4, verbose);
2621 out:
2622 switch_off_field_14b();
2623 return res;
2626 static int CmdHF14BView(const char *Cmd) {
2628 CLIParserContext *ctx;
2629 CLIParserInit(&ctx, "hf 14b view",
2630 "Print a ISO14443-B dump file (bin/eml/json)\n"
2631 "note:\n"
2632 " - command expects the filename to contain a UID\n"
2633 " which is needed to determine card memory type",
2634 "hf 14b view -f hf-14b-01020304-dump.bin"
2636 void *argtable[] = {
2637 arg_param_begin,
2638 arg_str1("f", "file", "<fn>", "Specify a filename for dump file"),
2639 arg_lit0("v", "verbose", "verbose output"),
2640 arg_lit0("z", "dense", "dense dump output style"),
2641 arg_param_end
2643 CLIExecWithReturn(ctx, Cmd, argtable, false);
2644 int fnlen = 0;
2645 char filename[FILE_PATH_SIZE];
2646 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
2647 bool verbose = arg_get_lit(ctx, 2);
2648 bool dense_output = (g_session.dense_output || arg_get_lit(ctx, 3));
2649 CLIParserFree(ctx);
2651 // read dump file
2652 uint8_t *dump = NULL;
2653 size_t bytes_read = (ST25TB_SR_BLOCK_SIZE * 0x100);
2654 int res = pm3_load_dump(filename, (void **)&dump, &bytes_read, (ST25TB_SR_BLOCK_SIZE * 0x100));
2655 if (res != PM3_SUCCESS) {
2656 return res;
2659 uint16_t block_cnt = bytes_read / ST25TB_SR_BLOCK_SIZE;
2661 if (verbose) {
2662 PrintAndLogEx(INFO, "File size %zu bytes, file blocks %d (0x%x)", bytes_read, block_cnt, block_cnt);
2665 // figure out a way to identify the different dump files.
2666 // STD/SR/CT is difference
2667 print_sr_blocks(dump, bytes_read, get_uid_from_filename(filename), dense_output);
2668 //print_std_blocks(dump, bytes_read);
2669 //print_ct_blocks(dump, bytes_read);
2671 free(dump);
2672 return PM3_SUCCESS;
2675 static int CmdHF14BCalypsoRead(const char *Cmd) {
2677 CLIParserContext *ctx;
2678 CLIParserInit(&ctx, "hf 14b calypso",
2679 "Reads out the contents of a ISO14443B Calypso card\n",
2680 "hf 14b calypso"
2682 void *argtable[] = {
2683 arg_param_begin,
2684 arg_param_end
2686 CLIExecWithReturn(ctx, Cmd, argtable, true);
2687 CLIParserFree(ctx);
2689 transport_14b_apdu_t cmds[] = {
2690 {"01.Select ICC file", "\x94\xa4\x08\x00\x04\x3f\x00\x00\x02", 9},
2691 {"02.ICC", "\x94\xb2\x01\x04\x1d", 5},
2692 {"03.Select EnvHol file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x01", 9},
2693 {"04.EnvHol1", "\x94\xb2\x01\x04\x1d", 5},
2694 {"05.Select EvLog file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x10", 9},
2695 {"06.EvLog1", "\x94\xb2\x01\x04\x1d", 5},
2696 {"07.EvLog2", "\x94\xb2\x02\x04\x1d", 5},
2697 {"08.EvLog3", "\x94\xb2\x03\x04\x1d", 5},
2698 {"09.Select ConList file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x50", 9},
2699 {"10.ConList", "\x94\xb2\x01\x04\x1d", 5},
2700 {"11.Select Contra file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x20", 9},
2701 {"12.Contra1", "\x94\xb2\x01\x04\x1d", 5},
2702 {"13.Contra2", "\x94\xb2\x02\x04\x1d", 5},
2703 {"14.Contra3", "\x94\xb2\x03\x04\x1d", 5},
2704 {"15.Contra4", "\x94\xb2\x04\x04\x1d", 5},
2705 {"16.Select Counter file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x69", 9},
2706 {"17.Counter", "\x94\xb2\x01\x04\x1d", 5},
2707 {"18.Select SpecEv file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x40", 9},
2708 {"19.SpecEv1", "\x94\xb2\x01\x04\x1d", 5},
2712 local CLA = '94'
2713 local _calypso_cmds = {
2715 -- Break down of command bytes:
2716 -- A4 = select
2717 -- Master File 3F00
2718 -- 0x3F = master file
2719 -- 0x00 = master file id, is constant to 0x00.
2721 -- DF Dedicated File 38nn
2722 -- can be seen as directories
2723 -- 0x38
2724 -- 0xNN id
2725 -- ["01.Select ICC file"] = '0294 a4 080004 3f00 0002',
2727 -- EF Elementary File
2728 -- EF1 Pin file
2729 -- EF2 Key file
2730 -- Grey Lock file
2731 -- Electronic deposit file
2732 -- Electronic Purse file
2733 -- Electronic Transaction log file
2735 bool activate_field = true;
2736 bool leave_signal_on = true;
2737 uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 };
2739 for (int i = 0; i < ARRAYLEN(cmds); i++) {
2741 int user_timeout = -1;
2742 int resplen = 0;
2743 int res = exchange_14b_apdu(
2744 (uint8_t *)cmds[i].apdu,
2745 cmds[i].apdulen,
2746 activate_field,
2747 leave_signal_on,
2748 response,
2749 PM3_CMD_DATA_SIZE,
2750 &resplen,
2751 user_timeout
2754 if (res != PM3_SUCCESS) {
2755 PrintAndLogEx(FAILED, "sending command failed, aborting!");
2756 switch_off_field_14b();
2757 return res;
2760 uint16_t sw = get_sw(response, resplen);
2761 if (sw != ISO7816_OK) {
2762 PrintAndLogEx(ERR, "Sending command failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2763 switch_off_field_14b();
2764 return PM3_ESOFT;
2767 PrintAndLogEx(INFO, "%s - %s", cmds[i].desc, sprint_hex(response, resplen));
2768 activate_field = false;
2771 switch_off_field_14b();
2772 return PM3_SUCCESS;
2775 static int CmdHF14BMobibRead(const char *Cmd) {
2777 CLIParserContext *ctx;
2778 CLIParserInit(&ctx, "hf 14b mobib",
2779 "Reads out the contents of a ISO14443B Mobib card\n",
2780 "hf 14b mobib"
2782 void *argtable[] = {
2783 arg_param_begin,
2784 arg_param_end
2786 CLIExecWithReturn(ctx, Cmd, argtable, true);
2787 CLIParserFree(ctx);
2789 transport_14b_apdu_t cmds[] = {
2790 {"01.SELECT AID 1TIC.ICA", "\x00\xa4\x04\x00\x08\x31\x54\x49\x43\x2e\x49\x43\x41", 13},
2791 {"02.Select ICC file a", "\x00\xa4\x00\x00\x02\x3f\x00", 7},
2792 {"03.Select ICC file b", "\x00\xa4\x00\x00\x02\x00\x02", 7},
2793 {"04.ICC", "\x00\xb2\x01\x04\x1d", 5},
2794 {"05.Select Holder file", "\x00\xa4\x00\x00\x02\x3f\x1c", 7},
2795 {"06.Holder1", "\x00\xb2\x01\x04\x1d", 5},
2796 {"07.Holder2", "\x00\xb2\x02\x04\x1d", 5},
2797 {"08.Select EnvHol file a", "\x00\xa4\x00\x00\x00", 5},
2798 {"09.Select EnvHol file b", "\x00\xa4\x00\x00\x02\x20\x00", 7},
2799 {"10.Select EnvHol file c", "\x00\xa4\x00\x00\x02\x20\x01", 7},
2800 {"11.EnvHol1", "\x00\xb2\x01\x04\x1D", 5},
2801 {"11.EnvHol2", "\x00\xb2\x02\x04\x1D", 5},
2802 {"12.Select EvLog file", "\x00\xa4\x00\x00\x02\x20\x10", 7},
2803 {"13.EvLog1", "\x00\xb2\x01\x04\x1D", 5},
2804 {"14.EvLog2", "\x00\xb2\x02\x04\x1D", 5},
2805 {"15.EvLog3", "\x00\xb2\x03\x04\x1D", 5},
2806 {"16.Select ConList file", "\x00\xa4\x00\x00\x02\x20\x50", 7},
2807 {"17.ConList", "\x00\xb2\x01\x04\x1D", 5},
2808 {"18.Select Contra file", "\x00\xa4\x00\x00\x02\x20\x20", 7},
2809 {"19.Contra1", "\x00\xb2\x01\x04\x1D", 5},
2810 {"20.Contra2", "\x00\xb2\x02\x04\x1D", 5},
2811 {"21.Contra3", "\x00\xb2\x03\x04\x1D", 5},
2812 {"22.Contra4", "\x00\xb2\x04\x04\x1D", 5},
2813 {"23.Contra5", "\x00\xb2\x05\x04\x1D", 5},
2814 {"24.Contra6", "\x00\xb2\x06\x04\x1D", 5},
2815 {"25.Contra7", "\x00\xb2\x07\x04\x1D", 5},
2816 {"26.Contra8", "\x00\xb2\x08\x04\x1D", 5},
2817 {"27.Contra9", "\x00\xb2\x09\x04\x1D", 5},
2818 {"28.ContraA", "\x00\xb2\x0a\x04\x1D", 5},
2819 {"29.ContraB", "\x00\xb2\x0b\x04\x1D", 5},
2820 {"30.ContraC", "\x00\xb2\x0c\x04\x1D", 5},
2821 {"31.Select Counter file", "\x00\xa4\x00\x00\x02\x20\x69", 7},
2822 {"32.Counter", "\x00\xb2\x01\x04\x1D", 5},
2823 {"33.Select LoadLog file a", "\x00\xa4\x00\x00\x00", 5},
2824 {"34.Select LoadLog file b", "\x00\xa4\x00\x00\x02\x10\x00", 7},
2825 {"35.Select LoadLog file c", "\x00\xa4\x00\x00\x02\x10\x14", 7},
2826 {"36.LoadLog", "\x00\xb2\x01\x04\x1D", 5},
2827 {"37.Select Purcha file", "\x00\xa4\x00\x00\x02\x10\x15", 7},
2828 {"38.Purcha1", "\x00\xb2\x01\x04\x1D", 5},
2829 {"39.Purcha2", "\x00\xb2\x02\x04\x1D", 5},
2830 {"40.Purcha3", "\x00\xb2\x03\x04\x1D", 5},
2831 {"41.Select SpecEv file a", "\x00\xa4\x00\x00\x00", 5},
2832 {"42.Select SpecEv file b", "\x00\xa4\x00\x00\x02\x20\x00", 7},
2833 {"43.Select SpecEv file c", "\x00\xa4\x00\x00\x02\x20\x40", 7},
2834 {"44.SpecEv1", "\x00\xb2\x01\x04\x1D", 5},
2835 {"45.SpecEv2", "\x00\xb2\x02\x04\x1D", 5},
2836 {"46.SpecEv3", "\x00\xb2\x03\x04\x1D", 5},
2837 {"47.SpecEv4", "\x00\xb2\x04\x04\x1d", 5},
2840 bool activate_field = true;
2841 bool leave_signal_on = true;
2842 uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 };
2844 for (int i = 0; i < ARRAYLEN(cmds); i++) {
2846 int user_timeout = -1;
2847 int resplen = 0;
2848 int res = exchange_14b_apdu(
2849 (uint8_t *)cmds[i].apdu,
2850 cmds[i].apdulen,
2851 activate_field,
2852 leave_signal_on,
2853 response,
2854 PM3_CMD_DATA_SIZE,
2855 &resplen,
2856 user_timeout
2859 if (res != PM3_SUCCESS) {
2860 PrintAndLogEx(FAILED, "sending command failed, aborting!");
2861 switch_off_field_14b();
2862 return res;
2865 uint16_t sw = get_sw(response, resplen);
2866 if (sw != ISO7816_OK) {
2867 PrintAndLogEx(ERR, "Sending command failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2868 switch_off_field_14b();
2869 return PM3_ESOFT;
2872 PrintAndLogEx(INFO, "%s - %s", cmds[i].desc, sprint_hex(response, resplen));
2873 activate_field = false;
2876 switch_off_field_14b();
2877 return PM3_SUCCESS;
2880 static command_t CommandTable[] = {
2881 {"---------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("General") " -----------------------"},
2882 {"help", CmdHelp, AlwaysAvailable, "This help"},
2883 {"list", CmdHF14BList, AlwaysAvailable, "List ISO-14443-B history"},
2884 {"---------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("Operations") " -----------------------"},
2885 {"apdu", CmdHF14BAPDU, IfPm3Iso14443b, "Send ISO 14443-4 APDU to tag"},
2886 {"dump", CmdHF14BDump, IfPm3Iso14443b, "Read all memory pages of an ISO-14443-B tag, save to file"},
2887 {"info", CmdHF14Binfo, IfPm3Iso14443b, "Tag information"},
2888 {"ndefread", CmdHF14BNdefRead, IfPm3Iso14443b, "Read NDEF file on tag"},
2889 {"raw", CmdHF14BRaw, IfPm3Iso14443b, "Send raw hex data to tag"},
2890 {"rdbl", CmdHF14BSriRdBl, IfPm3Iso14443b, "Read SRI512/SRIX4 block"},
2891 {"reader", CmdHF14BReader, IfPm3Iso14443b, "Act as a ISO-14443-B reader to identify a tag"},
2892 {"restore", CmdHF14BRestore, IfPm3Iso14443b, "Restore from file to all memory pages of an ISO-14443-B tag"},
2893 {"sim", CmdHF14BSim, IfPm3Iso14443b, "Fake ISO ISO-14443-B tag"},
2894 {"sniff", CmdHF14BSniff, IfPm3Iso14443b, "Eavesdrop ISO-14443-B"},
2895 {"wrbl", CmdHF14BSriWrbl, IfPm3Iso14443b, "Write data to a SRI512/SRIX4 tag"},
2896 {"view", CmdHF14BView, AlwaysAvailable, "Display content from tag dump file"},
2897 {"valid", CmdSRIX4kValid, AlwaysAvailable, "SRIX4 checksum test"},
2898 {"---------", CmdHelp, AlwaysAvailable, "------------------ " _CYAN_("Calypso / Mobib") " ------------------"},
2899 {"calypso", CmdHF14BCalypsoRead, IfPm3Iso14443b, "Read contents of a Calypso card"},
2900 {"mobib", CmdHF14BMobibRead, IfPm3Iso14443b, "Read contents of a Mobib card"},
2901 {NULL, NULL, NULL, NULL}
2904 static int CmdHelp(const char *Cmd) {
2905 (void)Cmd; // Cmd is not used so far
2906 CmdsHelp(CommandTable);
2907 return PM3_SUCCESS;
2910 int CmdHF14B(const char *Cmd) {
2911 clearCommandBuffer();
2912 return CmdsParse(CommandTable, Cmd);
2915 // get and print all info known about any known 14b tag
2916 int infoHF14B(bool verbose, bool do_aid_search) {
2918 // try std 14b (atqb)
2919 if (HF14B_Std_Info(verbose, do_aid_search))
2920 return PM3_SUCCESS;
2922 // try ST 14b
2923 if (HF14B_ST_Info(verbose, do_aid_search))
2924 return PM3_SUCCESS;
2926 // try unknown 14b read commands (to be identified later)
2927 // could be read of calypso, CEPAS, moneo, or pico pass.
2928 if (verbose) PrintAndLogEx(FAILED, "no 14443-B tag found");
2929 return PM3_EOPABORTED;
2932 // get and print general info about all known 14b chips
2933 int readHF14B(bool loop, bool verbose, bool read_plot) {
2934 bool found = false;
2935 int res = PM3_SUCCESS;
2936 do {
2937 found = false;
2939 // try std 14b (atqb)
2940 found |= HF14B_std_reader(verbose);
2941 if (found)
2942 goto plot;
2944 // try ST Microelectronics 14b
2945 found |= HF14B_st_reader(verbose);
2946 if (found)
2947 goto plot;
2949 // Picopass
2950 found |= HF14B_picopass_reader(verbose);
2951 if (found)
2952 goto plot;
2954 // try ASK CT 14b
2955 found |= HF14B_ask_ct_reader(verbose);
2956 if (found)
2957 goto plot;
2959 // try unknown 14b read commands (to be identified later)
2960 // could be read of calypso, CEPAS, moneo, or pico pass.
2961 found |= HF14B_other_reader(verbose);
2962 if (found)
2963 goto plot;
2964 plot:
2965 if (read_plot) {
2966 res = handle_hf_plot(verbose);
2967 if (res != PM3_SUCCESS) {
2968 PrintAndLogEx(DEBUG, "plot failed");
2972 } while (loop && kbd_enter_pressed() == false);
2974 if (verbose && found == false) {
2975 PrintAndLogEx(FAILED, "no ISO 14443-B tag found");
2977 return (found) ? PM3_SUCCESS : PM3_EOPABORTED;