Files
proxmark3/armsrc/i2c_direct.c
T
Antiklesys d5d00bce0a smartcard-i2c-fixes
## armsrc: smartcard / I2C correctness + SAM compatibility fixes

A focused pass over `armsrc/i2c.{c,h}` and `armsrc/i2c_direct.c` addressing correctness bugs (NULL deref on alloc failure, unbounded recursion, write-failure silently falling through to read), and removing two long-standing SAM-compatibility blockers (`SmartCardSetBaud` was a stub; float in firmware hot path).

### Fixed

- **`SmartCardRaw`: BigBuf_calloc result was unchecked.** NULL deref on memory pressure crashed the firmware. Now bails with `PM3_EMALLOC` before touching `resp[]`.
- **`SmartCardRaw`: `I2C_BufferWrite` failure was only acted on at `dbglevel > 3`.** Lower debug levels silently fell through to `sc_rx_bytes()` reading from a card we never wrote to. The `reply_ng` / `goto OUT` path now runs on any write failure; the `Dbprintf` is the only thing gated on dbglevel.
- **`SmartCardRaw`: replaced float division** `(p->wait_delay * 1000) / 3.07` with integer math via `uint64_t`. Avoids pulling `__aeabi_fdiv` into the ARM image and removes overflow at large `wait_delay` values: `wait = (ms * 100000 + 153) / 307`.
- **`SmartCardUpgrade`: BigBuf_calloc result was unchecked.** Now bails with `PM3_EMALLOC`. Renamed local `verfiydata` typo to `verifydata`. Failure messages now include the offset where the upgrade aborted (`Writing failed at offset 0x%04X` instead of `Writing failed`).
- **`I2C_BufferRead`: rejected `len == 0` but accepted `len == 1`**, which cannot represent the SIM module's 2-byte BE length header (returned -1 cast through int16_t). Tightened to `len < 2`.
- **`WaitSCL_L_timeout`: `return (delay == 0)` was dead code** — post-decrement underflows `delay` to `UINT32_MAX` after the loop, so the expression was always false. Replaced with explicit `return false` and corrected the comment that claimed an 1800 ms cap (actual cap is 1200 ms).
- **`i2c.h`: SIM_WAIT_DELAY comment was wrong** — `150000 * 3.07us = 460 ms`, not 270 ms. Updated comment to match the actual value; constant unchanged.
- **`SmartCardDirectSend`: BigBuf_calloc result for `resp[]` was unchecked.** The next `resp[0] = prepend` would NULL-deref on alloc failure. Now bails.
- **`SmartCardDirectSend`: GET RESPONSE (61xx) chain recursed without bound**, allocating a fresh `smart_card_raw_t` from BigBuf each round. A misbehaving card returning 61xx every time would wedge the device. Added `depth` parameter capped at `SC_DIRECT_MAX_DEPTH` (8); both call sites updated. The GET RESPONSE inner allocation is also now NULL-checked.
- **`SmartCardDirectSend`: same write-failure-silent fix** as `SmartCardRaw`.
- **`SmartCardDirectSend`: same float → integer-math conversion** as `SmartCardRaw`.

### Added

- **`SmartCardSetBaud` is now functional.** Was an empty stub (wired through `pm3_cmd.h` / `appmain.c` dispatch but did nothing). Now sends `I2C_DEVICE_CMD_SETBAUD` (0x04) to the SIM module's main address.

### Notes for follow-up

- `SmartCardSetBaud` is now functional on the firmware side, but no client command exposes it — `client/src/cmdsmartcard.c` has no `setbaud` subcommand. A separate change can wire `CMD_SMART_SETBAUD` into the client if needed; leaving it out of this patch keeps it firmware-only and safe to backport.
- The proxmark3 SIM module's stock asm firmware (`sim013`) silently drops `CMD_SETBAUD`. gentilkiwi's `sim_c` v4.50+ also currently dispatches it to a no-op. Full PPS follow-through requires a SIM-firmware-side patch in addition to this commit.
- Mid-byte SCL stretch timeouts in `I2C_SendByte` / `I2C_ReadByte` are still swallowed (return void / -1, both ignored at most callers). Fixing this requires changing those signatures and verifying every caller — out of scope here, merits its own PR.
2026-05-10 14:35:16 +08:00

233 lines
6.9 KiB
C

// //-----------------------------------------------------------------------------
// Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// See LICENSE.txt for the text of the license.
//-----------------------------------------------------------------------------
// The main i2c code, for communications with smart card module
//-----------------------------------------------------------------------------
#include <inttypes.h>
#include "BigBuf.h"
#include "iso14443a.h"
#include "BigBuf.h"
#include "string.h"
#include "mifareutil.h"
#include "fpgaloader.h"
#include "proxmark3_arm.h"
#include "cmd.h"
#include "protocols.h"
#include "appmain.h"
#include "util.h"
#include "commonutil.h"
#include "crc16.h"
#include "dbprint.h"
#include "ticks.h"
#include "i2c.h"
#include "i2c_direct.h"
// Maximum chained ISO 7816-4 GET RESPONSE (61xx) follow-ups before bailing.
// A misbehaving card that always returns 61xx would otherwise recurse without
// bound, allocating fresh smart_card_raw_t payloads from BigBuf each time
// until the device wedges. Eight rounds is more than any legitimate APDU
// chain would need.
#define SC_DIRECT_MAX_DEPTH 8
static void SmartCardDirectSend(uint8_t prepend, const smart_card_raw_t *p, uint8_t *output, uint16_t *olen, uint8_t depth) {
LED_D_ON();
uint16_t len = 0;
uint8_t *resp = BigBuf_calloc(ISO7816_MAX_FRAME);
if (resp == NULL) {
Dbprintf("SmartCardDirectSend: BigBuf_calloc failed");
if (olen) *olen = 0;
LEDsoff();
return;
}
resp[0] = prepend;
smartcard_command_t flags = p->flags;
if ((flags & SC_LOG) == SC_LOG)
set_tracing(true);
else
set_tracing(false);
if ((flags & SC_CONNECT) == SC_CONNECT) {
I2C_Reset_EnterMainProgram();
if ((flags & SC_SELECT) == SC_SELECT) {
smart_card_atr_t card;
bool gotATR = GetATR(&card, true);
if (gotATR == false) {
Dbprintf("No ATR received...\n");
goto OUT;
}
}
}
uint32_t wait = SIM_WAIT_DELAY;
if (((flags & SC_RAW) == SC_RAW) || ((flags & SC_RAW_T0) == SC_RAW_T0)) {
if ((flags & SC_WAIT) == SC_WAIT) {
// wait_delay is in ms; one WaitSCL_H_delay iteration is ~3.07us.
// Integer-only conversion via uint64_t to avoid soft-float and
// avoid overflow at large wait_delay values.
wait = (uint32_t)(((uint64_t)p->wait_delay * 100000U + 153U) / 307U);
}
LogTrace(p->data, p->len, 0, 0, NULL, true);
bool res = I2C_BufferWrite(
p->data,
p->len,
(((flags & SC_RAW_T0) == SC_RAW_T0) ? I2C_DEVICE_CMD_SEND_T0 : I2C_DEVICE_CMD_SEND),
I2C_DEVICE_ADDRESS_MAIN
);
if (res == false) {
if (g_dbglevel > 3) {
Dbprintf("SmartCardDirectSend: I2C_BufferWrite failed");
}
goto OUT;
}
// read bytes from module
len = ISO7816_MAX_FRAME;
res = sc_rx_bytes(&resp[1], &len, wait);
if (res) {
LogTrace(&resp[1], len, 0, 0, NULL, false);
} else {
len = 0;
}
}
if (len == 2 && resp[1] == 0x61) {
if (depth >= SC_DIRECT_MAX_DEPTH) {
Dbprintf("SmartCardDirectSend: GET RESPONSE chain depth (%u) exceeded; aborting", depth);
goto OUT;
}
uint8_t cmd_getresp[] = {0x00, ISO7816_GET_RESPONSE, 0x00, 0x00, resp[2]};
smart_card_raw_t *payload = (smart_card_raw_t *)BigBuf_calloc(sizeof(smart_card_raw_t) + sizeof(cmd_getresp));
if (payload == NULL) {
Dbprintf("SmartCardDirectSend: GET RESPONSE alloc failed");
goto OUT;
}
payload->flags = SC_RAW | SC_LOG;
payload->len = sizeof(cmd_getresp);
payload->wait_delay = 0;
memcpy(payload->data, cmd_getresp, sizeof(cmd_getresp));
SmartCardDirectSend(prepend, payload, output, olen, depth + 1);
} else if (len == 2) {
Dbprintf("***** BAD response from card (response unsupported)...");
Dbhexdump(3, &resp[0], false);
resp[0] = prepend;
resp[1] = 0x6a;
resp[2] = 0x82;
AddCrc14A(resp, 3);
memcpy(output, resp, 5);
*olen = 5;
}
if (resp[1] == 0x6a && resp[2] == 0x82) {
Dbprintf("***** bad response from card (file not found)...");
resp[0] = prepend;
resp[1] = 0x6a;
resp[2] = 0x82;
AddCrc14A(resp, 3);
memcpy(output, resp, 5);
*olen = 5;
FpgaDisableTracing();
}
if (len > 2) {
Dbprintf("***** sending it over the wire... len: %d =>\n", len);
resp[1] = prepend;
AddCrc14A(&resp[1], len);
Dbhexdump(len + 2, &resp[1], false);
BigBuf_free();
if (prepend == 0xff) {
Dbprintf("pdol request, we can ignore the response...");
return;
}
memcpy(output, &resp[1], len + 2);
*olen = len + 2;
BigBuf_free();
}
OUT:
LEDsoff();
}
int CmdSmartRaw(const uint8_t prepend, const uint8_t *data, int dlen, uint8_t *output, uint16_t *olen) {
Dbprintf("sending command to smart card... %02x %02x %02x... =>", prepend, data[0], data[1]);
Dbhexdump(dlen, data, false);
if (data[4] + 5 != dlen) {
Dbprintf("invalid length of data. Received: %d, command specifies %d", dlen, data[4] + 5);
dlen = data[4] + 5;
}
smart_card_raw_t *payload = (smart_card_raw_t *)BigBuf_calloc(sizeof(smart_card_raw_t) + dlen);
if (payload == NULL) {
Dbprintf("Failed to allocate memory");
return PM3_EMALLOC;
}
payload->len = dlen;
memcpy(payload->data, data, dlen);
payload->flags = SC_LOG;
bool active = true;
bool active_select = false;
int timeout = 600;
bool use_t0 = true;
if (active || active_select) {
payload->flags |= (SC_CONNECT | SC_CLEARLOG);
if (active_select)
payload->flags |= SC_SELECT;
}
payload->wait_delay = 0;
if (timeout > -1) {
payload->flags |= SC_WAIT;
payload->wait_delay = timeout;
}
if (dlen > 0) {
if (use_t0)
payload->flags |= SC_RAW_T0;
else
payload->flags |= SC_RAW;
}
SmartCardDirectSend(prepend, payload, output, olen, 0);
return PM3_SUCCESS;
}