added ISO 7816-3 protocol and parameter selection exchange command. wired up T=1 in device side and fixed timing issues too. Thanks Claude

This commit is contained in:
iceman1001 committed 2026-08-26 20:42:39 +02:00
1 parent 6a3ab99611
commit dcb474a963
11 files changed
+492 -80

No files matched your search

+1
View File
@@ -3,6 +3,7 @@ All notable changes to this project will be documented in this file.
This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log...
## [unreleased][unreleased]
- Added `smart pps` - ISO 7816-3 protocol and parameter selection exchange (@iceman1001)
- Added `sim015.bin` - sim modul firmware now supports T=0 and T=1 (@iceman1001)
- Added tools script `tools/ePassport/ePassport` - kivy python3 script that dumps a passport with BAC/CAN and a nice viewer (@iceman1001)
- Added tools script `external_sam_read.py` enabling PM3 3 Easy and Proxmark 5 to use an external SIM/SAM reader for `hf iclass sam` and `hf seos sam` commands (@antiklesys)
+4
View File
@@ -3142,6 +3142,10 @@ static void PacketReceived(PacketCommandNG *packet) {
SmartCardSetBaud(packet->oldarg[0]);
break;
}
case CMD_SMART_PPS: {
SmartCardPPS((const smart_card_pps_t *)packet->data.asBytes);
break;
}
case CMD_SMART_SETCLOCK: {
struct p {
uint32_t new_clk;
+99 -6
View File
@@ -174,10 +174,24 @@ static bool WaitSCL_L(void) {
return WaitSCL_L_delay(5000);
}
// Wait up to 1200ms or until SCL goes LOW, whichever comes first.
// Used to bound the timeout while reading a response from the card.
// How long to allow the SIM module to *start* an operation, i.e. to pull SCL
// low after it has taken a command.
//
// This used to be 1200 ms, which is three orders of magnitude more than the
// module needs - its interrupt hands the command to the main loop and SCL goes
// low within microseconds of the STOP. The only thing that long allowance ever
// bought was dead time: every caller that arrives when the module has *already*
// finished (SCL back high, and it is never going to go low again) sat here for
// the full 1200 ms before doing the read. sc_rx_bytes() does exactly that on
// every call that follows a completed operation, which is why an ordinary
// `smart info` took about one and a half seconds.
//
// The result is ignored by sc_rx_bytes() anyway - reaching the end of this
// simply means the module is idle and the data is ready to read.
#define SIM_START_TIMEOUT_MS 50
static bool WaitSCL_L_timeout(void) {
volatile uint32_t delay = 1200;
volatile uint32_t delay = SIM_START_TIMEOUT_MS;
while (delay--) {
// exit on SCL LOW
if (SCL_read == false)
@@ -775,16 +789,27 @@ bool I2C_WriteFW(const uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uin
return true;
}
static bool sim_module_at_least(uint8_t major, uint8_t minor, uint8_t want_major, uint8_t want_minor) {
return ((major > want_major) || ((major == want_major) && (minor >= want_minor)));
}
void I2C_print_status(void) {
DbpString(_CYAN_("Smart card module (ISO 7816)"));
uint8_t major, minor;
if (I2C_get_version(&major, &minor) == PM3_SUCCESS) {
bool ok = sim_module_at_least(major, minor, SIM_MODULE_VERS_MIN_HI, SIM_MODULE_VERS_MIN_LO);
bool t1 = sim_module_at_least(major, minor, SIM_MODULE_VERS_T1_HI, SIM_MODULE_VERS_T1_LO);
Dbprintf(" version................. v%d.%02d ( %s )"
, major
, minor
, ((major == 4) && (minor == 42)) ? _GREEN_("ok") : _RED_("Outdated")
, ok ? _GREEN_("ok") : _RED_("Outdated")
);
Dbprintf(" T=1, PPS................ ( %s )"
, t1 ? _GREEN_("supported") : _YELLOW_("not in this firmware")
);
} else {
DbpString(" version................. ( " _RED_("fail") " )");
@@ -829,6 +854,16 @@ bool sc_rx_bytes(uint8_t *dest, uint16_t *destlen, uint32_t wait) {
return true;
}
uint8_t sc_raw_device_cmd(smartcard_command_t flags) {
if ((flags & SC_RAW_T1) == SC_RAW_T1) {
return I2C_DEVICE_CMD_SEND_T1;
}
if ((flags & SC_RAW_T0) == SC_RAW_T0) {
return I2C_DEVICE_CMD_SEND_T0;
}
return I2C_DEVICE_CMD_SEND;
}
bool GetATR(smart_card_atr_t *card_ptr, bool verbose) {
if (card_ptr == NULL) {
@@ -940,7 +975,9 @@ void SmartCardRaw(const smart_card_raw_t *p) {
}
}
if (((flags & SC_RAW) == SC_RAW) || ((flags & SC_RAW_T0) == SC_RAW_T0)) {
if (((flags & SC_RAW) == SC_RAW) ||
((flags & SC_RAW_T0) == SC_RAW_T0) ||
((flags & SC_RAW_T1) == SC_RAW_T1)) {
uint32_t wait = SIM_WAIT_DELAY;
if ((flags & SC_WAIT) == SC_WAIT) {
@@ -955,7 +992,7 @@ void SmartCardRaw(const smart_card_raw_t *p) {
bool res = I2C_BufferWrite(
p->data,
p->len,
(((flags & SC_RAW_T0) == SC_RAW_T0) ? I2C_DEVICE_CMD_SEND_T0 : I2C_DEVICE_CMD_SEND),
sc_raw_device_cmd(flags),
I2C_DEVICE_ADDRESS_MAIN
);
@@ -1065,6 +1102,62 @@ void SmartCardSetBaud(uint64_t arg0) {
LEDsoff();
}
/*
* ISO/IEC 7816-3 clause 9 protocol and parameter selection.
*
* PPS is only legal in the window straight after the ATR, so the card is reset
* and its ATR collected first - that also gives the SIM module the interface
* bytes it needs to time the exchange. The module answers with
*
* [0] 1 when the card confirmed the request
* [1] the protocol now in force
* [2] the TA1 (FI/DI) now in force
*
* Note that SEND_T1 already runs a PPS on its own when the ATR offers T=1 but
* names T=0 first, so this is only needed to negotiate Fi/Di explicitly.
*/
void SmartCardPPS(const smart_card_pps_t *p) {
LED_D_ON();
set_tracing(true);
I2C_Reset_EnterMainProgram();
smart_card_atr_t card;
if (GetATR(&card, true) == false) {
reply_ng(CMD_SMART_PPS, PM3_ETIMEOUT, NULL, 0);
goto out;
}
uint8_t req[2];
uint16_t reqlen = 1;
req[0] = (uint8_t)(p->protocol & 0x0F);
if (p->use_ta1) {
req[1] = p->ta1;
reqlen = 2;
}
if (I2C_BufferWrite(req, reqlen, I2C_DEVICE_CMD_PPS, I2C_DEVICE_ADDRESS_MAIN) == false) {
if (g_dbglevel > DBG_DEBUG) {
DbpString(I2C_ERROR);
}
reply_ng(CMD_SMART_PPS, PM3_ESOFT, NULL, 0);
goto out;
}
uint8_t resp[8] = {0};
uint16_t len = sizeof(resp);
if ((sc_rx_bytes(resp, &len, SIM_WAIT_DELAY) == false) || (len < 3)) {
reply_ng(CMD_SMART_PPS, PM3_ETIMEOUT, NULL, 0);
goto out;
}
reply_ng(CMD_SMART_PPS, PM3_SUCCESS, resp, 3);
out:
set_tracing(false);
LEDsoff();
}
void SmartCardSetClock(uint64_t arg0) {
LED_D_ON();
set_tracing(true);
+21
View File
@@ -29,6 +29,23 @@
#define I2C_DEVICE_CMD_SIM_CLC 0x05
#define I2C_DEVICE_CMD_GETVERSION 0x06
#define I2C_DEVICE_CMD_SEND_T0 0x07
// SIM module firmware v4.51 and up. SEND_T1 takes a plain APDU and runs the
// whole T=1 block layer on the module - chaining, R block recovery, S(WTX),
// LRC/CRC - the same way SEND_T0 handles the T=0 procedure bytes.
#define I2C_DEVICE_CMD_SEND_T1 0x08
#define I2C_DEVICE_CMD_PPS 0x09
// SIM module firmware versions this build knows about.
//
// v4.42 - the stock firmware, T=0 only
// v4.51 - adds SEND_T1 (0x08) and PPS (0x09)
//
// Anything at or above the baseline is reported as ok, so a module does not go
// red every time its firmware moves on.
#define SIM_MODULE_VERS_MIN_HI 4
#define SIM_MODULE_VERS_MIN_LO 42
#define SIM_MODULE_VERS_T1_HI 4
#define SIM_MODULE_VERS_T1_LO 51
// The SIM module v4 supports up to 384 bytes for the length.
#define ISO7816_MAX_FRAME 270
@@ -60,6 +77,9 @@ int16_t I2C_BufferRead(uint8_t *data, uint16_t len, uint8_t device_cmd, uint8_t
int16_t I2C_ReadFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address);
bool I2C_WriteFW(const uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address);
// Which SIM module opcode a set of SC_RAW* flags asks for.
uint8_t sc_raw_device_cmd(smartcard_command_t flags);
bool sc_rx_bytes(uint8_t *dest, uint16_t *destlen, uint32_t wait);
//
bool GetATR(smart_card_atr_t *card_ptr, bool verbose);
@@ -70,6 +90,7 @@ void SmartCardRaw(const smart_card_raw_t *p);
void SmartCardUpgrade(uint64_t arg0);
void SmartCardSetBaud(uint64_t arg0);
void SmartCardSetClock(uint64_t arg0);
void SmartCardPPS(const smart_card_pps_t *p);
void I2C_print_status(void);
int I2C_get_version(uint8_t *major, uint8_t *minor);
+4 -2
View File
@@ -80,7 +80,9 @@ static void SmartCardDirectSend(uint8_t prepend, const smart_card_raw_t *p, uint
uint32_t wait = SIM_WAIT_DELAY;
if (((flags & SC_RAW) == SC_RAW) || ((flags & SC_RAW_T0) == SC_RAW_T0)) {
if (((flags & SC_RAW) == SC_RAW) ||
((flags & SC_RAW_T0) == SC_RAW_T0) ||
((flags & SC_RAW_T1) == SC_RAW_T1)) {
if ((flags & SC_WAIT) == SC_WAIT) {
// wait_delay is in ms; one WaitSCL_H_delay iteration is ~3.07us.
@@ -94,7 +96,7 @@ static void SmartCardDirectSend(uint8_t prepend, const smart_card_raw_t *p, uint
bool res = I2C_BufferWrite(
p->data,
p->len,
(((flags & SC_RAW_T0) == SC_RAW_T0) ? I2C_DEVICE_CMD_SEND_T0 : I2C_DEVICE_CMD_SEND),
sc_raw_device_cmd(flags),
I2C_DEVICE_ADDRESS_MAIN
);
+97 -4
View File
@@ -42,6 +42,97 @@
* @param resplen Pointer to the variable where the length of the response will be stored.
* @return Status code indicating success or failure of the operation.
*/
/*
* Offset of the 0xBD response node inside a SAM reply.
*
* Ahead of it sits a routing tail that is either 5 or 6 bytes long: the request
* header we build is always 6 (FROM, TO, REPLY-TO, 0x00, 0x00, scFlag), and
* some SAMs mirror all of it while others drop a byte. A HID iCLASS SE "Grace"
* part answers
*
* 0a 44 00 00 00 00 | bd 11 8a 0f 80 02 01 29 ...
*
* where SAM_RX_ASN1_PREFIX_LENGTH on its own lands one byte short and every
* caller then rejects a perfectly good response.
*
* Only those two offsets are ever considered, deliberately: 0xBD occurs inside
* SAM payloads as well, so an open ended search would eventually latch onto the
* wrong one. Returns 0 when neither holds it, which is never a valid offset.
*/
uint16_t sam_bd_offset(const uint8_t *response, uint16_t response_len) {
uint16_t fallback = 0;
for (uint16_t ofs = SAM_RX_ASN1_PREFIX_LENGTH;
ofs <= (uint16_t)(SAM_RX_ASN1_PREFIX_LENGTH + 1);
ofs++) {
if ((uint16_t)(ofs + 1) >= response_len) {
break;
}
if (response[ofs] != 0xBD) {
continue;
}
// A 0xBD in the right place accounts for the rest of the frame exactly:
// tag, length byte, that many bytes of contents, then SW1 SW2. This is
// what tells a real response node apart from a 0xBD that happens to sit
// in the routing tail - without it a SAM whose scFlag were 0xBD would
// resolve to the wrong offset.
if ((uint16_t)(ofs + 2 + response[ofs + 1] + 2) == response_len) {
return ofs;
}
if (fallback == 0) {
fallback = ofs;
}
}
// Nothing accounted for the whole frame; hand back a plain 0xBD match if
// there was one, so a caller that only wants the tag still works.
return fallback;
}
/*
* Locate the SAM's response node and work out how many bytes from there make up
* the reply to forward.
*
* This arithmetic used to be written out three times - twice in sam_picopass.c,
* once in sam_seos.c - each with a hardcoded 5 byte routing tail and no bounds
* checks at all, so a short or truncated frame walked off the end of the
* buffer. One copy, one place to be wrong.
*
* Returns the offset of the response node. *payload_len gets the length from
* that offset, clamped to what actually arrived, or 0 if the frame is too short
* to hold anything.
*/
uint16_t sam_response_payload(const uint8_t *rx, uint16_t rx_len, uint16_t *payload_len) {
uint16_t ofs = sam_bd_offset(rx, rx_len);
if (ofs == 0) {
ofs = SAM_RX_ASN1_PREFIX_LENGTH;
}
*payload_len = 0;
// SNMP shaped reply carries a long form length: bd 81 <len> 8a 81 ...
if (((uint16_t)(ofs + 4) < rx_len) &&
(rx[ofs + 1] == 0x81) && (rx[ofs + 3] == 0x8a) && (rx[ofs + 4] == 0x81)) {
*payload_len = (uint16_t)(rx[ofs + 2] + 3);
} else if ((uint16_t)(ofs + 1) < rx_len) {
*payload_len = (uint16_t)(rx[ofs + 1] + 2);
}
// never hand back more than arrived
if ((uint16_t)(ofs + *payload_len) > rx_len) {
*payload_len = (rx_len > ofs) ? (uint16_t)(rx_len - ofs) : 0;
}
return ofs;
}
int sam_rxtx(const uint8_t *data, uint16_t n, uint8_t *resp, uint16_t *resplen) {
bool res = I2C_BufferWrite(data, n, I2C_DEVICE_CMD_SEND_T0, I2C_DEVICE_ADDRESS_MAIN);
if (res == false) {
@@ -267,11 +358,12 @@ int sam_get_version(bool info) {
DbpString("end sam_get_version");
}
if (response[5] != 0xbd) {
uint16_t bd = sam_bd_offset(response, response_len);
if (bd == 0) {
Dbprintf("Invalid SAM response");
goto error;
} else {
uint8_t *sam_response_an = sam_find_asn1_node(response + 5, 0x8a);
uint8_t *sam_response_an = sam_find_asn1_node(response + bd, 0x8a);
if (sam_response_an == NULL) {
if (g_dbglevel >= DBG_ERROR) DbpString("SAM get response failed");
goto error;
@@ -344,11 +436,12 @@ int sam_get_serial_number(void) {
DbpString("end sam_get_serial_number");
}
if (response[5] != 0xbd) {
uint16_t bd = sam_bd_offset(response, response_len);
if (bd == 0) {
Dbprintf("Invalid SAM response");
goto error;
} else {
uint8_t *sam_response_an = sam_find_asn1_node(response + 5, 0x8a);
uint8_t *sam_response_an = sam_find_asn1_node(response + bd, 0x8a);
if (sam_response_an == NULL) {
if (g_dbglevel >= DBG_ERROR) DbpString(_RED_("SAM: get response failed"));
goto error;
+6
View File
@@ -22,6 +22,12 @@ static const uint8_t SAM_TX_APDU_PREFIX_LENGTH = 5;
static const uint8_t SAM_TX_ASN1_PREFIX_LENGTH = 6;
static const uint8_t SAM_RX_ASN1_PREFIX_LENGTH = 5;
// Offset of the 0xBD response node - 5 or 6 depending on the SAM. 0 if absent.
uint16_t sam_bd_offset(const uint8_t *response, uint16_t response_len);
// Offset of the response node plus how much of it to forward. See the .c file.
uint16_t sam_response_payload(const uint8_t *rx, uint16_t rx_len, uint16_t *payload_len);
int sam_rxtx(const uint8_t *data, uint16_t n, uint8_t *resp, uint16_t *resplen);
void switch_clock_to_ticks(void);
+21 -23
View File
@@ -227,10 +227,13 @@ static int sam_send_request_iso15(const uint8_t *const request, const uint8_t re
// 82 01
// 07
// 90 00
uint16_t plen = 0;
uint16_t ofs = sam_response_payload(sam_rx_buf, sam_rx_len, &plen);
if (request_len == 0) {
if (!(sam_rx_buf[5] == 0xbd && sam_rx_buf[5 + 2] == 0x8a && sam_rx_buf[5 + 4] == 0x03) &&
!(sam_rx_buf[5] == 0xbd && sam_rx_buf[5 + 2] == 0xb3 && sam_rx_buf[5 + 4] == 0xa0)) {
if (!(sam_rx_buf[ofs] == 0xbd && sam_rx_buf[ofs + 2] == 0x8a && sam_rx_buf[ofs + 4] == 0x03) &&
!(sam_rx_buf[ofs] == 0xbd && sam_rx_buf[ofs + 2] == 0xb3 && sam_rx_buf[ofs + 4] == 0xa0)) {
if (g_dbglevel >= DBG_ERROR) {
Dbprintf("No PACS data in SAM response");
@@ -239,17 +242,13 @@ static int sam_send_request_iso15(const uint8_t *const request, const uint8_t re
}
}
if (sam_rx_buf[6] == 0x81 && sam_rx_buf[8] == 0x8a && sam_rx_buf[9] == 0x81) { //check if the response is an SNMP message
*response_len = sam_rx_buf[5 + 2] + 3;
} else { //if not, use the old logic
*response_len = sam_rx_buf[5 + 1] + 2;
*response_len = (uint8_t)plen;
if (sam_rx_buf[ofs] == 0xBD && sam_rx_buf[ofs - 1] != 0x00) { //secure channel flag is not 0x00
Dbprintf(_YELLOW_("Secure channel flag set to: ")"%02x", sam_rx_buf[ofs - 1]);
}
if (sam_rx_buf[5] == 0xBD && sam_rx_buf[4] != 0x00) { //secure channel flag is not 0x00
Dbprintf(_YELLOW_("Secure channel flag set to: ")"%02x", sam_rx_buf[4]);
}
memcpy(response, sam_rx_buf + 5, *response_len);
memcpy(response, sam_rx_buf + ofs, *response_len);
goto out;
@@ -498,9 +497,12 @@ static int sam_send_request_emulated(const uint8_t *const request, const uint8_t
Dbhexdump(sam_rx_len, sam_rx_buf, false);
}
uint16_t plen = 0;
uint16_t ofs = sam_response_payload(sam_rx_buf, sam_rx_len, &plen);
if (request_len == 0) {
if (!(sam_rx_buf[5] == 0xbd && sam_rx_buf[5 + 2] == 0x8a && sam_rx_buf[5 + 4] == 0x03) &&
!(sam_rx_buf[5] == 0xbd && sam_rx_buf[5 + 2] == 0xb3 && sam_rx_buf[5 + 4] == 0xa0)) {
if (!(sam_rx_buf[ofs] == 0xbd && sam_rx_buf[ofs + 2] == 0x8a && sam_rx_buf[ofs + 4] == 0x03) &&
!(sam_rx_buf[ofs] == 0xbd && sam_rx_buf[ofs + 2] == 0xb3 && sam_rx_buf[ofs + 4] == 0xa0)) {
if (g_dbglevel >= DBG_ERROR) {
Dbprintf("No PACS data in SAM response");
@@ -512,17 +514,13 @@ static int sam_send_request_emulated(const uint8_t *const request, const uint8_t
}
}
if (sam_rx_buf[6] == 0x81 && sam_rx_buf[8] == 0x8a && sam_rx_buf[9] == 0x81) {
*response_len = sam_rx_buf[5 + 2] + 3;
} else {
*response_len = sam_rx_buf[5 + 1] + 2;
*response_len = (uint8_t)plen;
if (sam_rx_buf[ofs] == 0xBD && sam_rx_buf[ofs - 1] != 0x00) {
Dbprintf(_YELLOW_("Secure channel flag set to: ")"%02x", sam_rx_buf[ofs - 1]);
}
if (sam_rx_buf[5] == 0xBD && sam_rx_buf[4] != 0x00) {
Dbprintf(_YELLOW_("Secure channel flag set to: ")"%02x", sam_rx_buf[4]);
}
memcpy(response, sam_rx_buf + 5, *response_len);
memcpy(response, sam_rx_buf + ofs, *response_len);
goto out;
@@ -583,7 +581,7 @@ static int sam_set_card_detected_picopass(const picopass_hdr_t *card_select) {
// 8a 00 <- empty response (accepted)
// 90 00
if (response[5] != 0xbd) {
if (sam_bd_offset(response, response_len) == 0) {
if (g_dbglevel >= DBG_ERROR)
Dbprintf("Invalid SAM response");
goto error;
+8 -5
View File
@@ -90,7 +90,7 @@ static int sam_set_card_detected_seos(iso14a_card_select_t *card_select) {
// 8a 00 <- empty response (accepted)
// 90 00
if (response[5] != 0xbd) {
if (sam_bd_offset(response, response_len) == 0) {
if (g_dbglevel >= DBG_ERROR)
Dbprintf("Invalid SAM response");
goto error;
@@ -234,11 +234,14 @@ static int sam_send_request_iso14a(const uint8_t *const request, const uint8_t r
// 82 01
// 07
// 90 00
uint16_t plen = 0;
uint16_t ofs = sam_response_payload(sam_rx_buf, sam_rx_len, &plen);
if (request_len == 0) {
if (
!(sam_rx_buf[5] == 0xbd && sam_rx_buf[5 + 2] == 0x8a && sam_rx_buf[5 + 4] == 0x03) &&
!(sam_rx_buf[5] == 0xbd && sam_rx_buf[5 + 2] == 0xb3 && sam_rx_buf[5 + 4] == 0xa0)
!(sam_rx_buf[ofs] == 0xbd && sam_rx_buf[ofs + 2] == 0x8a && sam_rx_buf[ofs + 4] == 0x03) &&
!(sam_rx_buf[ofs] == 0xbd && sam_rx_buf[ofs + 2] == 0xb3 && sam_rx_buf[ofs + 4] == 0xa0)
) {
if (g_dbglevel >= DBG_ERROR) {
@@ -248,8 +251,8 @@ static int sam_send_request_iso14a(const uint8_t *const request, const uint8_t r
}
}
*response_len = sam_rx_buf[5 + 1] + 2;
memcpy(response, sam_rx_buf + 5, *response_len);
*response_len = (uint8_t)plen;
memcpy(response, sam_rx_buf + ofs, *response_len);
out:
BigBuf_free();
+220 -39
View File
@@ -327,7 +327,43 @@ static int smart_wait(uint8_t *out, int maxoutlen, bool verbose) {
return -1;
}
static int smart_responseEx(uint8_t *out, int maxoutlen, bool verbose) {
// Which class byte a GET RESPONSE following a 61xx / 9Fxx should carry.
//
// There is no rule that can be derived from the command's own class, because
// two cards that both use CLA 'A0' disagree:
//
// - a GSM 11.11 / TS 51.011 SIM answers 6D00 to '00 C0 ...' and needs 'A0 C0'
// - a HID iCLASS SE SAM answers 6D00 to 'A0 C0 ...' and needs '00 C0'
//
// and EMV (Book 1, 9.3.1) fixes GET RESPONSE at '00' even after a proprietary
// '80' command. So '00' is tried first - the historical behaviour, right for
// EMV and for the SAM - and a card that rejects the class gets one retry with
// the class of the command that produced the status word.
#define GETRESP_TRY_FIRST 0
#define GETRESP_TRY_RETRY 1
static uint8_t get_response_cla(uint8_t cla, int attempt) {
if (attempt == GETRESP_TRY_FIRST) {
// class '00', keeping only the logical channel bits
return (uint8_t)(cla & 0x03);
}
return cla;
}
// 6D00 / 6E00: the card did not recognise the instruction or the class.
static bool getresp_class_rejected(const uint8_t *sw, int len) {
if (len < 2) {
return false;
}
return ((sw[len - 2] == 0x6D) || (sw[len - 2] == 0x6E));
}
// cla - class byte of the command whose response we are fetching.
// proto - SC_RAW, SC_RAW_T0 or SC_RAW_T1, the protocol the GET RESPONSE must
// go out on. It has to match the command that produced the 61xx/9Fxx:
// a bare APDU pushed onto a T=1 link is not a block and the card will
// not answer it.
static int smart_responseEx(uint8_t *out, int maxoutlen, bool verbose, uint8_t cla, smartcard_command_t proto) {
int datalen = smart_wait(out, maxoutlen, verbose);
int totallen = datalen;
@@ -364,22 +400,43 @@ static int smart_responseEx(uint8_t *out, int maxoutlen, bool verbose) {
if (verbose) PrintAndLogEx(INFO, "Requesting " _YELLOW_("0x%02X") " bytes response", len);
uint8_t cmd_getresp[] = {0x00, ISO7816_GET_RESPONSE, 0x00, 0x00, len};
smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
if (payload == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
goto out;
// '00' first, then one retry with the command's own class if the card
// rejects it - see get_response_cla() for why neither works everywhere.
for (int attempt = GETRESP_TRY_FIRST; attempt <= GETRESP_TRY_RETRY; attempt++) {
uint8_t cmd_getresp[] = {
get_response_cla(cla, attempt), ISO7816_GET_RESPONSE, 0x00, 0x00, len
};
if (attempt == GETRESP_TRY_RETRY) {
if (cmd_getresp[0] == get_response_cla(cla, GETRESP_TRY_FIRST)) {
break; // the retry would send the same thing
}
if (verbose) {
PrintAndLogEx(INFO, "GetResponse refused, retrying with CLA %02X", cmd_getresp[0]);
}
}
smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
if (payload == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
goto out;
}
payload->flags = proto | SC_LOG;
payload->len = sizeof(cmd_getresp);
payload->wait_delay = 0;
memcpy(payload->data, cmd_getresp, sizeof(cmd_getresp));
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
free(payload);
datalen = smart_wait(&out[ofs], maxoutlen, verbose);
if (getresp_class_rejected(&out[ofs], datalen) == false) {
break;
}
}
payload->flags = SC_RAW | SC_LOG;
payload->len = sizeof(cmd_getresp);
payload->wait_delay = 0;
memcpy(payload->data, cmd_getresp, sizeof(cmd_getresp));
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
free(payload);
datalen = smart_wait(&out[ofs], maxoutlen, verbose);
if (datalen < 2) {
goto out;
@@ -403,7 +460,10 @@ static int smart_responseEx(uint8_t *out, int maxoutlen, bool verbose) {
} else {
// wrong length
if (verbose) {
PrintAndLogEx(WARNING, "GetResponse wrong length. Must be 0x%02X got 0x%02X", len, datalen - 3);
// datalen - 3 goes negative when the card answered with a
// bare status word, and printing that as %02X rendered it
// as 0xFFFFFFFF. Report what actually arrived instead.
PrintAndLogEx(WARNING, "GetResponse wrong length. Expected 0x%02X data bytes, got %d byte(s)", len, datalen);
}
}
}
@@ -413,8 +473,8 @@ out:
return totallen;
}
static int smart_response(uint8_t *out, int maxoutlen) {
return smart_responseEx(out, maxoutlen, true);
static int smart_response(uint8_t *out, int maxoutlen, uint8_t cla, smartcard_command_t proto) {
return smart_responseEx(out, maxoutlen, true, cla, proto);
}
static int CmdSmartRaw(const char *Cmd) {
@@ -424,7 +484,9 @@ static int CmdSmartRaw(const char *Cmd) {
"smart raw -s -0 -d 00a404000e315041592e5359532e4444463031 -> `1PAY.SYS.DDF01` PPSE directory with get ATR\n"
"smart raw -0 -d 00a404000e325041592e5359532e4444463031 -> `2PAY.SYS.DDF01` PPSE directory\n"
"smart raw -0 -t -d 00a4040007a0000000041010 -> Mastercard\n"
"smart raw -0 -t -d 00a4040007a0000000031010 -> Visa"
"smart raw -0 -t -d 00a4040007a0000000031010 -> Visa\n"
"smart raw -1 -s -d 00a404000e325041592e5359532e444446303100 -> PPSE over T=1\n"
" (T=1 carries the whole APDU, so case 4 needs its Le)"
);
void *argtable[] = {
@@ -434,6 +496,7 @@ static int CmdSmartRaw(const char *Cmd) {
arg_lit0("s", NULL, "active smartcard with select (get ATR)"),
arg_lit0("t", "tlv", "executes TLV decoder if it possible"),
arg_lit0("0", NULL, "use protocol T=0"),
arg_lit0("1", NULL, "use protocol T=1 (needs SIM module fw v4.51+)"),
arg_int0(NULL, "timeout", "<ms>", "Timeout in MS waiting for SIM to respond. (def 337ms)"),
arg_str1("d", "data", "<hex>", "bytes to send"),
arg_param_end
@@ -445,11 +508,12 @@ static int CmdSmartRaw(const char *Cmd) {
bool active_select = arg_get_lit(ctx, 3);
bool decode_tlv = arg_get_lit(ctx, 4);
bool use_t0 = arg_get_lit(ctx, 5);
int timeout = arg_get_int_def(ctx, 6, -1);
bool use_t1 = arg_get_lit(ctx, 6);
int timeout = arg_get_int_def(ctx, 7, -1);
int dlen = 0;
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
int res = CLIParamHexToBuf(arg_get_str(ctx, 7), data, sizeof(data), &dlen);
int res = CLIParamHexToBuf(arg_get_str(ctx, 8), data, sizeof(data), &dlen);
CLIParserFree(ctx);
if (res) {
@@ -457,6 +521,11 @@ static int CmdSmartRaw(const char *Cmd) {
return PM3_EINVARG;
}
if (use_t0 && use_t1) {
PrintAndLogEx(FAILED, "Choose either -0 or -1, not both");
return PM3_EINVARG;
}
smart_card_raw_t *payload = calloc(1, sizeof(smart_card_raw_t) + dlen);
if (payload == NULL) {
PrintAndLogEx(WARNING, "Failed to allocate memory");
@@ -480,11 +549,18 @@ static int CmdSmartRaw(const char *Cmd) {
}
PrintAndLogEx(DEBUG, "SIM Card timeout... %u ms", payload->wait_delay);
// The protocol the exchange runs on. It is reused for any GET RESPONSE the
// answer turns out to need, so the follow-up cannot end up on a different
// one than the command it belongs to.
smartcard_command_t proto = SC_RAW;
if (use_t1) {
proto = SC_RAW_T1;
} else if (use_t0) {
proto = SC_RAW_T0;
}
if (dlen > 0) {
if (use_t0)
payload->flags |= SC_RAW_T0;
else
payload->flags |= SC_RAW;
payload->flags |= proto;
}
uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
@@ -502,22 +578,25 @@ static int CmdSmartRaw(const char *Cmd) {
}
// reading response from smart card
int len = smart_response(buf, PM3_CMD_DATA_SIZE);
int len = smart_response(buf, PM3_CMD_DATA_SIZE, (dlen > 0) ? data[0] : 0x00, proto);
if (len < 0) {
free(payload);
free(buf);
return PM3_ESOFT;
}
if (buf[0] == 0x6C) {
// 6Cxx says "wrong Le, use xx". Test the status word where it actually
// lives: buf[0] is only the SW when the answer is a bare status word, and
// on a zero length answer it is whatever the previous exchange left behind.
if (len >= 2 && dlen > 4 && buf[len - 2] == 0x6C) {
// request more bytes to download
data[4] = buf[1];
data[4] = buf[len - 1];
memcpy(payload->data, data, dlen);
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + dlen);
len = smart_response(buf, PM3_CMD_DATA_SIZE);
len = smart_response(buf, PM3_CMD_DATA_SIZE, data[0], proto);
data[4] = 0;
}
@@ -835,6 +914,107 @@ static int CmdSmartReader(const char *Cmd) {
return PM3_SUCCESS;
}
// ISO/IEC 7816-3 tables 7 and 8, so the negotiated rate can be printed back.
static const uint16_t pps_fi_table[16] = {
372, 372, 558, 744, 1116, 1488, 1860, 0,
0, 512, 768, 1024, 1536, 2048, 0, 0
};
static const uint8_t pps_di_table[16] = {
0, 1, 2, 4, 8, 16, 32, 64,
12, 20, 0, 0, 0, 0, 0, 0
};
static int CmdSmartPPS(const char *Cmd) {
CLIParserContext *ctx;
CLIParserInit(&ctx, "smart pps",
"Run an ISO 7816-3 protocol and parameter selection exchange.\n"
"The card is reset and its ATR read first, because PPS is only\n"
"legal in the window straight after the ATR.\n"
"\n"
"Note `smart raw -1` already switches a card to T=1 by itself when\n"
"the ATR offers it; this is for negotiating Fi/Di explicitly.\n"
"Needs SIM module firmware v4.51 or newer.",
"smart pps -1 -> select T=1\n"
"smart pps -0 -> select T=0\n"
"smart pps -1 --ta1 96 -> select T=1 and F=512 / D=32"
);
void *argtable[] = {
arg_param_begin,
arg_lit0("0", NULL, "select protocol T=0"),
arg_lit0("1", NULL, "select protocol T=1 (default)"),
arg_str0(NULL, "ta1", "<hex>", "also negotiate this TA1 (FI << 4 | DI)"),
arg_param_end
};
CLIExecWithReturn(ctx, Cmd, argtable, true);
bool use_t0 = arg_get_lit(ctx, 1);
bool use_t1 = arg_get_lit(ctx, 2);
int ta1len = 0;
uint8_t ta1[1] = {0};
int res = CLIParamHexToBuf(arg_get_str(ctx, 3), ta1, sizeof(ta1), &ta1len);
CLIParserFree(ctx);
if (res) {
PrintAndLogEx(FAILED, "Error parsing TA1");
return PM3_EINVARG;
}
if (use_t0 && use_t1) {
PrintAndLogEx(FAILED, "Choose either -0 or -1, not both");
return PM3_EINVARG;
}
smart_card_pps_t payload = {
.protocol = use_t0 ? 0 : 1,
.ta1 = (ta1len > 0) ? ta1[0] : 0x11,
.use_ta1 = (ta1len > 0) ? 1 : 0,
};
clearCommandBuffer();
SendCommandNG(CMD_SMART_PPS, (uint8_t *)&payload, sizeof(payload));
PacketResponseNG resp;
if (WaitForResponseTimeout(CMD_SMART_PPS, &resp, 4000) == false) {
PrintAndLogEx(WARNING, "smart card timeout");
return PM3_ETIMEOUT;
}
if (resp.status != PM3_SUCCESS || resp.length < 3) {
PrintAndLogEx(FAILED, "PPS exchange failed");
return PM3_ESOFT;
}
const uint8_t *r = resp.data.asBytes;
bool ok = (r[0] != 0);
uint8_t proto = r[1];
uint8_t got_ta1 = r[2];
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(INFO, "--- " _CYAN_("PPS") " ---------------------------");
PrintAndLogEx(INFO, "Result.......... %s", ok ? _GREEN_("accepted") : _RED_("refused"));
PrintAndLogEx(INFO, "Protocol........ T=%u", proto);
PrintAndLogEx(INFO, "TA1............. 0x%02X", got_ta1);
uint16_t fi = pps_fi_table[(got_ta1 >> 4) & 0x0F];
uint8_t di = pps_di_table[got_ta1 & 0x0F];
if (fi && di) {
PrintAndLogEx(INFO, " Fi / Di....... %u / %u", fi, di);
PrintAndLogEx(INFO, " Cycles/ETU.... %u", fi / di);
PrintAndLogEx(INFO, " bits/sec ..... %u at 4 MHz", 4000000U / (fi / di));
} else {
PrintAndLogEx(INFO, " Fi / Di....... " _YELLOW_("RFU"));
}
PrintAndLogEx(NORMAL, "");
if (ok == false) {
return PM3_ESOFT;
}
return PM3_SUCCESS;
}
static int CmdSmartSetClock(const char *Cmd) {
CLIParserContext *ctx;
@@ -940,7 +1120,7 @@ static void smart_brute_prim(void) {
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + 5);
free(payload);
int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false, get_card_data[i], SC_RAW);
if (len > 2) {
PrintAndLogEx(SUCCESS, "\tHEX %d |: %s", len, sprint_hex(buf, len));
}
@@ -990,15 +1170,15 @@ static int smart_brute_sfi(bool decodeTLV) {
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(READ_RECORD));
len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false, READ_RECORD[0], SC_RAW);
if (buf[0] == 0x6C) {
READ_RECORD[4] = buf[1];
if (len >= 2 && buf[len - 2] == 0x6C) {
READ_RECORD[4] = buf[len - 1];
memcpy(payload->data, READ_RECORD, sizeof(READ_RECORD));
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(READ_RECORD));
len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false, READ_RECORD[0], SC_RAW);
READ_RECORD[4] = 0;
}
@@ -1049,7 +1229,7 @@ static void smart_brute_options(bool decodeTLV) {
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + sizeof(GET_PROCESSING_OPTIONS));
free(payload);
int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false, GET_PROCESSING_OPTIONS[0], SC_RAW);
if (len > 4) {
PrintAndLogEx(SUCCESS, "Got processing options");
if (decodeTLV) {
@@ -1171,7 +1351,7 @@ static int CmdSmartBruteforceSFI(const char *Cmd) {
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + hexlen);
free(payload);
int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false);
int len = smart_responseEx(buf, PM3_CMD_DATA_SIZE, false, (hexlen > 0) ? cmddata[0] : 0x00, SC_RAW);
if (len < 3) {
continue;
}
@@ -1439,6 +1619,7 @@ static command_t CommandTable[] = {
{"brute", CmdSmartBruteforceSFI, IfPm3Smartcard, "Bruteforce SFI"},
{"info", CmdSmartInfo, IfPm3Smartcard, "Tag information"},
{"pcsc", CmdPCSC, AlwaysAvailable, "Turn pm3 into pcsc reader and relay to host OS via vpcd"},
{"pps", CmdSmartPPS, IfPm3Smartcard, "Run an ISO 7816-3 PPS exchange"},
{"reader", CmdSmartReader, IfPm3Smartcard, "Act like an IS07816 reader"},
{"raw", CmdSmartRaw, IfPm3Smartcard, "Send raw hex data to tag"},
{"upgrade", CmdSmartUpgrade, AlwaysAvailable, "Upgrade sim module firmware"},
@@ -1477,7 +1658,7 @@ int ExchangeAPDUSC(bool verbose, uint8_t *datain, int datainlen, bool activateCa
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + datainlen);
int len = smart_responseEx(dataout, maxdataoutlen, verbose);
int len = smart_responseEx(dataout, maxdataoutlen, verbose, (datainlen > 0) ? datain[0] : 0x00, SC_RAW);
if (len < 0) {
free(payload);
return PM3_ESOFT;
@@ -1494,7 +1675,7 @@ int ExchangeAPDUSC(bool verbose, uint8_t *datain, int datainlen, bool activateCa
clearCommandBuffer();
SendCommandNG(CMD_SMART_RAW, (uint8_t *)payload, sizeof(smart_card_raw_t) + 5);
datain[4] = 0;
len = smart_responseEx(dataout, maxdataoutlen, verbose);
len = smart_responseEx(dataout, maxdataoutlen, verbose, datain[0], SC_RAW);
if (len < 0) {
free(payload);
return PM3_ESOFT;
+11 -1
View File
@@ -501,15 +501,24 @@ typedef enum SMARTCARD_COMMAND {
SC_CLEARLOG = (1 << 5),
SC_LOG = (1 << 6),
SC_WAIT = (1 << 7),
SC_RAW_T1 = (1 << 8),
} smartcard_command_t;
typedef struct {
uint8_t flags;
// 16 bit since SC_RAW_T1 took the ninth flag. Note this is a wire struct:
// client and ARM image have to be built and flashed together.
uint16_t flags;
uint32_t wait_delay;
uint16_t len;
uint8_t data[];
} PACKED smart_card_raw_t;
typedef struct {
uint8_t protocol; // T to select, 0 or 1
uint8_t ta1; // FI << 4 | DI, only read when use_ta1 is set
uint8_t use_ta1;
} PACKED smart_card_pps_t;
typedef struct {
uint8_t factory_info_version;
uint8_t ecdsa_secp256k1_signature[64];
@@ -622,6 +631,7 @@ typedef struct {
#define CMD_SMART_ATR 0x0143
#define CMD_SMART_SETBAUD 0x0144
#define CMD_SMART_SETCLOCK 0x0145
#define CMD_SMART_PPS 0x0146
// RDV40, FPC USART
#define CMD_USART_RX 0x0160