text
[RRG-proxmark3.git] / client / src / cmdhf14b.c
blob6817bde9a0d8e0b9b1f79d62a5434268c9cdb6dd
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 PrintAndLogEx(NORMAL, "");
470 PrintAndLogEx(INFO, "--- " _CYAN_("Fingerprint"));
471 if (memcmp(data, "\x54\x43\x4F\x53",4) == 0) {
473 int outlen = 0;
474 uint8_t out[PM3_CMD_DATA_SIZE] = {0};
475 uint8_t tcos_version[] = {0x90, 0xB2, 0x90, 0x00, 0x00};
476 if (exchange_14b_apdu(tcos_version, sizeof(tcos_version), true, false, out, PM3_CMD_DATA_SIZE, &outlen, -1) == PM3_SUCCESS) {
477 if (outlen > 2) {
478 PrintAndLogEx(SUCCESS, "Tiananxin TCOS CPU card... " _YELLOW_("%s"), sprint_ascii(out, outlen - 2));
479 } else {
480 PrintAndLogEx(SUCCESS, "Tiananxin TCOS CPU card... " _RED_("n/a"));
482 PrintAndLogEx(SUCCESS, "Magic capabilities........ most likely");
485 } else {
486 PrintAndLogEx(INFO, "n/a");
488 PrintAndLogEx(NORMAL, "");
489 return PM3_SUCCESS;
492 // get SRx chip model (from UID) // from ST Microelectronics
493 static const char *get_st_chip_model(uint8_t id) {
494 switch (id) {
495 case 0x0:
496 return "SRIX4K (Special)";
497 case 0x2:
498 return "SR176";
499 case 0x3:
500 return "SRIX4K";
501 case 0x4:
502 return "SRIX512";
503 case 0x6:
504 return "SRI512";
505 case 0x7:
506 return "SRI4K";
507 case 0xC:
508 return "SRT512";
509 default :
510 return "";
515 static const char *get_st25_chip_model(uint8_t id) {
516 switch (id) {
517 case 0x1B:
518 return "ST25TB512-AC";
519 case 0x33:
520 return "ST25TB512-AT";
521 case 0x3F:
522 return "ST25TB02K";
523 case 0x1F:
524 return "ST25TB04K";
525 default:
526 return "";
531 #define ST_LOCK_INFO_EMPTY " "
532 static const char *get_st_lock_info(uint8_t model, const uint8_t *lockbytes, uint8_t blk) {
533 if (blk > 15) {
534 return ST_LOCK_INFO_EMPTY;
537 uint8_t mask = 0;
538 switch (model) {
539 case 0x0: // SRIX4K special
540 case 0x3: // SRIx4K
541 case 0x7: { // SRI4K
542 //only need data[3]
543 switch (blk) {
544 case 7:
545 case 8:
546 mask = 0x01;
547 break;
548 case 9:
549 mask = 0x02;
550 break;
551 case 10:
552 mask = 0x04;
553 break;
554 case 11:
555 mask = 0x08;
556 break;
557 case 12:
558 mask = 0x10;
559 break;
560 case 13:
561 mask = 0x20;
562 break;
563 case 14:
564 mask = 0x40;
565 break;
566 case 15:
567 mask = 0x80;
568 break;
569 default:
570 return ST_LOCK_INFO_EMPTY;
572 if ((lockbytes[1] & mask) == 0) {
573 return _RED_("1");
575 return ST_LOCK_INFO_EMPTY;
577 case 0x4: // SRIX512
578 case 0x6: // SRI512
579 case 0xC: { // SRT512
580 //need data[2] and data[3]
581 uint8_t b = 1;
582 switch (blk) {
583 case 0:
584 mask = 0x01;
585 break;
586 case 1:
587 mask = 0x02;
588 break;
589 case 2:
590 mask = 0x04;
591 break;
592 case 3:
593 mask = 0x08;
594 break;
595 case 4:
596 mask = 0x10;
597 break;
598 case 5:
599 mask = 0x20;
600 break;
601 case 6:
602 mask = 0x40;
603 break;
604 case 7:
605 mask = 0x80;
606 break;
607 case 8:
608 mask = 0x01;
609 b = 0;
610 break;
611 case 9:
612 mask = 0x02;
613 b = 0;
614 break;
615 case 10:
616 mask = 0x04;
617 b = 0;
618 break;
619 case 11:
620 mask = 0x08;
621 b = 0;
622 break;
623 case 12:
624 mask = 0x10;
625 b = 0;
626 break;
627 case 13:
628 mask = 0x20;
629 b = 0;
630 break;
631 case 14:
632 mask = 0x40;
633 b = 0;
634 break;
635 case 15:
636 mask = 0x80;
637 b = 0;
638 break;
640 if ((lockbytes[b] & mask) == 0) {
641 return _RED_("1");
643 return ST_LOCK_INFO_EMPTY;
645 case 0x2: { // SR176
646 //need data[2]
647 switch (blk) {
648 case 0:
649 case 1:
650 mask = 0x1;
651 break;
652 case 2:
653 case 3:
654 mask = 0x2;
655 break;
656 case 4:
657 case 5:
658 mask = 0x4;
659 break;
660 case 6:
661 case 7:
662 mask = 0x8;
663 break;
664 case 8:
665 case 9:
666 mask = 0x10;
667 break;
668 case 10:
669 case 11:
670 mask = 0x20;
671 break;
672 case 12:
673 case 13:
674 mask = 0x40;
675 break;
676 case 14:
677 case 15:
678 mask = 0x80;
679 break;
681 // iceman: this is opposite! need sample to test with.
682 if ((lockbytes[0] & mask)) {
683 return _RED_("1");
685 return ST_LOCK_INFO_EMPTY;
687 default:
688 break;
690 return ST_LOCK_INFO_EMPTY;
693 static uint8_t get_st_chipid(const uint8_t *uid) {
694 return uid[5] >> 2;
698 static uint8_t get_st25_chipid(const uint8_t *uid) {
699 return uid[5];
703 static uint8_t get_st_cardsize(const uint8_t *uid) {
704 uint8_t chipid = get_st_chipid(uid);
705 switch (chipid) {
706 case 0x0:
707 case 0x3:
708 case 0x7:
709 return SR_SIZE_4K;
710 case 0x4:
711 case 0x6:
712 case 0xC:
713 return SR_SIZE_512;
714 default:
715 return 0;
721 static uint8_t get_st25_cardsize(const uint8_t *uid) {
722 uint8_t chipid = get_st25_chipid(uid);
723 switch (chipid) {
724 case 0x1B:
725 case 0x33:
726 return ST25_SIZE_512;
727 case 0x1F:
728 return ST25_SIZE_4K;
729 case 0x3F:
730 return ST25_SIZE_2K;
731 default:
732 return 0;
737 // print UID info from SRx chips (ST Microelectronics)
738 static void print_st_general_info(uint8_t *data, uint8_t len) {
739 //uid = first 8 bytes in data
740 uint8_t mfgid = data[6];
741 uint8_t chipid = get_st_chipid(data);
742 PrintAndLogEx(NORMAL, "");
743 PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s"), sprint_hex(SwapEndian64(data, 8, 8), len));
744 PrintAndLogEx(SUCCESS, " MFG: %02X, " _YELLOW_("%s"), mfgid, getTagInfo(mfgid));
745 PrintAndLogEx(SUCCESS, "Chip: %02X, " _YELLOW_("%s"), chipid, get_st_chip_model(chipid));
748 // print UID info from ASK CT chips
749 static void print_ct_general_info(void *vcard) {
750 iso14b_cts_card_select_t card;
751 memcpy(&card, (iso14b_cts_card_select_t *)vcard, sizeof(iso14b_cts_card_select_t));
753 uint32_t uid32 = MemLeToUint4byte(card.uid);
754 PrintAndLogEx(NORMAL, "");
755 PrintAndLogEx(SUCCESS, "ASK C-Ticket");
756 PrintAndLogEx(SUCCESS, " UID: " _GREEN_("%s") " ( " _YELLOW_("%010u") " )", sprint_hex(card.uid, sizeof(card.uid)), uid32);
757 PrintAndLogEx(SUCCESS, " Product Code: %02X", card.pc);
758 PrintAndLogEx(SUCCESS, " Facility Code: %02X", card.fc);
759 PrintAndLogEx(NORMAL, "");
762 static void print_hdr(void) {
763 PrintAndLogEx(NORMAL, "");
764 PrintAndLogEx(INFO, " block# | data |lck| ascii");
765 PrintAndLogEx(INFO, "---------+-------------+---+------");
768 static void print_footer(void) {
769 PrintAndLogEx(INFO, "---------+-------------+---+------");
770 PrintAndLogEx(NORMAL, "");
774 static void print_ct_blocks(uint8_t *data, size_t len) {
776 size_t blocks = len / ST25TB_SR_BLOCK_SIZE;
778 print_hdr();
780 for (int i = 0; i <= blocks; i++) {
781 PrintAndLogEx(INFO,
782 "%3d/0x%02X | %s | %s | %s",
785 sprint_hex(data + (i * 4), 4),
786 " ",
787 sprint_ascii(data + (i * 4), 4)
790 print_footer();
794 static void print_sr_blocks(uint8_t *data, size_t len, const uint8_t *uid, bool dense_output) {
796 size_t blocks = (len / ST25TB_SR_BLOCK_SIZE) - 1 ;
797 uint8_t *systemblock = data + blocks * ST25TB_SR_BLOCK_SIZE ;
798 uint8_t chipid = get_st_chipid(uid);
800 PrintAndLogEx(NORMAL, "");
801 PrintAndLogEx(INFO, "-------- " _CYAN_("%s tag memory") " ---------", get_st_chip_model(chipid));
802 PrintAndLogEx(DEBUG, "systemblock... " _YELLOW_("%s"), sprint_hex(systemblock, ST25TB_SR_BLOCK_SIZE));
803 PrintAndLogEx(DEBUG, " otp lock... " _YELLOW_("%02x %02x"), *systemblock, *(systemblock + 1));
805 print_hdr();
807 bool in_repeated_block = false;
810 for (int i = 0; i < blocks; i++) {
812 // suppress repeating blocks, truncate as such that the first and last block with the same data is shown
813 // but the blocks in between are replaced with a single line of "......" if dense_output is enabled
814 uint8_t *blk = data + (i * ST25TB_SR_BLOCK_SIZE);
815 if (dense_output &&
816 (i > 3) &&
817 (i < (blocks - 1)) &&
818 (in_repeated_block == false) &&
819 (memcmp(blk, blk - ST25TB_SR_BLOCK_SIZE, ST25TB_SR_BLOCK_SIZE) == 0) &&
820 (memcmp(blk, blk + ST25TB_SR_BLOCK_SIZE, ST25TB_SR_BLOCK_SIZE) == 0) &&
821 (memcmp(blk, blk + (ST25TB_SR_BLOCK_SIZE * 2), ST25TB_SR_BLOCK_SIZE) == 0)
823 // we're in a user block that isn't the first user block nor last two user blocks,
824 // and the current block data is the same as the previous and next two block
825 in_repeated_block = true;
826 PrintAndLogEx(INFO, " ......");
827 } else if (in_repeated_block &&
828 (memcmp(blk, blk + ST25TB_SR_BLOCK_SIZE, ST25TB_SR_BLOCK_SIZE) || i == blocks)
830 // in a repeating block, but the next block doesn't match anymore, or we're at the end block
831 in_repeated_block = false;
834 if (in_repeated_block == false) {
835 PrintAndLogEx(INFO,
836 "%3d/0x%02X | %s| %s | %s",
839 sprint_hex(data + (i * ST25TB_SR_BLOCK_SIZE), ST25TB_SR_BLOCK_SIZE),
840 get_st_lock_info(chipid, systemblock, i),
841 sprint_ascii(data + (i * ST25TB_SR_BLOCK_SIZE), ST25TB_SR_BLOCK_SIZE)
846 PrintAndLogEx(INFO,
847 "%3d/0x%02X | %s| %s | %s",
848 0xFF,
849 0xFF,
850 sprint_hex(systemblock, ST25TB_SR_BLOCK_SIZE),
851 get_st_lock_info(chipid, systemblock, 0xFF),
852 sprint_ascii(systemblock, ST25TB_SR_BLOCK_SIZE)
855 print_footer();
858 // iceman, calypso?
859 // 05 00 00 = find one tag in field
860 // 1d xx xx xx xx 00 08 01 00 = attrib xx=UID (resp 10 [f9 e0])
861 // 0200a40400 (resp 02 67 00 [29 5b])
862 // 0200a4040c07a0000002480300 (resp 02 67 00 [29 5b])
863 // 0200a4040c07a0000002480200 (resp 02 67 00 [29 5b])
864 // 0200a4040006a0000000010100 (resp 02 6a 82 [4b 4c])
865 // 0200a4040c09d27600002545500200 (resp 02 67 00 [29 5b])
866 // 0200a404000cd2760001354b414e4d30310000 (resp 02 6a 82 [4b 4c])
867 // 0200a404000ca000000063504b43532d313500 (resp 02 6a 82 [4b 4c])
868 // 0200a4040010a000000018300301000000000000000000 (resp 02 6a 82 [4b 4c])
870 static int CmdHF14BList(const char *Cmd) {
871 return CmdTraceListAlias(Cmd, "hf 14b", "14b -c");
874 static int CmdHF14BSim(const char *Cmd) {
876 CLIParserContext *ctx;
877 CLIParserInit(&ctx, "hf 14b sim",
878 "Simulate a ISO/IEC 14443 type B tag with 4 byte UID / PUPI",
879 "hf 14b sim -u 11AA33BB"
882 void *argtable[] = {
883 arg_param_begin,
884 arg_str1("u", "uid", "hex", "4byte UID/PUPI"),
885 arg_param_end
887 CLIExecWithReturn(ctx, Cmd, argtable, false);
889 uint8_t pupi[4];
890 int n = 0;
891 int res = CLIParamHexToBuf(arg_get_str(ctx, 1), pupi, sizeof(pupi), &n);
892 CLIParserFree(ctx);
894 if (res) {
895 PrintAndLogEx(FAILED, "failed to read pupi");
896 return PM3_EINVARG;
899 PrintAndLogEx(INFO, "Simulate with PUPI : " _GREEN_("%s"), sprint_hex_inrow(pupi, sizeof(pupi)));
900 PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " to abort simulation");
901 clearCommandBuffer();
902 SendCommandNG(CMD_HF_ISO14443B_SIMULATE, pupi, sizeof(pupi));
903 return PM3_SUCCESS;
906 static int CmdHF14BSniff(const char *Cmd) {
908 CLIParserContext *ctx;
909 CLIParserInit(&ctx, "hf 14b sniff",
910 "Sniff the communication between reader and tag\n"
911 "Use `hf 14b list` to view collected data.",
912 "hf 14b sniff"
915 void *argtable[] = {
916 arg_param_begin,
917 arg_param_end
919 CLIExecWithReturn(ctx, Cmd, argtable, true);
920 CLIParserFree(ctx);
922 PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " to abort sniffing");
924 PacketResponseNG resp;
925 clearCommandBuffer();
926 SendCommandNG(CMD_HF_ISO14443B_SNIFF, NULL, 0);
927 WaitForResponse(CMD_HF_ISO14443B_SNIFF, &resp);
928 PrintAndLogEx(HINT, "Try `" _YELLOW_("hf 14b list") "` to view captured tracelog");
929 PrintAndLogEx(HINT, "Try `" _YELLOW_("trace save -h") "` to save tracelog for later analysing");
930 return PM3_SUCCESS;
933 static int CmdHF14BRaw(const char *Cmd) {
934 CLIParserContext *ctx;
935 CLIParserInit(&ctx, "hf 14b raw",
936 "Sends raw bytes to card. Activates field by default",
937 "hf 14b raw -cks --data 0200a40400 -> standard select, apdu 0200a4000 (7816)\n"
938 "hf 14b raw -ck --sr --data 0200a40400 -> SRx select\n"
939 "hf 14b raw -ck --cts --data 0200a40400 -> C-ticket select\n"
942 void *argtable[] = {
943 arg_param_begin,
944 arg_lit0("a", NULL, "active signal field ON without select"),
945 arg_lit0("c", "crc", "calculate and append CRC"),
946 arg_lit0("k", "keep", "leave the signal field ON after receive response"),
948 arg_str0("d", "data", "<hex>", "data, bytes to send"),
949 arg_lit0("r", NULL, "do not read response from card"),
950 arg_int0("t", "timeout", "<dec>", "timeout in ms"),
952 arg_lit0("s", "std", "use ISO14B select"),
953 arg_lit0(NULL, "sr", "use SRx ST select"),
954 arg_lit0(NULL, "cts", "use ASK C-ticket select"),
955 arg_lit0(NULL, "xrx", "use Fuji/Xerox select"),
956 arg_lit0(NULL, "pico", "use Picopass select"),
958 arg_lit0("v", "verbose", "verbose output"),
959 arg_param_end
961 CLIExecWithReturn(ctx, Cmd, argtable, false);
963 bool activate_field = arg_get_lit(ctx, 1);
964 bool add_crc = arg_get_lit(ctx, 2);
965 bool keep_field_on = arg_get_lit(ctx, 3);
967 uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
968 int datalen = 0;
969 CLIParamHexToBuf(arg_get_str(ctx, 4), data, sizeof(data), &datalen);
971 bool read_reply = (arg_get_lit(ctx, 5) == false);
972 int user_timeout = arg_get_int_def(ctx, 6, -1);
973 bool select_std = arg_get_lit(ctx, 7);
974 bool select_sr = arg_get_lit(ctx, 8);
975 bool select_cts = arg_get_lit(ctx, 9);
976 bool select_xrx = arg_get_lit(ctx, 10);
977 bool select_pico = arg_get_lit(ctx, 11);
978 bool verbose = arg_get_lit(ctx, 12);
979 CLIParserFree(ctx);
981 // FLAGS for device side
982 uint32_t flags = 0;
984 if (activate_field) {
985 flags |= ISO14B_CONNECT;
988 if (add_crc) {
989 flags |= ISO14B_APPEND_CRC;
992 if (select_std) {
993 flags |= (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_CLEARTRACE);
994 if (verbose) {
995 PrintAndLogEx(INFO, "using ISO14443-B select");
997 } else if (select_sr) {
998 flags |= (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_CLEARTRACE);
999 if (verbose) {
1000 PrintAndLogEx(INFO, "using ST/SRx select");
1002 } else if (select_cts) {
1003 flags |= (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_CLEARTRACE);
1004 if (verbose) {
1005 PrintAndLogEx(INFO, "using ASK/C-ticket select");
1007 } else if (select_xrx) {
1008 flags |= (ISO14B_CONNECT | ISO14B_SELECT_XRX | ISO14B_CLEARTRACE);
1009 if (verbose) {
1010 PrintAndLogEx(INFO, "using Fuji/Xerox select");
1012 } else if (select_pico) {
1013 flags |= (ISO14B_CONNECT | ISO14B_SELECT_PICOPASS | ISO14B_CLEARTRACE);
1014 if (verbose) {
1015 PrintAndLogEx(INFO, "using Picopass select");
1019 uint32_t time_wait = 0;
1020 if (user_timeout > 0) {
1022 flags |= ISO14B_SET_TIMEOUT;
1024 if (user_timeout > MAX_14B_TIMEOUT_MS) {
1025 user_timeout = MAX_14B_TIMEOUT_MS;
1026 PrintAndLogEx(INFO, "set timeout to 4.9 seconds. The max we can wait for response");
1029 // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us)
1030 time_wait = (uint32_t)((13560 / 128) * user_timeout);
1031 if (verbose)
1032 PrintAndLogEx(INFO, " new raw timeout : %u ETU ( %u ms )", time_wait, user_timeout);
1035 if (keep_field_on == false) {
1036 flags |= ISO14B_DISCONNECT;
1039 if (datalen > 0) {
1040 flags |= ISO14B_RAW;
1043 // Max buffer is PM3_CMD_DATA_SIZE
1044 datalen = (datalen > PM3_CMD_DATA_SIZE) ? PM3_CMD_DATA_SIZE : datalen;
1046 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + datalen);
1047 if (packet == NULL) {
1048 PrintAndLogEx(FAILED, "failed to allocate memory");
1049 return PM3_EMALLOC;
1052 packet->flags = flags;
1053 packet->timeout = time_wait;
1054 packet->rawlen = datalen;
1055 memcpy(packet->raw, data, datalen);
1057 clearCommandBuffer();
1058 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1059 free(packet);
1061 if (read_reply == false) {
1062 clearCommandBuffer();
1063 return PM3_SUCCESS;
1066 bool success = true;
1068 // Select, device will send back iso14b_card_select_t, don't print it.
1069 if (select_std) {
1070 success = wait_cmd_14b(verbose, true, user_timeout);
1071 if (verbose && success) {
1072 PrintAndLogEx(SUCCESS, "Got response for standard select");
1076 if (select_sr) {
1077 success = wait_cmd_14b(verbose, true, user_timeout);
1078 if (verbose && success) {
1079 PrintAndLogEx(SUCCESS, "Got response for ST/SRx select");
1083 if (select_cts) {
1084 success = wait_cmd_14b(verbose, true, user_timeout);
1085 if (verbose && success) {
1086 PrintAndLogEx(SUCCESS, "Got response for ASK/C-ticket select");
1090 if (select_xrx) {
1091 success = wait_cmd_14b(verbose, true, user_timeout);
1092 if (verbose && success) {
1093 PrintAndLogEx(SUCCESS, "Got response for Fuji/Xerox select");
1097 if (select_pico) {
1098 success = wait_cmd_14b(verbose, true, user_timeout);
1099 if (verbose && success) {
1100 PrintAndLogEx(SUCCESS, "Got response for Picopass select");
1104 // get back response from the raw bytes you sent.
1105 if (success && datalen > 0) {
1106 wait_cmd_14b(true, false, user_timeout);
1109 return PM3_SUCCESS;
1112 // 14b get and print Full Info (as much as we know)
1113 static bool HF14B_Std_Info(bool verbose, bool do_aid_search) {
1114 // 14b get and print UID only (general info)
1115 iso14b_raw_cmd_t packet = {
1116 .flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT),
1117 .timeout = 0,
1118 .rawlen = 0,
1121 clearCommandBuffer();
1122 PacketResponseNG resp;
1123 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1124 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1125 if (verbose) {
1126 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1128 switch_off_field_14b();
1129 return false;
1132 switch (resp.status) {
1133 case PM3_SUCCESS: {
1135 iso14b_card_select_t card;
1136 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1138 PrintAndLogEx(NORMAL, "");
1139 PrintAndLogEx(INFO, "--- " _CYAN_("Tag Information") " ---------------------------");
1140 PrintAndLogEx(SUCCESS, " UID : " _GREEN_("%s"), sprint_hex(card.uid, card.uidlen));
1141 PrintAndLogEx(SUCCESS, " ATQB : %s", sprint_hex(card.atqb, sizeof(card.atqb)));
1142 PrintAndLogEx(SUCCESS, " CHIPID : %02X", card.chipid);
1143 print_atqb_resp(card.atqb, card.cid);
1145 if (do_aid_search) {
1146 hf14b_aid_search(verbose);
1149 return true;
1151 case PM3_ELENGTH:
1152 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 STD ATTRIB fail");
1153 break;
1154 case PM3_ECRC:
1155 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 STD CRC fail");
1156 break;
1157 default:
1158 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b STD select failed");
1159 break;
1162 return false;
1165 // SRx get and print full info (needs more info...)
1166 static bool HF14B_ST_Info(bool verbose, bool do_aid_search) {
1168 iso14b_raw_cmd_t packet = {
1169 .flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT),
1170 .timeout = 0,
1171 .rawlen = 0,
1174 clearCommandBuffer();
1175 PacketResponseNG resp;
1176 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1177 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1178 if (verbose) {
1179 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1181 return false;
1184 if (resp.status != PM3_SUCCESS) {
1185 return false;
1188 iso14b_card_select_t card;
1189 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1191 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1192 if ((card.uidlen != 8) || (memcmp(card.uid, empty, card.uidlen) == 0)) {
1193 return false;
1196 print_st_general_info(card.uid, card.uidlen);
1198 if (do_aid_search) {
1199 hf14b_aid_search(verbose);
1201 return true;
1204 // menu command to get and print all info known about any known 14b tag
1205 static int CmdHF14Binfo(const char *Cmd) {
1206 CLIParserContext *ctx;
1207 CLIParserInit(&ctx, "hf 14b info",
1208 "Tag information for ISO/IEC 14443 type B based tags",
1209 "hf 14b info\n"
1212 void *argtable[] = {
1213 arg_param_begin,
1214 arg_lit0("s", "aidsearch", "checks if AIDs from aidlist.json is present on the card and prints information about found AIDs"),
1215 arg_lit0("v", "verbose", "verbose output"),
1216 arg_param_end
1218 CLIExecWithReturn(ctx, Cmd, argtable, true);
1219 bool do_aid_search = arg_get_lit(ctx, 1);
1220 bool verbose = arg_get_lit(ctx, 2);
1221 CLIParserFree(ctx);
1222 return infoHF14B(verbose, do_aid_search);
1225 // #define ISO14443B_READ_BLK 0x08
1226 // #define ISO14443B_WRITE_BLK 0x09
1228 static int read_sr_block(uint8_t blockno, uint8_t *out) {
1229 struct {
1230 uint8_t blockno;
1231 } PACKED payload;
1233 payload.blockno = blockno;
1235 PacketResponseNG resp;
1236 clearCommandBuffer();
1237 SendCommandNG(CMD_HF_SRI_READ, (uint8_t *)&payload, sizeof(payload));
1238 if (WaitForResponseTimeout(CMD_HF_SRI_READ, &resp, TIMEOUT) == false) {
1239 return PM3_ETIMEOUT;
1242 if (resp.status == PM3_SUCCESS && out) {
1243 memcpy(out, resp.data.asBytes, resp.length);
1245 return resp.status;
1248 static int write_sr_block(uint8_t blockno, uint8_t datalen, uint8_t *data) {
1250 uint8_t psize = sizeof(iso14b_raw_cmd_t) + datalen + 2;
1251 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, psize);
1252 if (packet == NULL) {
1253 PrintAndLogEx(FAILED, "failed to allocate memory");
1254 return PM3_EMALLOC;
1257 packet->flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_RAW | ISO14B_APPEND_CRC | ISO14B_DISCONNECT);
1258 packet->timeout = 0;
1259 packet->rawlen = 6;
1260 packet->raw[0] = ISO14443B_WRITE_BLK;
1261 packet->raw[1] = blockno;
1262 packet->raw[2] = data[0];
1263 packet->raw[3] = data[1];
1264 packet->raw[4] = data[2];
1265 packet->raw[5] = data[3];
1267 // SRx get and print general info about SRx chip from UID
1268 clearCommandBuffer();
1269 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, psize);
1270 free(packet);
1272 if (wait_14b_response(true, NULL, NULL) == false) {
1273 PrintAndLogEx(FAILED, "SRx write block ( " _RED_("failed") " )");
1274 return PM3_ESOFT;
1276 return PM3_SUCCESS;
1279 static bool HF14B_st_reader(bool verbose) {
1281 iso14b_raw_cmd_t packet = {
1282 .flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT),
1283 .timeout = 0,
1284 .rawlen = 0,
1287 // SRx get and print general info about SRx chip from UID
1288 clearCommandBuffer();
1289 PacketResponseNG resp;
1290 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1291 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1292 if (verbose) {
1293 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1295 return false;
1298 switch (resp.status) {
1299 case PM3_SUCCESS: {
1300 iso14b_card_select_t card;
1301 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1303 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1304 if ((card.uidlen != 8) || (memcmp(card.uid, empty, card.uidlen) == 0)) {
1305 return false;
1307 print_st_general_info(card.uid, card.uidlen);
1308 return true;
1310 case PM3_ELENGTH:
1311 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ST ATTRIB fail");
1312 break;
1313 case PM3_ECRC:
1314 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ST CRC fail");
1315 break;
1316 case PM3_EWRONGANSWER:
1317 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ST random chip id fail");
1318 break;
1319 default:
1320 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b ST select SRx failed");
1321 break;
1323 return false;
1326 static bool HF14B_std_reader(bool verbose) {
1327 iso14b_raw_cmd_t packet = {
1328 .flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT),
1329 .timeout = 0,
1330 .rawlen = 0,
1333 // 14b get and print UID only (general info)
1334 clearCommandBuffer();
1335 PacketResponseNG resp;
1336 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1337 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1338 if (verbose) {
1339 PrintAndLogEx(WARNING, "timeout while waiting for reply");
1341 return false;
1344 switch (resp.status) {
1345 case PM3_SUCCESS: {
1346 iso14b_card_select_t card;
1347 memcpy(&card, (iso14b_card_select_t *)resp.data.asBytes, sizeof(iso14b_card_select_t));
1349 uint8_t empty[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
1350 if (memcmp(card.uid, empty, card.uidlen) == 0) {
1351 return false;
1353 PrintAndLogEx(NORMAL, "");
1354 PrintAndLogEx(SUCCESS, " UID : " _GREEN_("%s"), sprint_hex(card.uid, card.uidlen));
1355 PrintAndLogEx(SUCCESS, " ATQB : %s", sprint_hex(card.atqb, sizeof(card.atqb)));
1356 PrintAndLogEx(SUCCESS, " CHIPID : %02X", card.chipid);
1357 print_atqb_resp(card.atqb, card.cid);
1358 return true;
1360 case PM3_ELENGTH: {
1361 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ATTRIB fail");
1362 break;
1364 case PM3_ECRC: {
1365 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail");
1366 break;
1368 default: {
1369 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b card select failed");
1370 break;
1373 return false;
1376 static bool HF14B_ask_ct_reader(bool verbose) {
1378 iso14b_raw_cmd_t packet = {
1379 .flags = (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_DISCONNECT),
1380 .timeout = 0,
1381 .rawlen = 0,
1384 // 14b get and print UID only (general info)
1385 clearCommandBuffer();
1386 PacketResponseNG resp;
1387 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1388 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1389 if (verbose) PrintAndLogEx(WARNING, "timeout while waiting for reply");
1390 return false;
1393 switch (resp.status) {
1394 case PM3_SUCCESS: {
1395 print_ct_general_info(resp.data.asBytes);
1396 return true;
1398 case PM3_ELENGTH: {
1399 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CTS wrong length");
1400 break;
1402 case PM3_ECRC: {
1403 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CTS CRC fail");
1404 break;
1406 default: {
1407 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b CTS select failed");
1408 break;
1411 return false;
1414 static bool HF14B_picopass_reader(bool verbose) {
1416 iso14b_raw_cmd_t packet = {
1417 .flags = (ISO14B_CONNECT | ISO14B_SELECT_PICOPASS | ISO14B_DISCONNECT),
1418 .timeout = 0,
1419 .rawlen = 0,
1422 // 14b get and print UID only (general info)
1423 clearCommandBuffer();
1424 PacketResponseNG resp;
1425 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
1426 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
1427 if (verbose) PrintAndLogEx(WARNING, "timeout while waiting for reply");
1428 return false;
1431 switch (resp.status) {
1432 case PM3_SUCCESS: {
1434 picopass_hdr_t *card = calloc(1, sizeof(picopass_hdr_t));
1435 if (card == NULL) {
1436 PrintAndLogEx(FAILED, "failed to allocate memory");
1437 return false;
1439 memcpy(card, resp.data.asBytes, sizeof(picopass_hdr_t));
1440 PrintAndLogEx(NORMAL, "");
1441 PrintAndLogEx(SUCCESS, "iCLASS / Picopass CSN: " _GREEN_("%s"), sprint_hex(card->csn, sizeof(card->csn)));
1442 free(card);
1443 return true;
1445 case PM3_ELENGTH: {
1446 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 wrong length");
1447 break;
1449 case PM3_ECRC: {
1450 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail");
1451 break;
1453 default: {
1454 if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b Picopass select failed");
1455 break;
1458 return false;
1461 // test for other 14b type tags (mimic another reader - don't have tags to identify)
1462 static bool HF14B_other_reader(bool verbose) {
1464 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + 4);
1465 if (packet == NULL) {
1466 PrintAndLogEx(FAILED, "failed to allocate memory");
1467 return false;
1469 packet->flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_RAW | ISO14B_APPEND_CRC);
1470 packet->timeout = 0;
1471 packet->rawlen = 4;
1472 memcpy(packet->raw, "\x00\x0b\x3f\x80", 4);
1474 // 14b get and print UID only (general info)
1476 clearCommandBuffer();
1477 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1479 // wait for the select message and wait for response
1480 if (wait_14b_response(false, NULL, NULL)) {
1481 PrintAndLogEx(SUCCESS, "\n14443-3b tag found:");
1482 PrintAndLogEx(SUCCESS, "unknown tag type answered to a " _YELLOW_("0x000b3f80") " command");
1483 switch_off_field_14b();
1484 free(packet);
1485 return true;
1488 packet->rawlen = 1;
1489 packet->raw[0] = ISO14443B_AUTHENTICATE;
1490 clearCommandBuffer();
1491 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1493 if (wait_14b_response(false, NULL, NULL)) {
1494 PrintAndLogEx(SUCCESS, "\n14443-3b tag found:");
1495 PrintAndLogEx(SUCCESS, "Unknown tag type answered to a " _YELLOW_("0x0A") " command");
1496 switch_off_field_14b();
1497 free(packet);
1498 return true;
1501 packet->raw[0] = ISO14443B_RESET;
1502 clearCommandBuffer();
1503 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
1504 free(packet);
1505 if (wait_14b_response(false, NULL, NULL)) {
1506 PrintAndLogEx(SUCCESS, "\n14443-3b tag found:");
1507 PrintAndLogEx(SUCCESS, "Unknown tag type answered to a " _YELLOW_("0x0C") " command");
1508 switch_off_field_14b();
1509 return true;
1512 switch_off_field_14b();
1513 return false;
1516 // menu command to get and print general info about all known 14b chips
1517 static int CmdHF14BReader(const char *Cmd) {
1518 CLIParserContext *ctx;
1519 CLIParserInit(&ctx, "hf 14b reader",
1520 "Act as a 14443B reader to identify a tag",
1521 "hf 14b reader\n"
1522 "hf 14b reader -@ -> continuous reader mode"
1525 void *argtable[] = {
1526 arg_param_begin,
1527 arg_lit0(NULL, "plot", "show anticollision signal trace in plot window"),
1528 arg_lit0("v", "verbose", "verbose output"),
1529 arg_lit0("@", NULL, "optional - continuous reader mode"),
1530 arg_param_end
1532 CLIExecWithReturn(ctx, Cmd, argtable, true);
1533 bool read_plot = arg_get_lit(ctx, 1);
1534 bool verbose = arg_get_lit(ctx, 2);
1535 bool cm = arg_get_lit(ctx, 3);
1536 CLIParserFree(ctx);
1538 if (cm) {
1539 PrintAndLogEx(INFO, "Press " _GREEN_("<Enter>") " to exit");
1542 clear_trace_14b();
1544 return readHF14B(cm, verbose, read_plot);
1547 // Read SRI512|SRIX4K block
1548 static int CmdHF14BSriRdBl(const char *Cmd) {
1550 CLIParserContext *ctx;
1551 CLIParserInit(&ctx, "hf 14b rdbl",
1552 "Read SRI512 | SRIX4K block",
1553 "hf 14b rdbl -b 06\n"
1556 void *argtable[] = {
1557 arg_param_begin,
1558 arg_int0("b", "block", "<dec>", "block number"),
1559 arg_param_end
1561 CLIExecWithReturn(ctx, Cmd, argtable, false);
1562 int blockno = arg_get_int_def(ctx, 1, -1);
1563 CLIParserFree(ctx);
1566 iso14b_card_select_t card;
1567 if (get_14b_UID(&card) == false) {
1568 PrintAndLogEx(WARNING, "no tag found");
1569 return PM3_SUCCESS;
1572 if (card.uidlen != 8) {
1573 PrintAndLogEx(FAILED, "current read command only work with SRI4K / SRI512 tags");
1574 return PM3_SUCCESS;
1577 // detect cardsize
1578 // 1 = 4096
1579 // 2 = 512
1580 uint8_t cardtype = get_st_cardsize(card.uid);
1581 uint8_t blocks = (cardtype == 1) ? 0x7F : 0x0F;
1584 uint8_t out[4] = {0};
1585 int status = read_sr_block(blockno, out);
1586 if (status == PM3_SUCCESS) {
1587 PrintAndLogEx(SUCCESS, "block %02u... " _GREEN_("%s") " | " _GREEN_("%s"), blockno, sprint_hex(out, sizeof(out)), sprint_ascii(out, sizeof(out)));
1589 return status;
1592 // New command to write a SRI512/SRIX4K tag.
1593 static int CmdHF14BSriWrbl(const char *Cmd) {
1595 * For SRIX4K blocks 00 - 7F
1596 * hf 14b raw --sr -c --data [09 $srix4kwblock $srix4kwdata
1598 * For SR512 blocks 00 - 0F
1599 * hf 14b raw --sr -c --data [09 $sr512wblock $sr512wdata]
1601 * Special block FF = otp_lock_reg block.
1602 * Data len 4 bytes-
1605 CLIParserContext *ctx;
1606 CLIParserInit(&ctx, "hf 14b wrbl",
1607 "Write data to a SRI512 or SRIX4K block\n"
1608 "If writing to a block out-of-range, use `--force` to override checks\n"
1609 "Special block at end denots OTP and lock bits among others",
1610 "hf 14b wrbl --4k -b 100 -d 11223344\n"
1611 "hf 14b wrbl --4k --sb -d 11223344 --> special block write\n"
1612 "hf 14b wrbl --512 -b 15 -d 11223344\n"
1613 "hf 14b wrbl --512 --sb -d 11223344 --> special block write\n"
1616 void *argtable[] = {
1617 arg_param_begin,
1618 arg_int0("b", "block", "<dec>", "block number"),
1619 arg_str1("d", "data", "<hex>", "4 hex bytes"),
1620 arg_lit0(NULL, "512", "target SRI 512 tag"),
1621 arg_lit0(NULL, "4k", "target SRIX 4k tag (def)"),
1622 arg_lit0(NULL, "sb", "special block write at end of memory (0xFF)"),
1623 arg_lit0(NULL, "force", "overrides block range checks"),
1624 arg_param_end
1626 CLIExecWithReturn(ctx, Cmd, argtable, false);
1627 int blockno = arg_get_int_def(ctx, 1, -1);
1628 int dlen = 0;
1629 uint8_t data[4] = {0, 0, 0, 0};
1630 int res = CLIParamHexToBuf(arg_get_str(ctx, 2), data, sizeof(data), &dlen);
1631 if (res) {
1632 CLIParserFree(ctx);
1633 return PM3_EINVARG;
1636 bool use_sri512 = arg_get_lit(ctx, 3);
1637 bool use_srix4k = arg_get_lit(ctx, 4);
1638 bool special = arg_get_lit(ctx, 5);
1639 bool override = arg_get_lit(ctx, 6);
1640 CLIParserFree(ctx);
1642 if (dlen != sizeof(data)) {
1643 PrintAndLogEx(FAILED, "data must be 4 hex bytes, got %d", dlen);
1644 return PM3_EINVARG;
1647 if (use_sri512 + use_srix4k > 1) {
1648 PrintAndLogEx(FAILED, "Select only one card type");
1649 return PM3_EINVARG;
1652 // Set default
1653 if (use_sri512 == false) {
1654 use_srix4k = true;
1657 if (use_srix4k && blockno > 0x7F) {
1658 PrintAndLogEx(FAILED, "block number out of range, max 127 (0x7F), got " _RED_("%u"), blockno);
1659 if (override) {
1660 PrintAndLogEx(INFO, "overriding block check");
1661 } else {
1662 return PM3_EINVARG;
1666 if (use_sri512 && blockno > 0x0F) {
1667 PrintAndLogEx(FAILED, "block number out of range, max 15 (0x0F), got " _RED_("%u"), blockno);
1668 if (override) {
1669 PrintAndLogEx(INFO, "overriding block check");
1670 } else {
1671 return PM3_EINVARG;
1675 // special block at end of memory
1676 if (special) {
1677 blockno = 0xFF;
1678 PrintAndLogEx(SUCCESS, _YELLOW_("%s") " Write special block %02X - " _YELLOW_("%s"),
1679 (use_srix4k) ? "SRIX4K" : "SRI512",
1680 blockno,
1681 sprint_hex(data, sizeof(data))
1683 } else {
1684 PrintAndLogEx(SUCCESS, _YELLOW_("%s") " Write block %02X - " _YELLOW_("%s"),
1685 (use_srix4k) ? "SRIX4K" : "SRI512",
1686 blockno,
1687 sprint_hex(data, sizeof(data))
1691 int status = write_sr_block(blockno, ST25TB_SR_BLOCK_SIZE, data);
1692 if (status != PM3_SUCCESS) {
1693 return status;
1696 // verify
1697 uint8_t out[4] = {0};
1698 status = read_sr_block(blockno, out);
1699 if (status == PM3_SUCCESS) {
1700 if (memcmp(data, out, 4) == 0) {
1701 PrintAndLogEx(SUCCESS, "SRx write block ( " _GREEN_("ok") " )");
1703 } else {
1704 PrintAndLogEx(INFO, "Verifying block ( " _RED_("failed") " )");
1706 return status;
1709 // need to write to file
1710 static int CmdHF14BDump(const char *Cmd) {
1712 CLIParserContext *ctx;
1713 CLIParserInit(&ctx, "hf 14b dump",
1714 "This command dumps the contents of a ISO-14443-B tag and save it to file\n"
1715 "Tries to autodetect cardtype, memory size defaults to SRI4K",
1716 "hf 14b dump\n"
1717 "hf 14b dump -f myfilename\n"
1720 void *argtable[] = {
1721 arg_param_begin,
1722 arg_str0("f", "file", "<fn>", "(optional) filename, if no <name> UID will be used as filename"),
1723 arg_lit0(NULL, "ns", "no save to file"),
1724 arg_lit0("z", "dense", "dense dump output style"),
1725 arg_param_end
1727 CLIExecWithReturn(ctx, Cmd, argtable, true);
1729 int fnlen = 0;
1730 char filename[FILE_PATH_SIZE] = {0};
1731 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
1732 bool nosave = arg_get_lit(ctx, 2);
1733 bool dense_output = (g_session.dense_output || arg_get_lit(ctx, 3));
1734 CLIParserFree(ctx);
1737 uint8_t select[sizeof(iso14b_card_select_t)] = {0};
1738 iso14b_type_t select_cardtype = ISO14B_NONE;
1739 if (get_14b_UID(select, &select_cardtype) == false) {
1740 PrintAndLogEx(WARNING, "no tag found");
1741 return PM3_SUCCESS;
1744 if (select_cardtype == ISO14B_CT) {
1745 iso14b_cts_card_select_t ct_card;
1746 memcpy(&ct_card, (iso14b_cts_card_select_t *)&select, sizeof(iso14b_cts_card_select_t));
1748 uint32_t uid32 = MemLeToUint4byte(ct_card.uid);
1749 PrintAndLogEx(SUCCESS, "UID: " _GREEN_("%s") " ( " _YELLOW_("%010u") " )", sprint_hex(ct_card.uid, 4), uid32);
1751 // Have to figure out how large one of these are..
1752 PrintAndLogEx(FAILED, "Dumping CT tags is not implemented yet.");
1754 // print_ct_blocks(data, cardsize);
1755 return switch_off_field_14b();
1758 if (select_cardtype == ISO14B_STANDARD) {
1759 // Have to figure out how large one of these are..
1760 PrintAndLogEx(FAILED, "Dumping Standard ISO14443-B tags is not implemented yet.");
1761 // print_std_blocks(data, cardsize);
1762 return switch_off_field_14b();
1765 if (select_cardtype == ISO14B_SR) {
1766 iso14b_card_select_t card;
1767 memcpy(&card, (iso14b_card_select_t *)&select, sizeof(iso14b_card_select_t));
1769 // detect cardsize
1770 // 1 = 4096
1771 // 2 = 512
1772 uint8_t cardtype = get_st_cardsize(card.uid);
1773 uint8_t lastblock = 0;
1774 uint16_t cardsize = 0;
1776 switch (cardtype) {
1777 case SR_SIZE_512:
1778 cardsize = (512 / 8) + ST25TB_SR_BLOCK_SIZE;
1779 lastblock = 0x0F;
1780 break;
1781 case SR_SIZE_4K:
1782 default:
1783 cardsize = (4096 / 8) + ST25TB_SR_BLOCK_SIZE;
1784 lastblock = 0x7F;
1785 break;
1788 uint8_t chipid = get_st_chipid(card.uid);
1789 PrintAndLogEx(SUCCESS, "found a " _GREEN_("%s") " tag", get_st_chip_model(chipid));
1791 // detect blocksize from card :)
1792 PrintAndLogEx(INFO, "reading tag memory");
1794 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + 2);
1795 if (packet == NULL) {
1796 PrintAndLogEx(FAILED, "failed to allocate memory");
1797 return PM3_EMALLOC;
1799 packet->flags = (ISO14B_CONNECT | ISO14B_SELECT_SR);
1800 packet->timeout = 0;
1801 packet->rawlen = 0;
1803 clearCommandBuffer();
1804 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t));
1805 PacketResponseNG resp;
1807 // select SR tag
1808 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, 2000)) {
1809 if (resp.status != PM3_SUCCESS) {
1810 PrintAndLogEx(FAILED, "failed to select ( " _RED_("%d") " )", resp.status);
1811 free(packet);
1812 return switch_off_field_14b();
1816 PrintAndLogEx(INFO, "." NOLF);
1818 uint8_t data[cardsize];
1819 memset(data, 0, sizeof(data));
1820 uint16_t blocknum = 0;
1822 for (int retry = 0; retry < 3; retry++) {
1824 // set up the read command
1825 packet->flags = (ISO14B_APPEND_CRC | ISO14B_RAW);
1826 packet->rawlen = 2;
1827 packet->raw[0] = ISO14443B_READ_BLK;
1828 packet->raw[1] = blocknum & 0xFF;
1830 clearCommandBuffer();
1831 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + 2);
1832 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, 2000)) {
1834 if (resp.status != PM3_SUCCESS) {
1835 PrintAndLogEx(FAILED, "retrying one more time");
1836 continue;
1839 uint8_t *recv = resp.data.asBytes;
1841 if (check_crc(CRC_14443_B, recv, resp.length) == false) {
1842 PrintAndLogEx(FAILED, "crc fail, retrying one more time");
1843 continue;
1846 // last read
1847 if (blocknum == 0xFF) {
1848 // we reserved space for this block after 0x0F and 0x7F, ie 0x10, 0x80
1849 memcpy(data + ((lastblock + 1) * ST25TB_SR_BLOCK_SIZE), recv, ST25TB_SR_BLOCK_SIZE);
1850 break;
1852 memcpy(data + (blocknum * ST25TB_SR_BLOCK_SIZE), recv, ST25TB_SR_BLOCK_SIZE);
1855 retry = 0;
1856 blocknum++;
1857 if (blocknum > lastblock) {
1858 // read config block
1859 blocknum = 0xFF;
1862 PrintAndLogEx(NORMAL, "." NOLF);
1863 fflush(stdout);
1866 free(packet);
1868 PrintAndLogEx(NORMAL, "");
1869 switch_off_field_14b();
1871 if (blocknum != 0xFF) {
1872 PrintAndLogEx(FAILED, "dump failed");
1873 return PM3_ESOFT;
1876 print_sr_blocks(data, cardsize, card.uid, dense_output);
1878 if (nosave) {
1879 PrintAndLogEx(INFO, "Called with no save option");
1880 PrintAndLogEx(NORMAL, "");
1881 return PM3_SUCCESS;
1884 // save to file
1885 if (fnlen < 1) {
1886 PrintAndLogEx(INFO, "using UID as filename");
1887 char *fptr = filename + snprintf(filename, sizeof(filename), "hf-14b-");
1888 FillFileNameByUID(fptr, SwapEndian64(card.uid, card.uidlen, 8), "-dump", card.uidlen);
1891 size_t datalen = (lastblock + 2) * ST25TB_SR_BLOCK_SIZE;
1892 pm3_save_dump(filename, data, datalen, jsf14b_v2);
1895 return PM3_ESOFT;
1898 static int CmdHF14BRestore(const char *Cmd) {
1900 CLIParserContext *ctx;
1901 CLIParserInit(&ctx, "hf 14b restore",
1902 "Restore data from (bin/eml/json) dump file to tag\n"
1903 "If the dump file includes the special block at the end it will be ignored\n",
1904 "hf 14b restore --4k -f myfilename\n"
1905 "hf 14b restore --512 -f myfilename\n"
1908 void *argtable[] = {
1909 arg_param_begin,
1910 arg_str0("f", "file", "<fn>", "(optional) filename, if no <name> UID will be used as filename"),
1911 arg_lit0(NULL, "512", "target SRI 512 tag"),
1912 arg_lit0(NULL, "4k", "target SRIX 4k tag (def)"),
1913 arg_param_end
1915 CLIExecWithReturn(ctx, Cmd, argtable, true);
1917 int fnlen = 0;
1918 char filename[FILE_PATH_SIZE] = {0};
1919 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
1920 bool use_sri512 = arg_get_lit(ctx, 2);
1921 bool use_srix4k = arg_get_lit(ctx, 3);
1922 CLIParserFree(ctx);
1924 if (use_sri512 + use_srix4k > 1) {
1925 PrintAndLogEx(FAILED, "Select only one card type");
1926 return PM3_EINVARG;
1929 // Set default
1930 if (use_sri512 == false) {
1931 use_srix4k = true;
1934 char s[7];
1935 memset(s, 0, sizeof(s));
1936 uint16_t block_cnt = 0;
1937 if (use_sri512) {
1938 block_cnt = 16;
1939 memcpy(s, "SRI512", 7);
1940 } else if (use_srix4k) {
1941 block_cnt = 128;
1942 memcpy(s, "SRIX4K", 7);
1945 // reserve memory
1946 uint8_t *data = NULL;
1947 size_t bytes_read = 0;
1948 int res = pm3_load_dump(filename, (void **)&data, &bytes_read, (ST25TB_SR_BLOCK_SIZE * block_cnt));
1949 if (res != PM3_SUCCESS) {
1950 PrintAndLogEx(FAILED, "Failed to load file");
1951 return res;
1954 // Ignore remaining block if the file is 1 block larger than the expected size
1955 // (because hf 14b dump also saves the special block at the end of the memory, it will be ignored by the restore command)
1956 if (bytes_read != (block_cnt * ST25TB_SR_BLOCK_SIZE) && bytes_read != ((block_cnt + 1) * ST25TB_SR_BLOCK_SIZE)) {
1957 PrintAndLogEx(ERR, "File content error. Read %zu", bytes_read);
1958 free(data);
1959 return PM3_EFILE;
1961 PrintAndLogEx(INFO, "Copying to %s", s);
1963 int blockno = 0;
1964 while (bytes_read) {
1966 int status = write_sr_block(blockno, ST25TB_SR_BLOCK_SIZE, data + blockno * ST25TB_SR_BLOCK_SIZE);
1967 if (status != PM3_SUCCESS) {
1968 PrintAndLogEx(FAILED, "Write failed");
1969 free(data);
1970 return status;
1973 // verify
1974 uint8_t out[ST25TB_SR_BLOCK_SIZE] = {0};
1975 status = read_sr_block(blockno, out);
1976 if (status == PM3_SUCCESS) {
1977 if (memcmp(data + blockno * ST25TB_SR_BLOCK_SIZE, out, ST25TB_SR_BLOCK_SIZE) == 0) {
1978 printf("\33[2K\r");
1979 PrintAndLogEx(INFO, "SRx write block %d/%d ( " _GREEN_("ok") " )" NOLF, blockno, block_cnt - 1);
1980 } else {
1981 printf("\n");
1982 PrintAndLogEx(INFO, "SRx write block %d/%d ( " _RED_("different") " )", blockno, block_cnt - 1);
1984 } else {
1985 printf("\n");
1986 PrintAndLogEx(INFO, "Verifying block %d/%d ( " _RED_("failed") " )", blockno, block_cnt - 1);
1989 fflush(stdout);
1991 bytes_read -= ST25TB_SR_BLOCK_SIZE;
1992 blockno++;
1993 if (blockno >= block_cnt) break;
1996 PrintAndLogEx(NORMAL, "\n");
1997 free(data);
1999 // confirm number written blocks.
2000 if (blockno != block_cnt) {
2001 PrintAndLogEx(ERR, "File content error. There must be %d blocks", block_cnt);
2002 return PM3_EFILE;
2005 PrintAndLogEx(SUCCESS, "Card loaded " _YELLOW_("%d") " blocks from file", block_cnt);
2006 PrintAndLogEx(INFO, "Done!");
2009 return PM3_SUCCESS;
2014 static uint32_t srix4kEncode(uint32_t value) {
2015 // vv = value
2016 // pp = position
2017 // vv vv vv pp
2018 // 4 bytes : 00 1A 20 01
2019 // only the lower crumbs.
2020 uint8_t block = (value & 0xFF);
2021 uint8_t i = 0;
2022 uint8_t valuebytes[] = {0, 0, 0};
2023 Uint3byteToMemBe(valuebytes, value >> 8);
2025 uint32_t value_x = (value >> 8);
2026 PrintAndLogEx(INFO, "value...... %08x %06x", value, value_x);
2027 PrintAndLogEx(INFO, "3b value... %s", sprint_hex_inrow(valuebytes, sizeof(valuebytes)));
2028 PrintAndLogEx(INFO, "block no... %02x", block);
2030 // Scrambled part
2031 // Crumb swapping of value.
2032 uint32_t foo = 0;
2033 foo |= CRUMB(value_x, 22) << 28;
2034 foo |= CRUMB(value_x, 14) << 26;
2035 foo |= CRUMB(value_x, 6) << 24;
2037 foo |= CRUMB(value_x, 20) << 20;
2038 foo |= CRUMB(value_x, 12) << 18;
2039 foo |= CRUMB(value_x, 4) << 16;
2041 foo |= CRUMB(value_x, 18) << 12;
2042 foo |= CRUMB(value_x, 10) << 10;
2043 foo |= CRUMB(value_x, 2) << 8;
2045 foo |= CRUMB(value_x, 16) << 4;
2046 foo |= CRUMB(value_x, 8) << 2;
2047 foo |= CRUMB(value_x, 0) << 0;
2049 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 22), CRUMB(value_x, 14), CRUMB(value_x, 6));
2050 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 20), CRUMB(value_x, 12), CRUMB(value_x, 4));
2051 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 18), CRUMB(value_x, 10), CRUMB(value_x, 2));
2052 PrintAndLogEx(INFO, "hex........ %02x %02x %02x", CRUMB(value_x, 16), CRUMB(value_x, 8), CRUMB(value_x, 0));
2054 PrintAndLogEx(INFO, "hex........ %08x", foo);
2056 // chksum part
2057 uint32_t chksum = 0xFF - block;
2059 // chksum is reduced by each nibbles of value.
2060 for (i = 0; i < 3; ++i) {
2061 chksum -= NIBBLE_HIGH(valuebytes[i]);
2062 chksum -= NIBBLE_LOW(valuebytes[i]);
2065 // base4 conversion and left shift twice
2066 i = 3;
2067 uint8_t base4[] = {0, 0, 0, 0};
2068 while (chksum != 0) {
2069 base4[i--] = (chksum % 4 << 2);
2070 chksum /= 4;
2072 PrintAndLogEx(INFO, "%s", sprint_hex_inrow(base4, sizeof(base4)));
2074 // merge scambled and chksum parts
2075 uint32_t encvalue = 0;
2077 (NIBBLE_LOW(base4[0]) << 28) |
2078 (NIBBLE_HIGH(temp[0]) << 24) |
2080 (NIBBLE_LOW(base4[1]) << 20) |
2081 (NIBBLE_LOW(temp[0]) << 16) |
2083 (NIBBLE_LOW(base4[2]) << 12) |
2084 (NIBBLE_HIGH(temp[1]) << 8) |
2086 (NIBBLE_LOW(base4[3]) << 4) |
2087 NIBBLE_LOW(temp[1]);
2089 PrintAndLogEx(NORMAL, "ICE encoded | %08X -> %08X", value, encvalue);
2090 return encvalue;
2094 static uint32_t srix4k_decode_counter(uint32_t num) {
2095 uint32_t value = ~num;
2096 ++value;
2097 return value;
2100 static uint32_t srix4kDecode(uint32_t value) {
2101 switch (value) {
2102 case 0xC04F42C5:
2103 return 0x003139;
2104 case 0xC1484807:
2105 return 0x002943;
2106 case 0xC0C60848:
2107 return 0x001A20;
2109 return 0;
2113 static uint32_t srix4k_get_magicbytes(uint64_t uid, uint32_t block6, uint32_t block18, uint32_t block19) {
2114 #define MASK 0xFFFFFFFF;
2115 uint32_t uid32 = uid & MASK;
2116 uint32_t counter = srix4k_decode_counter(block6);
2117 uint32_t decodedBlock18 = 0;
2118 uint32_t decodedBlock19 = 0;
2119 // uint32_t decodedBlock18 = srix4kDecode(block18);
2120 // uint32_t decodedBlock19 = srix4kDecode(block19);
2121 uint32_t doubleBlock = (decodedBlock18 << 16 | decodedBlock19) + 1;
2123 uint32_t result = (uid32 * doubleBlock * counter) & MASK;
2124 PrintAndLogEx(SUCCESS, "Magic bytes | %08X", result);
2125 return result;
2128 static int CmdSRIX4kValid(const char *Cmd) {
2129 CLIParserContext *ctx;
2130 CLIParserInit(&ctx, "hf 14b valid",
2131 "SRIX checksum test",
2132 "hf 14b valid\n"
2135 void *argtable[] = {
2136 arg_param_begin,
2137 arg_param_end
2139 CLIExecWithReturn(ctx, Cmd, argtable, false);
2140 CLIParserFree(ctx);
2142 uint64_t uid = 0xD00202501A4532F9;
2143 uint32_t block6 = 0xFFFFFFFF;
2144 uint32_t block18 = 0xC04F42C5;
2145 uint32_t block19 = 0xC1484807;
2146 uint32_t block21 = 0xD1BCABA4;
2148 uint32_t test_b18 = 0x001A2001; // 0x00313918;
2149 uint32_t test_b18_enc = 0;
2150 // uint32_t test_b18_enc = srix4kEncode(test_b18);
2151 // uint32_t test_b18_dec = srix4kDecode(test_b18_enc);
2152 PrintAndLogEx(SUCCESS, "ENCODE & CHECKSUM | %08X -> %08X (%s)", test_b18, test_b18_enc, "");
2154 uint32_t magic = srix4k_get_magicbytes(uid, block6, block18, block19);
2155 PrintAndLogEx(SUCCESS, "BLOCK 21 | %08X -> %08X (no XOR)", block21, magic ^ block21);
2156 return PM3_SUCCESS;
2159 int select_card_14443b_4(bool disconnect, iso14b_card_select_t *card) {
2160 if (card) {
2161 memset(card, 0, sizeof(iso14b_card_select_t));
2164 switch_off_field_14b();
2166 iso14b_raw_cmd_t packet = {
2167 .flags = (ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_CLEARTRACE),
2168 .timeout = 0,
2169 .rawlen = 0,
2171 // Anticollision + SELECT STD card
2172 PacketResponseNG resp;
2173 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
2174 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
2176 PrintAndLogEx(INFO, "Trying 14B Select SRx");
2177 // Anticollision + SELECT SR card
2178 packet.flags = (ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_CLEARTRACE);
2179 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
2180 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
2182 PrintAndLogEx(INFO, "Trying 14B Select CTS");
2183 // Anticollision + SELECT ASK C-Ticket card
2184 packet.flags = (ISO14B_CONNECT | ISO14B_SELECT_CTS | ISO14B_CLEARTRACE);
2185 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)&packet, sizeof(iso14b_raw_cmd_t));
2186 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, TIMEOUT) == false) {
2187 PrintAndLogEx(ERR, "connection timeout");
2188 switch_off_field_14b();
2189 return PM3_ESOFT;
2194 // check result
2195 if (resp.status != PM3_SUCCESS) {
2196 PrintAndLogEx(WARNING, "No ISO14443-B Card in field");
2197 switch_off_field_14b();
2198 return PM3_ESOFT;
2201 SetISODEPState(ISODEP_NFCB);
2202 apdu_frame_length = 0;
2203 // get frame length from ATS in card data structure
2204 iso14b_card_select_t *vcard = (iso14b_card_select_t *) resp.data.asBytes;
2205 // uint8_t fsci = vcard->atqb[1] & 0x0f;
2206 // if (fsci < ARRAYLEN(ats_fsc)) {
2207 // apdu_frame_length = ats_fsc[fsci];
2208 // }
2210 if (card) {
2211 memcpy(card, vcard, sizeof(iso14b_card_select_t));
2214 if (disconnect) {
2215 switch_off_field_14b();
2217 return PM3_SUCCESS;
2220 static int handle_14b_apdu(bool chainingin, uint8_t *datain, int datainlen,
2221 bool activateField, uint8_t *dataout, int maxdataoutlen,
2222 int *dataoutlen, bool *chainingout, int user_timeout) {
2224 *chainingout = false;
2226 if (activateField) {
2227 // select with no disconnect and set frameLength
2228 int selres = select_card_14443b_4(false, NULL);
2229 if (selres != PM3_SUCCESS) {
2230 return selres;
2234 iso14b_raw_cmd_t *packet = (iso14b_raw_cmd_t *)calloc(1, sizeof(iso14b_raw_cmd_t) + datainlen);
2235 if (packet == NULL) {
2236 PrintAndLogEx(FAILED, "APDU: failed to allocate memory");
2237 return PM3_EMALLOC;
2239 packet->flags = (ISO14B_APDU);
2240 packet->timeout = 0;
2241 packet->rawlen = 0;
2243 if (chainingin) {
2244 packet->flags = (ISO14B_SEND_CHAINING | ISO14B_APDU);
2247 if (user_timeout > 0) {
2248 packet->flags |= ISO14B_SET_TIMEOUT;
2249 if (user_timeout > MAX_14B_TIMEOUT_MS) {
2250 user_timeout = MAX_14B_TIMEOUT_MS;
2251 PrintAndLogEx(INFO, "set timeout to 4.9 seconds. The max we can wait for response");
2254 // timeout in ETU
2255 packet->timeout = (uint32_t)((13560 / 128) * user_timeout);
2258 // "Command APDU" length should be 5+255+1, but javacard's APDU buffer might be smaller - 133 bytes
2259 // https://stackoverflow.com/questions/32994936/safe-max-java-card-apdu-data-command-and-respond-size
2260 // here length PM3_CMD_DATA_SIZE=512
2261 if (datain) {
2262 packet->rawlen = datainlen;
2263 memcpy(packet->raw, datain, datainlen);
2264 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t) + packet->rawlen);
2265 } else {
2266 SendCommandNG(CMD_HF_ISO14443B_COMMAND, (uint8_t *)packet, sizeof(iso14b_raw_cmd_t));
2268 free(packet);
2269 PacketResponseNG resp;
2270 if (WaitForResponseTimeout(CMD_HF_ISO14443B_COMMAND, &resp, MAX(APDU_TIMEOUT, user_timeout)) == false) {
2271 PrintAndLogEx(ERR, "APDU: reply timeout");
2272 return PM3_ETIMEOUT;
2275 if (resp.status != PM3_SUCCESS) {
2276 PrintAndLogEx(ERR, "APDU: no APDU response");
2277 return resp.status;
2280 iso14b_raw_apdu_response_t *apdu = (iso14b_raw_apdu_response_t *)resp.data.asBytes;
2282 // remove crc bytes
2283 int dlen = apdu->datalen - 2;
2284 if (dlen < 0) {
2285 dlen = 0;
2288 *dataoutlen += dlen;
2290 if (maxdataoutlen && *dataoutlen > maxdataoutlen) {
2291 PrintAndLogEx(ERR, "APDU: buffer too small ( " _RED_("%d") " ), needs " _YELLOW_("%d") " bytes", maxdataoutlen, *dataoutlen);
2292 return PM3_ESOFT;
2295 // I-block ACK
2296 if ((apdu->response_byte & 0xF2) == 0xA2) {
2297 *dataoutlen = 0;
2298 *chainingout = true;
2299 return PM3_SUCCESS;
2302 // check apdu length
2303 if (apdu->datalen < 2) {
2304 PrintAndLogEx(ERR, "APDU: small APDU response, len " _RED_("%d"), apdu->datalen);
2305 return PM3_ESOFT;
2308 // copy to output array
2309 memcpy(dataout, apdu->data, dlen);
2311 // chaining
2312 if ((apdu->response_byte & 0x10) != 0) {
2313 *chainingout = true;
2315 return PM3_SUCCESS;
2318 int exchange_14b_apdu(uint8_t *datain, int datainlen, bool activate_field,
2319 bool leave_signal_on, uint8_t *dataout, int maxdataoutlen,
2320 int *dataoutlen, int user_timeout) {
2322 *dataoutlen = 0;
2323 bool chaining = false;
2324 int res;
2326 // 3 byte here - 1b framing header, 2b crc16
2327 if (apdu_in_framing_enable &&
2328 ((apdu_frame_length && (datainlen > apdu_frame_length - 3)) || (datainlen > PM3_CMD_DATA_SIZE - 3))) {
2330 int clen = 0;
2331 bool v_activate_field = activate_field;
2333 do {
2334 int vlen = MIN(apdu_frame_length - 3, datainlen - clen);
2335 bool chainBlockNotLast = ((clen + vlen) < datainlen);
2337 *dataoutlen = 0;
2338 res = handle_14b_apdu(chainBlockNotLast, &datain[clen], vlen, v_activate_field, dataout, maxdataoutlen, dataoutlen, &chaining, user_timeout);
2339 if (res) {
2340 if (leave_signal_on == false) {
2341 switch_off_field_14b();
2344 return 200;
2347 // TODO check this one...
2348 // check R-block ACK
2349 // *dataoutlen!=0. 'A && (!A || B)' is equivalent to 'A && B'
2350 if ((*dataoutlen == 0) && (chaining != chainBlockNotLast)) {
2351 if (leave_signal_on == false) {
2352 switch_off_field_14b();
2354 return 201;
2357 clen += vlen;
2358 v_activate_field = false;
2359 if (*dataoutlen) {
2360 if (clen != datainlen) {
2361 PrintAndLogEx(ERR, "APDU: I-block/R-block sequence error. Data len=%d, Sent=%d, Last packet len=%d", datainlen, clen, *dataoutlen);
2363 break;
2365 } while (clen < datainlen);
2367 } else {
2368 res = handle_14b_apdu(false, datain, datainlen, activate_field, dataout, maxdataoutlen, dataoutlen, &chaining, user_timeout);
2369 if (res != PM3_SUCCESS) {
2370 if (leave_signal_on == false) {
2371 switch_off_field_14b();
2373 return res;
2377 while (chaining) {
2378 // I-block with chaining
2379 res = handle_14b_apdu(false, NULL, 0, false, &dataout[*dataoutlen], maxdataoutlen, dataoutlen, &chaining, user_timeout);
2380 if (res != PM3_SUCCESS) {
2381 if (leave_signal_on == false) {
2382 switch_off_field_14b();
2384 return 100;
2388 if (leave_signal_on == false) {
2389 switch_off_field_14b();
2392 return PM3_SUCCESS;
2395 // ISO14443-4. 7. Half-duplex block transmission protocol
2396 static int CmdHF14BAPDU(const char *Cmd) {
2397 CLIParserContext *ctx;
2398 CLIParserInit(&ctx, "hf 14b apdu",
2399 "Sends an ISO 7816-4 APDU via ISO 14443-4 block transmission protocol (T=CL).\n"
2400 "works with all apdu types from ISO 7816-4:2013",
2401 "hf 14b apdu -s -d 94a40800043f000002\n"
2402 "hf 14b apdu -s --decode -d 00A404000E325041592E5359532E444446303100 -> decode apdu\n"
2403 "hf 14b apdu -sm 00A40400 -l 256 -d 325041592E5359532E4444463031 -> encode standard apdu\n"
2404 "hf 14b apdu -sm 00A40400 -el 65536 -d 325041592E5359532E4444463031 -> encode extended apdu\n");
2406 void *argtable[] = {
2407 arg_param_begin,
2408 arg_lit0("s", "select", "activate field and select card"),
2409 arg_lit0("k", "keep", "leave the signal field ON after receive response"),
2410 arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
2411 arg_lit0(NULL, "decode", "decode apdu request if it possible"),
2412 arg_str0("m", "make", "<hex>", "make apdu with head from this field and data from data field.\n"
2413 " must be 4 bytes: <CLA INS P1 P2>"),
2414 arg_lit0("e", "extended", "make extended length apdu if `m` parameter included"),
2415 arg_int0("l", "le", "<int>", "Le apdu parameter if `m` parameter included"),
2416 arg_str1("d", "data", "<hex>", "<APDU | data> if `m` parameter included"),
2417 arg_int0(NULL, "timeout", "<dec>", "timeout in ms"),
2418 arg_param_end
2420 CLIExecWithReturn(ctx, Cmd, argtable, false);
2422 bool activate_field = arg_get_lit(ctx, 1);
2423 bool leave_signal_on = arg_get_lit(ctx, 2);
2424 bool decode_TLV = arg_get_lit(ctx, 3);
2425 bool decode_APDU = arg_get_lit(ctx, 4);
2427 uint8_t header[PM3_CMD_DATA_SIZE] = {0x00};
2428 int headerlen = 0;
2429 CLIGetHexWithReturn(ctx, 5, header, &headerlen);
2431 bool make_APDU = (headerlen > 0);
2432 if (make_APDU && headerlen != 4) {
2433 PrintAndLogEx(ERR, "header length must be 4 bytes, got " _RED_("%d"), headerlen);
2434 CLIParserFree(ctx);
2435 return PM3_EINVARG;
2438 bool extended_APDU = arg_get_lit(ctx, 6);
2439 int le = arg_get_int_def(ctx, 7, 0);
2441 uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
2442 int datalen = 0;
2444 if (make_APDU) {
2445 uint8_t apdudata[PM3_CMD_DATA_SIZE] = {0};
2446 int apdudatalen = 0;
2448 CLIGetHexBLessWithReturn(ctx, 8, apdudata, &apdudatalen, 1 + 2);
2450 APDU_t apdu;
2451 apdu.cla = header[0];
2452 apdu.ins = header[1];
2453 apdu.p1 = header[2];
2454 apdu.p2 = header[3];
2456 apdu.lc = apdudatalen;
2457 apdu.data = apdudata;
2459 apdu.extended_apdu = extended_APDU;
2460 apdu.le = le;
2462 if (APDUEncode(&apdu, data, &datalen)) {
2463 PrintAndLogEx(ERR, "can't make apdu with provided parameters.");
2464 CLIParserFree(ctx);
2465 return PM3_EINVARG;
2468 } else {
2469 if (extended_APDU) {
2470 PrintAndLogEx(ERR, "make mode not set but here `e` option.");
2471 CLIParserFree(ctx);
2472 return PM3_EINVARG;
2474 if (le > 0) {
2475 PrintAndLogEx(ERR, "make mode not set but here `l` option.");
2476 CLIParserFree(ctx);
2477 return PM3_EINVARG;
2480 // len = data + PCB(1b) + CRC(2b)
2481 CLIGetHexBLessWithReturn(ctx, 8, data, &datalen, 1 + 2);
2483 int user_timeout = arg_get_int_def(ctx, 9, -1);
2484 CLIParserFree(ctx);
2486 PrintAndLogEx(SUCCESS, _YELLOW_("%s%s%s"),
2487 activate_field ? "select card" : "",
2488 leave_signal_on ? ", keep field on" : "",
2489 decode_TLV ? ", TLV" : ""
2491 PrintAndLogEx(SUCCESS, ">>> %s", sprint_hex_inrow(data, datalen));
2493 if (decode_APDU) {
2494 APDU_t apdu;
2495 if (APDUDecode(data, datalen, &apdu) == 0)
2496 APDUPrint(apdu);
2497 else
2498 PrintAndLogEx(WARNING, "can't decode APDU.");
2501 int res = exchange_14b_apdu(data, datalen, activate_field, leave_signal_on, data, PM3_CMD_DATA_SIZE, &datalen, user_timeout);
2502 if (res != PM3_SUCCESS) {
2503 return res;
2506 PrintAndLogEx(INFO, "<<<< %s - %s", sprint_hex_inrow(data, datalen), sprint_ascii(data, datalen));
2507 uint16_t sw = get_sw(data, datalen);
2508 if (sw != ISO7816_OK) {
2509 PrintAndLogEx(SUCCESS, "APDU response: " _YELLOW_("%02x %02x") " - %s"
2510 , data[datalen - 2]
2511 , data[datalen - 1]
2512 , GetAPDUCodeDescription(data[datalen - 2], data[datalen - 1])
2514 } else {
2515 PrintAndLogEx(SUCCESS, "APDU response: " _GREEN_("%02x %02x") " - %s"
2516 , data[datalen - 2]
2517 , data[datalen - 1]
2518 , GetAPDUCodeDescription(data[datalen - 2], data[datalen - 1])
2522 // TLV decoder
2523 if (decode_TLV && datalen > 4) {
2524 TLVPrintFromBuffer(data, datalen - 2);
2527 return PM3_SUCCESS;
2530 int CmdHF14BNdefRead(const char *Cmd) {
2532 CLIParserContext *ctx;
2533 CLIParserInit(&ctx, "hf 14b ndefread",
2534 "Print NFC Data Exchange Format (NDEF)",
2535 "hf 14b ndefread\n"
2536 "hf 14b ndefread -f myfilename -> save raw NDEF to file"
2538 void *argtable[] = {
2539 arg_param_begin,
2540 arg_str0("f", "file", "<fn>", "Save raw NDEF to file"),
2541 arg_lit0("v", "verbose", "Verbose output"),
2542 arg_param_end
2544 CLIExecWithReturn(ctx, Cmd, argtable, true);
2545 int fnlen = 0;
2546 char filename[FILE_PATH_SIZE] = {0};
2547 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
2549 bool verbose = arg_get_lit(ctx, 2);
2550 CLIParserFree(ctx);
2552 bool activate_field = true;
2553 bool keep_field_on = true;
2554 uint8_t response[PM3_CMD_DATA_SIZE];
2555 int resplen = 0;
2557 // --------------- Select NDEF Tag application ----------------
2558 uint8_t aSELECT_AID[80];
2559 int aSELECT_AID_n = 0;
2560 param_gethex_to_eol("00a4040007d276000085010100", 0, aSELECT_AID, sizeof(aSELECT_AID), &aSELECT_AID_n);
2561 int res = exchange_14b_apdu(aSELECT_AID, aSELECT_AID_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2562 if (res) {
2563 goto out;
2566 if (resplen < 2) {
2567 res = PM3_ESOFT;
2568 goto out;
2571 uint16_t sw = get_sw(response, resplen);
2572 if (sw != ISO7816_OK) {
2573 PrintAndLogEx(ERR, "Selecting NDEF aid failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2574 res = PM3_ESOFT;
2575 goto out;
2578 activate_field = false;
2579 keep_field_on = true;
2580 // --------------- Send CC select ----------------
2581 // --------------- Read binary ----------------
2583 // --------------- NDEF file reading ----------------
2584 uint8_t aSELECT_FILE_NDEF[30];
2585 int aSELECT_FILE_NDEF_n = 0;
2586 param_gethex_to_eol("00a4000c020001", 0, aSELECT_FILE_NDEF, sizeof(aSELECT_FILE_NDEF), &aSELECT_FILE_NDEF_n);
2587 res = exchange_14b_apdu(aSELECT_FILE_NDEF, aSELECT_FILE_NDEF_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2588 if (res)
2589 goto out;
2591 sw = get_sw(response, resplen);
2592 if (sw != ISO7816_OK) {
2593 PrintAndLogEx(ERR, "Selecting NDEF file failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2594 res = PM3_ESOFT;
2595 goto out;
2598 // --------------- Read binary ----------------
2599 uint8_t aREAD_NDEF[30];
2600 int aREAD_NDEF_n = 0;
2601 param_gethex_to_eol("00b0000002", 0, aREAD_NDEF, sizeof(aREAD_NDEF), &aREAD_NDEF_n);
2602 res = exchange_14b_apdu(aREAD_NDEF, aREAD_NDEF_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2603 if (res) {
2604 goto out;
2607 sw = get_sw(response, resplen);
2608 if (sw != ISO7816_OK) {
2609 PrintAndLogEx(ERR, "reading NDEF file failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2610 res = PM3_ESOFT;
2611 goto out;
2613 // take offset from response
2614 uint8_t offset = response[1];
2616 // --------------- Read binary w offset ----------------
2617 keep_field_on = false;
2618 aREAD_NDEF_n = 0;
2619 param_gethex_to_eol("00b00002", 0, aREAD_NDEF, sizeof(aREAD_NDEF), &aREAD_NDEF_n);
2620 aREAD_NDEF[4] = offset;
2621 res = exchange_14b_apdu(aREAD_NDEF, aREAD_NDEF_n, activate_field, keep_field_on, response, sizeof(response), &resplen, -1);
2622 if (res) {
2623 goto out;
2626 sw = get_sw(response, resplen);
2627 if (sw != ISO7816_OK) {
2628 PrintAndLogEx(ERR, "reading NDEF file failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2629 res = PM3_ESOFT;
2630 goto out;
2633 // get total NDEF length before save. If fails, we save it all
2634 size_t n = 0;
2635 if (NDEFGetTotalLength(response + 2, resplen - 4, &n) != PM3_SUCCESS)
2636 n = resplen - 4;
2638 pm3_save_dump(filename, response + 2, n, jsfNDEF);
2640 res = NDEFRecordsDecodeAndPrint(response + 2, resplen - 4, verbose);
2642 out:
2643 switch_off_field_14b();
2644 return res;
2647 static int CmdHF14BView(const char *Cmd) {
2649 CLIParserContext *ctx;
2650 CLIParserInit(&ctx, "hf 14b view",
2651 "Print a ISO14443-B dump file (bin/eml/json)\n"
2652 "note:\n"
2653 " - command expects the filename to contain a UID\n"
2654 " which is needed to determine card memory type",
2655 "hf 14b view -f hf-14b-01020304-dump.bin"
2657 void *argtable[] = {
2658 arg_param_begin,
2659 arg_str1("f", "file", "<fn>", "Specify a filename for dump file"),
2660 arg_lit0("v", "verbose", "verbose output"),
2661 arg_lit0("z", "dense", "dense dump output style"),
2662 arg_param_end
2664 CLIExecWithReturn(ctx, Cmd, argtable, false);
2665 int fnlen = 0;
2666 char filename[FILE_PATH_SIZE];
2667 CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen);
2668 bool verbose = arg_get_lit(ctx, 2);
2669 bool dense_output = (g_session.dense_output || arg_get_lit(ctx, 3));
2670 CLIParserFree(ctx);
2672 // read dump file
2673 uint8_t *dump = NULL;
2674 size_t bytes_read = (ST25TB_SR_BLOCK_SIZE * 0x100);
2675 int res = pm3_load_dump(filename, (void **)&dump, &bytes_read, (ST25TB_SR_BLOCK_SIZE * 0x100));
2676 if (res != PM3_SUCCESS) {
2677 return res;
2680 uint16_t block_cnt = bytes_read / ST25TB_SR_BLOCK_SIZE;
2682 if (verbose) {
2683 PrintAndLogEx(INFO, "File size %zu bytes, file blocks %d (0x%x)", bytes_read, block_cnt, block_cnt);
2686 // figure out a way to identify the different dump files.
2687 // STD/SR/CT is difference
2688 print_sr_blocks(dump, bytes_read, get_uid_from_filename(filename), dense_output);
2689 //print_std_blocks(dump, bytes_read);
2690 //print_ct_blocks(dump, bytes_read);
2692 free(dump);
2693 return PM3_SUCCESS;
2696 static int CmdHF14BCalypsoRead(const char *Cmd) {
2698 CLIParserContext *ctx;
2699 CLIParserInit(&ctx, "hf 14b calypso",
2700 "Reads out the contents of a ISO14443B Calypso card\n",
2701 "hf 14b calypso"
2703 void *argtable[] = {
2704 arg_param_begin,
2705 arg_param_end
2707 CLIExecWithReturn(ctx, Cmd, argtable, true);
2708 CLIParserFree(ctx);
2710 transport_14b_apdu_t cmds[] = {
2711 {"01.Select ICC file", "\x94\xa4\x08\x00\x04\x3f\x00\x00\x02", 9},
2712 {"02.ICC", "\x94\xb2\x01\x04\x1d", 5},
2713 {"03.Select EnvHol file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x01", 9},
2714 {"04.EnvHol1", "\x94\xb2\x01\x04\x1d", 5},
2715 {"05.Select EvLog file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x10", 9},
2716 {"06.EvLog1", "\x94\xb2\x01\x04\x1d", 5},
2717 {"07.EvLog2", "\x94\xb2\x02\x04\x1d", 5},
2718 {"08.EvLog3", "\x94\xb2\x03\x04\x1d", 5},
2719 {"09.Select ConList file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x50", 9},
2720 {"10.ConList", "\x94\xb2\x01\x04\x1d", 5},
2721 {"11.Select Contra file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x20", 9},
2722 {"12.Contra1", "\x94\xb2\x01\x04\x1d", 5},
2723 {"13.Contra2", "\x94\xb2\x02\x04\x1d", 5},
2724 {"14.Contra3", "\x94\xb2\x03\x04\x1d", 5},
2725 {"15.Contra4", "\x94\xb2\x04\x04\x1d", 5},
2726 {"16.Select Counter file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x69", 9},
2727 {"17.Counter", "\x94\xb2\x01\x04\x1d", 5},
2728 {"18.Select SpecEv file", "\x94\xa4\x08\x00\x04\x20\x00\x20\x40", 9},
2729 {"19.SpecEv1", "\x94\xb2\x01\x04\x1d", 5},
2733 local CLA = '94'
2734 local _calypso_cmds = {
2736 -- Break down of command bytes:
2737 -- A4 = select
2738 -- Master File 3F00
2739 -- 0x3F = master file
2740 -- 0x00 = master file id, is constant to 0x00.
2742 -- DF Dedicated File 38nn
2743 -- can be seen as directories
2744 -- 0x38
2745 -- 0xNN id
2746 -- ["01.Select ICC file"] = '0294 a4 080004 3f00 0002',
2748 -- EF Elementary File
2749 -- EF1 Pin file
2750 -- EF2 Key file
2751 -- Grey Lock file
2752 -- Electronic deposit file
2753 -- Electronic Purse file
2754 -- Electronic Transaction log file
2756 bool activate_field = true;
2757 bool leave_signal_on = true;
2758 uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 };
2760 for (int i = 0; i < ARRAYLEN(cmds); i++) {
2762 int user_timeout = -1;
2763 int resplen = 0;
2764 int res = exchange_14b_apdu(
2765 (uint8_t *)cmds[i].apdu,
2766 cmds[i].apdulen,
2767 activate_field,
2768 leave_signal_on,
2769 response,
2770 PM3_CMD_DATA_SIZE,
2771 &resplen,
2772 user_timeout
2775 if (res != PM3_SUCCESS) {
2776 PrintAndLogEx(FAILED, "sending command failed, aborting!");
2777 switch_off_field_14b();
2778 return res;
2781 uint16_t sw = get_sw(response, resplen);
2782 if (sw != ISO7816_OK) {
2783 PrintAndLogEx(ERR, "Sending command failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2784 switch_off_field_14b();
2785 return PM3_ESOFT;
2788 PrintAndLogEx(INFO, "%s - %s", cmds[i].desc, sprint_hex(response, resplen));
2789 activate_field = false;
2792 switch_off_field_14b();
2793 return PM3_SUCCESS;
2796 static int CmdHF14BMobibRead(const char *Cmd) {
2798 CLIParserContext *ctx;
2799 CLIParserInit(&ctx, "hf 14b mobib",
2800 "Reads out the contents of a ISO14443B Mobib card\n",
2801 "hf 14b mobib"
2803 void *argtable[] = {
2804 arg_param_begin,
2805 arg_param_end
2807 CLIExecWithReturn(ctx, Cmd, argtable, true);
2808 CLIParserFree(ctx);
2810 transport_14b_apdu_t cmds[] = {
2811 {"01.SELECT AID 1TIC.ICA", "\x00\xa4\x04\x00\x08\x31\x54\x49\x43\x2e\x49\x43\x41", 13},
2812 {"02.Select ICC file a", "\x00\xa4\x00\x00\x02\x3f\x00", 7},
2813 {"03.Select ICC file b", "\x00\xa4\x00\x00\x02\x00\x02", 7},
2814 {"04.ICC", "\x00\xb2\x01\x04\x1d", 5},
2815 {"05.Select Holder file", "\x00\xa4\x00\x00\x02\x3f\x1c", 7},
2816 {"06.Holder1", "\x00\xb2\x01\x04\x1d", 5},
2817 {"07.Holder2", "\x00\xb2\x02\x04\x1d", 5},
2818 {"08.Select EnvHol file a", "\x00\xa4\x00\x00\x00", 5},
2819 {"09.Select EnvHol file b", "\x00\xa4\x00\x00\x02\x20\x00", 7},
2820 {"10.Select EnvHol file c", "\x00\xa4\x00\x00\x02\x20\x01", 7},
2821 {"11.EnvHol1", "\x00\xb2\x01\x04\x1D", 5},
2822 {"11.EnvHol2", "\x00\xb2\x02\x04\x1D", 5},
2823 {"12.Select EvLog file", "\x00\xa4\x00\x00\x02\x20\x10", 7},
2824 {"13.EvLog1", "\x00\xb2\x01\x04\x1D", 5},
2825 {"14.EvLog2", "\x00\xb2\x02\x04\x1D", 5},
2826 {"15.EvLog3", "\x00\xb2\x03\x04\x1D", 5},
2827 {"16.Select ConList file", "\x00\xa4\x00\x00\x02\x20\x50", 7},
2828 {"17.ConList", "\x00\xb2\x01\x04\x1D", 5},
2829 {"18.Select Contra file", "\x00\xa4\x00\x00\x02\x20\x20", 7},
2830 {"19.Contra1", "\x00\xb2\x01\x04\x1D", 5},
2831 {"20.Contra2", "\x00\xb2\x02\x04\x1D", 5},
2832 {"21.Contra3", "\x00\xb2\x03\x04\x1D", 5},
2833 {"22.Contra4", "\x00\xb2\x04\x04\x1D", 5},
2834 {"23.Contra5", "\x00\xb2\x05\x04\x1D", 5},
2835 {"24.Contra6", "\x00\xb2\x06\x04\x1D", 5},
2836 {"25.Contra7", "\x00\xb2\x07\x04\x1D", 5},
2837 {"26.Contra8", "\x00\xb2\x08\x04\x1D", 5},
2838 {"27.Contra9", "\x00\xb2\x09\x04\x1D", 5},
2839 {"28.ContraA", "\x00\xb2\x0a\x04\x1D", 5},
2840 {"29.ContraB", "\x00\xb2\x0b\x04\x1D", 5},
2841 {"30.ContraC", "\x00\xb2\x0c\x04\x1D", 5},
2842 {"31.Select Counter file", "\x00\xa4\x00\x00\x02\x20\x69", 7},
2843 {"32.Counter", "\x00\xb2\x01\x04\x1D", 5},
2844 {"33.Select LoadLog file a", "\x00\xa4\x00\x00\x00", 5},
2845 {"34.Select LoadLog file b", "\x00\xa4\x00\x00\x02\x10\x00", 7},
2846 {"35.Select LoadLog file c", "\x00\xa4\x00\x00\x02\x10\x14", 7},
2847 {"36.LoadLog", "\x00\xb2\x01\x04\x1D", 5},
2848 {"37.Select Purcha file", "\x00\xa4\x00\x00\x02\x10\x15", 7},
2849 {"38.Purcha1", "\x00\xb2\x01\x04\x1D", 5},
2850 {"39.Purcha2", "\x00\xb2\x02\x04\x1D", 5},
2851 {"40.Purcha3", "\x00\xb2\x03\x04\x1D", 5},
2852 {"41.Select SpecEv file a", "\x00\xa4\x00\x00\x00", 5},
2853 {"42.Select SpecEv file b", "\x00\xa4\x00\x00\x02\x20\x00", 7},
2854 {"43.Select SpecEv file c", "\x00\xa4\x00\x00\x02\x20\x40", 7},
2855 {"44.SpecEv1", "\x00\xb2\x01\x04\x1D", 5},
2856 {"45.SpecEv2", "\x00\xb2\x02\x04\x1D", 5},
2857 {"46.SpecEv3", "\x00\xb2\x03\x04\x1D", 5},
2858 {"47.SpecEv4", "\x00\xb2\x04\x04\x1d", 5},
2861 bool activate_field = true;
2862 bool leave_signal_on = true;
2863 uint8_t response[PM3_CMD_DATA_SIZE] = { 0x00 };
2865 for (int i = 0; i < ARRAYLEN(cmds); i++) {
2867 int user_timeout = -1;
2868 int resplen = 0;
2869 int res = exchange_14b_apdu(
2870 (uint8_t *)cmds[i].apdu,
2871 cmds[i].apdulen,
2872 activate_field,
2873 leave_signal_on,
2874 response,
2875 PM3_CMD_DATA_SIZE,
2876 &resplen,
2877 user_timeout
2880 if (res != PM3_SUCCESS) {
2881 PrintAndLogEx(FAILED, "sending command failed, aborting!");
2882 switch_off_field_14b();
2883 return res;
2886 uint16_t sw = get_sw(response, resplen);
2887 if (sw != ISO7816_OK) {
2888 PrintAndLogEx(ERR, "Sending command failed (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff));
2889 switch_off_field_14b();
2890 return PM3_ESOFT;
2893 PrintAndLogEx(INFO, "%s - %s", cmds[i].desc, sprint_hex(response, resplen));
2894 activate_field = false;
2897 switch_off_field_14b();
2898 return PM3_SUCCESS;
2901 static command_t CommandTable[] = {
2902 {"---------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("General") " -----------------------"},
2903 {"help", CmdHelp, AlwaysAvailable, "This help"},
2904 {"list", CmdHF14BList, AlwaysAvailable, "List ISO-14443-B history"},
2905 {"---------", CmdHelp, AlwaysAvailable, "----------------------- " _CYAN_("Operations") " -----------------------"},
2906 {"apdu", CmdHF14BAPDU, IfPm3Iso14443b, "Send ISO 14443-4 APDU to tag"},
2907 {"dump", CmdHF14BDump, IfPm3Iso14443b, "Read all memory pages of an ISO-14443-B tag, save to file"},
2908 {"info", CmdHF14Binfo, IfPm3Iso14443b, "Tag information"},
2909 {"ndefread", CmdHF14BNdefRead, IfPm3Iso14443b, "Read NDEF file on tag"},
2910 {"raw", CmdHF14BRaw, IfPm3Iso14443b, "Send raw hex data to tag"},
2911 {"rdbl", CmdHF14BSriRdBl, IfPm3Iso14443b, "Read SRI512/SRIX4 block"},
2912 {"reader", CmdHF14BReader, IfPm3Iso14443b, "Act as a ISO-14443-B reader to identify a tag"},
2913 {"restore", CmdHF14BRestore, IfPm3Iso14443b, "Restore from file to all memory pages of an ISO-14443-B tag"},
2914 {"sim", CmdHF14BSim, IfPm3Iso14443b, "Fake ISO ISO-14443-B tag"},
2915 {"sniff", CmdHF14BSniff, IfPm3Iso14443b, "Eavesdrop ISO-14443-B"},
2916 {"wrbl", CmdHF14BSriWrbl, IfPm3Iso14443b, "Write data to a SRI512/SRIX4 tag"},
2917 {"view", CmdHF14BView, AlwaysAvailable, "Display content from tag dump file"},
2918 {"valid", CmdSRIX4kValid, AlwaysAvailable, "SRIX4 checksum test"},
2919 {"---------", CmdHelp, AlwaysAvailable, "------------------ " _CYAN_("Calypso / Mobib") " ------------------"},
2920 {"calypso", CmdHF14BCalypsoRead, IfPm3Iso14443b, "Read contents of a Calypso card"},
2921 {"mobib", CmdHF14BMobibRead, IfPm3Iso14443b, "Read contents of a Mobib card"},
2922 {NULL, NULL, NULL, NULL}
2925 static int CmdHelp(const char *Cmd) {
2926 (void)Cmd; // Cmd is not used so far
2927 CmdsHelp(CommandTable);
2928 return PM3_SUCCESS;
2931 int CmdHF14B(const char *Cmd) {
2932 clearCommandBuffer();
2933 return CmdsParse(CommandTable, Cmd);
2936 // get and print all info known about any known 14b tag
2937 int infoHF14B(bool verbose, bool do_aid_search) {
2939 // try std 14b (atqb)
2940 if (HF14B_Std_Info(verbose, do_aid_search))
2941 return PM3_SUCCESS;
2943 // try ST 14b
2944 if (HF14B_ST_Info(verbose, do_aid_search))
2945 return PM3_SUCCESS;
2947 // try unknown 14b read commands (to be identified later)
2948 // could be read of calypso, CEPAS, moneo, or pico pass.
2949 if (verbose) PrintAndLogEx(FAILED, "no 14443-B tag found");
2950 return PM3_EOPABORTED;
2953 // get and print general info about all known 14b chips
2954 int readHF14B(bool loop, bool verbose, bool read_plot) {
2955 bool found = false;
2956 int res = PM3_SUCCESS;
2957 do {
2958 found = false;
2960 // try std 14b (atqb)
2961 found |= HF14B_std_reader(verbose);
2962 if (found)
2963 goto plot;
2965 // try ST Microelectronics 14b
2966 found |= HF14B_st_reader(verbose);
2967 if (found)
2968 goto plot;
2970 // Picopass
2971 found |= HF14B_picopass_reader(verbose);
2972 if (found)
2973 goto plot;
2975 // try ASK CT 14b
2976 found |= HF14B_ask_ct_reader(verbose);
2977 if (found)
2978 goto plot;
2980 // try unknown 14b read commands (to be identified later)
2981 // could be read of calypso, CEPAS, moneo, or pico pass.
2982 found |= HF14B_other_reader(verbose);
2983 if (found)
2984 goto plot;
2985 plot:
2986 if (read_plot) {
2987 res = handle_hf_plot(verbose);
2988 if (res != PM3_SUCCESS) {
2989 PrintAndLogEx(DEBUG, "plot failed");
2993 } while (loop && kbd_enter_pressed() == false);
2995 if (verbose && found == false) {
2996 PrintAndLogEx(FAILED, "no ISO 14443-B tag found");
2998 return (found) ? PM3_SUCCESS : PM3_EOPABORTED;