Fix defects found in a code sweep and a TRM cross-check

Security Engine: CTR ignored its input and returned the raw keystream;
CBC encrypt skipped the IV on the first block and saved the wrong
chaining value, so every CMAC over more than one block was wrong; OFB
was broken. The datapath now follows INPUT_SEL/XOR_POS/VCTRAM_SEL the
way bdk drives it, and matches OpenSSL for ECB, CBC, OFB, CTR and
CMAC. SHA-256 works in parts (SHA_CONTINUE), SE_OP_CTX_SAVE reads keys
back as se_aes_ctx_get_keys() expects, unwrap honours the word quad,
guest block counts and LL sizes are bounded, and unreachable buffers
end the op with an error.

Soft reboot now resets the whole SoC (GPIO/pinmux cache, UARTs, I2C,
PMC, CAR, flow controller, SE, touch, SDMMC, display, ACTMON, ...)
while keeping what hardware keeps (PMC SCRATCH0, the RTC, and the PMIC
unless the reboot is a power cycle). DRAM gets fresh zero pages
instead of a memset that made all 2 GB resident; stale BPMP
translations are dropped; CPSR returns to SVC; scripts restart.

Execution: a branch to address 0 no longer hangs the emulator
(until=0 made PC 0 an exit); bdk's reset-then-bpmp_halt() reboots
instead of exiting; an untimed halt with CPU0 running parks the BPMP
and lets CPU0 continue; CPU0 starts in the same batch it is released
in; CPU0 drops translations of pages the BPMP rewrote; shared models
no longer see time run backwards.

TRM cross-check: RST_CPUG_CMPLX resets to 0x2000feef and CPU0 runs on
CPURESET0/CORERESET0/L2RESET/NONCPURESET (bit names corrected); RAM
repair clears REQ and sets STS, and is no longer a run condition;
refused releases are re-evaluated; MSELECT ENABLE_PCIE_APERTURE gates
PCIe; RST_DEVICES_W/Y direct writes land; DL_UP is read-only; the
whole config aperture and memory window decode; OSC_CTRL reports
38.4 MHz; PLLE/PLLREFE no longer get bit 27 forced into a divider;
PMC is a R/W register file; RTC SECONDS counts; FLOW halt modes follow
17.2.2 and STOP_UNTIL_IRQ wakes on the armed TMR; UART IIR/IER/
loopback MSR; I2C NOACK code and empty I2C4/I2C6 buses; pinmux reset
values; the COP ACTMON counts halt time.

Peripherals: MAX77620 LDO power-good follows the rail (hwtest's
gamecard probe no longer fails), the Erista GPU MAX77621 answers at
0x1C, regulators ACK per generation, RTC CONTROL is binary/24h, PS3
card detect reads "slot empty", packet-mode I2C parses 4 bytes per
word, rawnand I/O splits at part boundaries, eMMC returns to its user
area on CMD0, ADMA2 descriptors decode per spec, SD CMD6/ACMD13 data
reaches the programmed buffer, ERR_INTERRUPT is reported, R1 follows
block commands.

Frontend and tooling: touch events queue instead of overwriting each
other, map through rotation overrides and bdk's edge offset, and use
finger ID 0; a scripted press is always seen before its release;
zeroed fuses persist in the ini; dropped UTF-8 paths open on Windows;
bad --input-script is an error; test scripts check exit status and
missing arguments; make_sd.py quotes names and picks a FAT32-valid
cluster size; the Dockerfile marks the mount safe for git.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
This commit is contained in:
Claude committed 2026-09-25 17:45:02 +00:00
1 parent 11ad2e4d9f
commit 6753c5f3db
26 files changed
+1615 -588

No files matched your search

+20 -4
View File
@@ -153,7 +153,16 @@ uint32_t count_insns(uc_engine *uc, const EmuState *s, uint64_t addr,
// A payload that jumps into zeroed memory executes `movs r0, r0` (Thumb
// 0x0000) or `andeq r0, r0, r0` (ARM) until it hits something. No compiler
// emits sixteen zero bytes at the start of a block, so that is the signal.
bool nop_slide(const EmuState *s, uint64_t addr) {
// The low 16 MB (a null function pointer lands there; the iROM has no
// contents) is zero-filled RAM too, read through the engine as it is not
// one of the host views.
bool nop_slide(uc_engine *uc, const EmuState *s, uint64_t addr) {
static const uint8_t zero[16] = {0};
if (addr < 0x01000000) {
uint8_t buf[16];
return uc_mem_read(uc, addr, buf, sizeof(buf)) == UC_ERR_OK &&
memcmp(buf, zero, sizeof(zero)) == 0;
}
bool in_range = (addr >= 0x40030000 && addr < IRAM_BASE + IRAM_SIZE) ||
(addr >= DRAM_BASE && addr < DRAM_BASE + DRAM_WINDOW_SIZE);
if (!in_range)
@@ -161,7 +170,6 @@ bool nop_slide(const EmuState *s, uint64_t addr) {
const uint8_t *p = code_ptr(s, addr, 16);
if (!p)
return false;
static const uint8_t zero[16] = {0};
return memcmp(p, zero, sizeof(zero)) == 0;
}
@@ -178,7 +186,7 @@ void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *ud) {
return;
}
if (nop_slide(s, address)) {
if (nop_slide(uc, s, address)) {
if (!clk.nop_slide_reported) {
clk.nop_slide_reported = true;
printf("\n[emu] NOP-slide detected at 0x%08llX (zeroed memory being "
@@ -220,7 +228,11 @@ uc_err bpmp_run(uc_engine *uc, EmuState *state, uint64_t begin,
uint64_t max_insns) {
clk.limit = state->insn_count + (max_insns ? max_insns : 1);
clk.pending = 0;
uc_err err = uc_emu_start(uc, begin, 0, 0, 0);
// `until` must be an address the core can never reach. 0 is not one: a
// null function pointer took the BPMP there, and from then on every start
// returned at once without running anything - the main loop spun forever
// waiting for instructions to retire. The PC is 32 bits wide.
uc_err err = uc_emu_start(uc, begin, 1ULL << 32, 0, 0);
// If something other than the budget ended the run (an MMIO handler
// calling uc_emu_stop, a fault), the block in flight has still run to its
// end - Unicorn only checks for a stop between blocks - so credit it.
@@ -244,3 +256,7 @@ uint32_t bpmp_timerus_read(EmuState *state) {
void bpmp_clock_jumped() {
clk.polling = false;
}
void bpmp_yield() {
clk.limit = 0;
}
+6
View File
@@ -45,4 +45,10 @@ uint32_t bpmp_timerus_read(EmuState *state);
// halt): whatever poll loop was being paced is over.
void bpmp_clock_jumped();
// End the current batch at the next block boundary - a clean stop, unlike
// uc_emu_stop() from an MMIO callback, which abandons the block in flight
// with the PC back at its start. Used when CPU0 is released, so its first
// slice starts now rather than a whole batch later.
void bpmp_yield();
#endif // T210_BPMP_H
+103 -23
View File
@@ -1,7 +1,10 @@
#include "ccplex.h"
#include "bpmp.h"
#include <cstdio>
#include <cstring>
#include <vector>
#include <memory>
#include <unicorn/unicorn.h>
@@ -27,10 +30,14 @@
#define CLK_V_MSELECT 3
#define CAR_RST_CPUG_CMPLX_SET 0x450
#define CAR_RST_CPUG_CMPLX_CLR 0x454
// The bits ccplex_boot_cpu0() clears for CPU0 - CPURESET0, DBGRESET0,
// CORERESET0 and bit 30 - and NONCPURESET, which it clears first. The core
// runs once all five are clear.
#define RST_CPU0_MASK ((1u << 0) | (1u << 16) | (1u << 24) | (1u << 30))
// RST_CPUG_CMPLX (TRM 5.2.152, reset 0x2000feef). CPU0 runs once nCPUPORESET
// (CPURESET0, bit 0), nCORERESET (CORERESET0, bit 16), nL2RESET (bit 24) and
// the nonCPU region's reset (NONCPURESET, bit 29) are all released.
// ccplex_boot_cpu0() also clears PRESETDBG (bit 30), but that only resets
// the CoreSight debug logic, which a core runs without; the DBGRESET/
// WDRESET/DERESET bits in 15:4 are reserved on this SoC.
#define RST_CPUG_CMPLX_RESET 0x2000FEEFu
#define RST_CPU0_MASK ((1u << 0) | (1u << 16) | (1u << 24))
#define RST_NONCPU (1u << 29)
// SB block, SYSREG + 0x200.
@@ -94,7 +101,7 @@ namespace {
enum class Cpu0 { Off, Running, Hung };
struct Model {
uint32_t rst_cpug = 0xFFFFFFFFu; // everything held at power-on
uint32_t rst_cpug = RST_CPUG_CMPLX_RESET;
uint32_t clk_enb_v = 0;
uint32_t cclk_burst = 0;
uint32_t pllx_base = 0;
@@ -122,6 +129,15 @@ struct Model {
Model m;
EmuState *g_state = nullptr;
// Pages CPU0 has executed code from, with the bytes it translated; see
// drop_stale_code().
struct CodePage {
uint64_t base;
uint8_t bytes[4096];
};
std::vector<std::unique_ptr<CodePage>> code_pages;
uint64_t last_code_page = ~0ULL;
uc_hook h_block, h_unmapped, h_intr;
bool held() { return (m.rst_cpug & (RST_CPU0_MASK | RST_NONCPU)) != 0; }
@@ -162,8 +178,6 @@ const char *boot_blocked(EmuState *state) {
return "CCLK runs from PLLX but PLLX is disabled";
if (!(m.clk_enb_v & (1u << CLK_V_MSELECT))) return "MSELECT clock disabled";
if (!pcie_mselect_up()) return "MSELECT still in reset";
if (!flow_ram_repair_done())
return "fast-cluster RAM repair never requested (FLOW_CTLR_RAM_REPAIR)";
if (!(m.sb_rst_lo & SB_AA64_RST_AARCH64_MODE_EN))
return "SB_AA64_RESET_LOW has no AArch64 vector (AArch32 CPU boot is not modelled)";
if (!entry_mapped(entry_vector())) return "reset vector outside IRAM/DRAM";
@@ -171,6 +185,8 @@ const char *boot_blocked(EmuState *state) {
}
void destroy_engine() {
code_pages.clear();
last_code_page = ~0ULL;
if (!m.uc)
return;
mmio_unmap_bus(m.uc);
@@ -199,6 +215,43 @@ void stop_cpu0(const char *why) {
// ---- CPU0 engine hooks ---------------------------------------------------
// ---- Code the BPMP rewrites under CPU0 ----------------------------------
//
// Stores the BPMP makes into shared DRAM/IRAM go through its own engine, so
// this engine's translation cache never hears of them: a stub loaded for a
// new job at the address of the last one would run the old one's code. A
// full flush before every slice cures that but costs tens of milliseconds a
// time (it walks the page descriptors of the whole 44-bit space), so instead
// the pages CPU0 has executed from are remembered with a copy of their
// bytes, and before each slice any that changed have just their own
// translations dropped.
void note_code_page(uint64_t address) {
uint64_t base = address & ~0xFFFULL;
if (base == last_code_page)
return;
last_code_page = base;
for (auto &p : code_pages)
if (p->base == base)
return;
const uint8_t *src = host_ptr(base, 4096);
if (!src || code_pages.size() >= 256)
return;
auto p = std::make_unique<CodePage>();
p->base = base;
memcpy(p->bytes, src, 4096);
code_pages.push_back(std::move(p));
}
void drop_stale_code() {
for (auto &p : code_pages) {
const uint8_t *now = host_ptr(p->base, 4096);
if (!now || memcmp(now, p->bytes, 4096) == 0)
continue;
uc_ctl_remove_cache(m.uc, p->base, p->base + 4096);
memcpy(p->bytes, now, 4096);
}
}
void commit_pending() {
m.ns += m.pending * NS_PER_INSN;
m.retired += m.pending;
@@ -228,6 +281,7 @@ void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *) {
uc_emu_stop(uc);
return;
}
note_code_page(address);
// Every A64 instruction is four bytes.
m.pending = size >= 4 ? size / 4 : 1;
if (const uint8_t *p = host_ptr(address + size - 4, 4)) {
@@ -288,8 +342,9 @@ bool start_cpu0(EmuState *state) {
// IRAM, DRAM and TZRAM are the same host memory the BPMP engine maps, so
// a stub the BPMP copies into DRAM and the mailbox both cores poll are one
// set of bytes. CPU0's engine is new on every release, so it cannot hold
// stale translations of code the BPMP has rewritten since the last boot.
// set of bytes. Stores from the other engine bypass this one's self-
// modifying-code tracking, so ccplex_run() drops its translations before
// every slice.
err = uc_mem_map_ptr(uc, IRAM_BASE, IRAM_SIZE, UC_PROT_ALL, state->iram_ptr);
if (err == UC_ERR_OK)
err = uc_mem_map_ptr(uc, DRAM_BASE, DRAM_WINDOW_SIZE, UC_PROT_ALL,
@@ -330,6 +385,10 @@ bool start_cpu0(EmuState *state) {
m.bus_accesses = 0;
m.cpu0 = Cpu0::Running;
m.boots++;
// Released from a BPMP register write: end the BPMP's batch at the next
// block so CPU0's first slice starts now, not up to a batch (~10 ms) later.
if (g_bus_master == BUS_BPMP)
bpmp_yield();
printf("[ccplex] CPU0 released: AArch64 EL3, MMU off, entry 0x%08llX "
"(boot #%u)\n", (unsigned long long)entry, m.boots);
fflush(stdout);
@@ -352,6 +411,14 @@ void try_release(EmuState *state) {
start_cpu0(state);
}
// Out of reset but refused: on silicon the core simply starts the moment the
// last missing piece (clock, partition, rail, vector) arrives, so every such
// change looks again.
void maybe_release(EmuState *state) {
if (m.cpu0 == Cpu0::Off && !held() && state)
try_release(state);
}
} // namespace
// ==========================================================================
@@ -375,10 +442,10 @@ void ccplex_reset(EmuState *state) {
void ccplex_car_write(EmuState *state, uint32_t offset, uint32_t val) {
switch (offset) {
case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; break;
case CAR_PLLX_BASE: m.pllx_base = val; break;
case CAR_CLK_OUT_ENB_V: m.clk_enb_v = val; break;
case CAR_CLK_ENB_V_SET: m.clk_enb_v |= val; break;
case CAR_CCLK_BURST_POLICY: m.cclk_burst = val; maybe_release(state); break;
case CAR_PLLX_BASE: m.pllx_base = val; maybe_release(state); break;
case CAR_CLK_OUT_ENB_V: m.clk_enb_v = val; maybe_release(state); break;
case CAR_CLK_ENB_V_SET: m.clk_enb_v |= val; maybe_release(state); break;
case CAR_CLK_ENB_V_CLR:
m.clk_enb_v &= ~val;
if ((val & (1u << CLK_V_CPUG)) && m.cpu0 == Cpu0::Running) {
@@ -430,24 +497,23 @@ uint32_t ccplex_sb_read(uint32_t offset) {
}
void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val) {
(void)state;
switch (offset) {
case SB_CSR:
// NS_RST_VEC_WR_DIS (bit 1) is sticky until reset. It only locks out
// non-secure writers; the BPMP is secure, so the vector stays writable
// from here either way.
// non-secure writers, and the vector write below does not check it.
m.sb_csr |= val;
break;
case SB_AA64_RESET_LOW: m.sb_rst_lo = val; break;
case SB_AA64_RESET_HIGH: m.sb_rst_hi = val; break;
case SB_AA64_RESET_LOW: m.sb_rst_lo = val; maybe_release(state); break;
case SB_AA64_RESET_HIGH: m.sb_rst_hi = val & 0xFFF; maybe_release(state); break;
default: break;
}
}
void ccplex_partition_changed(EmuState *state, int part, bool on) {
(void)state;
if (on)
if (on) {
maybe_release(state);
return;
}
if (part == POWER_RAIL_CRAIL) stop_cpu0("CRAIL partition powergated");
if (part == POWER_RAIL_C0NC) stop_cpu0("C0NC partition powergated");
if (part == POWER_RAIL_CE0) stop_cpu0("CE0 partition powergated");
@@ -456,14 +522,20 @@ void ccplex_partition_changed(EmuState *state, int part, bool on) {
void ccplex_rail_changed(EmuState *state) {
if (m.cpu0 != Cpu0::Off && !cpu_rail_on(state))
stop_cpu0("CPU rail switched off");
else
maybe_release(state);
}
void ccplex_preconditions_changed(EmuState *state) { maybe_release(state); }
void ccplex_bus_tick(EmuState *state) {
m.ns += NS_PER_BUS_ACCESS;
m.bus_accesses++;
state->emu_usec = m.ns / 1000;
}
uint64_t ccplex_now_us() { return m.ns / 1000; }
bool ccplex_cpu0_running() { return m.cpu0 == Cpu0::Running && m.uc; }
void ccplex_run(EmuState *state, uint64_t until_us) {
@@ -474,8 +546,12 @@ void ccplex_run(EmuState *state, uint64_t until_us) {
return;
// While CPU0 runs, it is the bus master and "now" is its clock: every
// register model reads state->emu_usec, and must see CPU0's time, not the
// BPMP's. Both are put back afterwards.
// register model reads state->emu_usec, and must see CPU0's time - a
// model timing CPU0's own sequence (PERST# after Trefclkstable, say) has
// to measure it on the clock CPU0 waits on. Both are put back afterwards.
// CPU0 trails the BPMP by up to a slice, so a model both cores touch sees
// time step back at the switch; such models must not assume `now` only
// grows.
uint64_t bpmp_usec = state->emu_usec;
BusMaster prev = g_bus_master;
g_bus_master = BUS_CPU0;
@@ -483,7 +559,11 @@ void ccplex_run(EmuState *state, uint64_t until_us) {
m.target_ns = target;
m.in_run = true;
uc_err err = uc_emu_start(m.uc, m.pc, 0, 0, 0);
drop_stale_code();
// `until` is an address an A64 PC can never hold (it is not 4-aligned).
// 0 would make a branch to address 0 end every slice before it starts.
uc_err err = uc_emu_start(m.uc, m.pc, ~0ULL, 0, 0);
commit_pending();
uc_reg_read(m.uc, UC_ARM64_REG_PC, &m.pc);
+7
View File
@@ -44,6 +44,13 @@ void ccplex_sb_write(EmuState *state, uint32_t offset, uint32_t val);
void ccplex_partition_changed(EmuState *state, int part, bool on);
void ccplex_rail_changed(EmuState *state);
// Something CPU0 needs in order to run changed (MSELECT reset released, ...):
// a core already out of reset but refused starts if nothing is missing now.
void ccplex_preconditions_changed(EmuState *state);
// CPU0's own clock, in emulated microseconds: what TIMERUS reads from CPU0.
uint64_t ccplex_now_us();
// Called by the MMIO front-end for every access CPU0 makes: charges the bus
// latency to CPU0's clock before the access is dispatched.
void ccplex_bus_tick(EmuState *state);
+26 -10
View File
@@ -132,17 +132,15 @@ void push_controller_ready() {
if (ev_stack.size() < 32) ev_stack.push_back(ev);
}
// If SDL has flagged a pending touch event, pack it into the FTS4 stack.
// Move whatever SDL has queued into the FTS4 event stack, oldest first.
void try_emit_pending_touch(EmuState *state) {
bool was_pending = state->tc_event_pending.exchange(false);
if (!was_pending) return;
uint8_t op = state->tc_event_op.load();
uint16_t x = state->tc_x.load();
uint16_t y = state->tc_y.load();
// pressure: a small non-zero value keeps z below the 500-palm-reject threshold
// in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
uint16_t pressure = (op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
push_event(op, state->tc_finger_id, x, y, pressure);
EmuState::TouchEvent ev;
while (ev_stack.size() < 32 && state->touch_take(&ev)) {
// pressure: a small non-zero value keeps z below the 500-palm-reject
// threshold in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
uint16_t pressure = (ev.op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
push_event(ev.op, state->tc_finger_id, ev.x, ev.y, pressure);
}
}
// Pop oldest event into 8-byte buffer; on empty, return NO_EVENT.
@@ -307,6 +305,24 @@ uint32_t pull_rx_word() {
} // namespace
void i2c3_reset(EmuState *state) {
slave_addr = 0;
dir_read = false;
cmd_data[0] = cmd_data[1] = 0;
last_cnfg = 0;
pkt_state = PKT_HDR_W1;
pkt_size = pkt_recv = 0;
pkt_is_combined = false;
tx_buf.clear();
rx_buf.clear();
rx_pos = 0;
ev_stack.clear();
EmuState::TouchEvent ev;
while (state->touch_take(&ev)) {
}
state->tc_pressed = false;
}
uint32_t i2c3_read(EmuState *state, uint64_t addr) {
uint32_t offset = (uint32_t)(addr - I2C3_BASE);
switch (offset) {
+4
View File
@@ -12,4 +12,8 @@ struct EmuState;
uint32_t i2c3_read(EmuState *state, uint64_t addr);
void i2c3_write(EmuState *state, uint64_t addr, uint32_t val);
// Soft reboot: controller and touch controller back to power-on, with no
// events left over from the previous run.
void i2c3_reset(EmuState *state);
#endif
+13 -9
View File
@@ -67,7 +67,10 @@ constexpr uint64_t I2C2_BASE = 0x7000C400; // GEN2_I2C, Rohm BH1730 ALS at slave
constexpr uint64_t I2C2_SIZE = 0x100;
constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49
constexpr uint64_t I2C5_BASE = 0x7000D000;
constexpr uint64_t I2C_SIZE = 0x1000;
constexpr uint64_t I2C_SIZE = 0x1000; // the MMIO page: I2C5, I2C6, SPI2B
constexpr uint64_t I2C_CTRL_SIZE = 0x100; // one controller's registers
constexpr uint64_t I2C4_BASE = 0x7000C700;
constexpr uint64_t I2C6_BASE = 0x7000D100;
constexpr uint64_t I2C3_SIZE = 0x100;
// PWM
@@ -203,12 +206,13 @@ constexpr uint64_t XUSB_PADCTL_SIZE = 0x1000;
// bdk's MMU table defines DRAM and IRAM entries only and leaves the fallback
// entry RWX, so PCIe space is reachable and uncached.
//
// Only the windows a payload actually touches are mapped: 16 KiB covering
// both root ports plus PADS and AFI, 128 KiB of configuration aperture (bus
// 0 and bus 1 are all that exist), and one 4 KiB page of downstream memory
// for the endpoint's BAR0 register window. Mapping the architectural sizes
// (256 MiB of config, 208 MiB of memory) would cost the host gigabytes for
// address ranges nothing ever reads.
// These are MMIO windows (callbacks, no backing memory), so they are mapped
// at their architectural sizes: the whole 256 MiB configuration aperture -
// extended registers sit at AXI[27:24] - and the non-prefetchable memory
// window to the end of PCIE_A2, wherever software places the endpoint's BARs.
// A smaller map left a CPU0 access to, say, config offset 0x100 or BAR0 +
// 0x2000 unmapped: nothing answered and the core wedged, where silicon
// returns data or all-ones.
constexpr uint64_t PCIE_RP0_BASE = 0x01000000; // root port 0 registers
constexpr uint64_t PCIE_RP1_BASE = 0x01001000; // root port 1 registers
constexpr uint64_t PCIE_PADS_BASE = 0x01003000;
@@ -216,9 +220,9 @@ constexpr uint64_t PCIE_AFI_BASE = 0x01003800;
constexpr uint64_t PCIE_BLOCK_BASE = 0x01000000;
constexpr uint64_t PCIE_BLOCK_SIZE = 0x4000;
constexpr uint64_t PCIE_CS_BASE = 0x02000000; // type-1 extended config
constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x20000; // buses 0 and 1 only
constexpr uint64_t PCIE_CS_MODEL_SIZE = 0x10000000; // all of it: 256 MiB
constexpr uint64_t PCIE_MEM_BASE = 0x13000000; // non-prefetchable window
constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x1000;
constexpr uint64_t PCIE_MEM_MODEL_SIZE = 0x0D000000; // up to the end of A2
// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE)
constexpr uint64_t TSEC_BASE = 0x54500000;
+628 -233
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -44,13 +44,17 @@ void mmio_bus_write(EmuState *state, uint64_t addr, unsigned size,
uint64_t value);
// Reset the per-run peripheral state that a soft reboot must not carry over.
void mmio_soft_reset(EmuState *state);
// `power_cycle`: the PMIC reset too (its register files return to their
// seeds); otherwise only the SoC reset (PMC MAIN_RST) and the PMIC keeps
// its rails.
void mmio_soft_reset(EmuState *state, bool power_cycle);
// PMC power-partition state (APBDEV_PMC_PWRGATE_STATUS bit `part`).
bool pmc_partition_on(int part);
// FLOW_CTLR_RAM_REPAIR has been requested (the fast cluster's RAMs repaired).
bool flow_ram_repair_done();
// APBDEV_PMC_SECURE_SCRATCH`n` (n = 0..7), written by hardware: the SE
// deposits its context-save key there.
void pmc_secure_scratch_write(unsigned n, uint32_t value);
// True when the CCPLEX CPU rail is up: the MAX77621 on Erista (enabled, and
// its EN pin driven by MAX77620 GPIO5), the MAX77812 M4 phase on Mariko.
+59 -10
View File
@@ -1,4 +1,5 @@
#include "pcie.h"
#include "ccplex.h"
#include <cstdio>
#include <cstring>
@@ -115,6 +116,7 @@ static constexpr uint64_t T_REFCLK_STABLE_US = 10000; // refclk -> PERST# high
// stub reads straight after the BPMP has cycled the AFI reset - xbar X4_X1 in
// bits 23:20 and root port 1 disabled (bit 2) until software clears it.
static constexpr uint32_t MSELECT_CONFIG_RESET = 0x07FF4020;
static constexpr uint32_t MSELECT_CFG_ENABLE_PCIE_APERTURE = 1u << 5;
static constexpr uint32_t AFI_PCIE_CONFIG_RESET = 0x00103025;
// Broadcom identity (brcm_hw_ids.h, brcmfmac/pcie.c).
@@ -227,9 +229,8 @@ bool radio_core_alive(EmuState *state) {
// hardware this is the difference between a register read and a dead
// console, so it is checked before every single access rather than folded
// into the link-training preconditions.
// Everything this emulator executes is BPMP code - Unicorn runs the ARM7,
// there is no CCPLEX model - and the BPMP cannot reach PCIe on real silicon.
// Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
// The BPMP cannot reach PCIe on real silicon; only a CPU-complex master can
// (CPU0, t210/ccplex.cpp). Measured on an Erista and a Mariko: with clocks, resets, power and PLLE all
// correct, the AFI window reads 0xFFFFFFFF and every offset of MSELECT reads
// one constant. The TRM agrees (ch.19: BPMP-Lite is an AHB master, PCIe is
// not an AHB slave; ch.16: MSELECT is CPU-complex hardware), and so does the
@@ -272,6 +273,21 @@ void mselect_complain(uint64_t addr) {
fflush(stdout);
}
// MSELECT_CONFIG bit 5, ENABLE_PCIE_APERTURE (TRM 16.3.1, set at reset):
// with it clear MSELECT does not route the PCIe apertures at all.
static bool pcie_aperture_enabled(uint64_t addr) {
if (pcie.mselect[0] & MSELECT_CFG_ENABLE_PCIE_APERTURE)
return true;
static bool warned = false;
if (!warned) {
warned = true;
printf("[pcie] access to %08X with MSELECT_CONFIG.ENABLE_PCIE_APERTURE "
"clear: MSELECT does not route it\n", (unsigned)addr);
fflush(stdout);
}
return false;
}
const char *link_blocked(EmuState *state, int port) {
if (!mselect_up()) return "MSELECT still in reset";
if (pcie.powergated) return "PCIE partition still gated";
@@ -394,7 +410,8 @@ void pcie_wl_reg_on(EmuState *state, bool level) {
// ---- clock and reset controller -----------------------------------------
void pcie_car_write(uint32_t offset, uint32_t val) {
void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val) {
bool mselect_was_up = mselect_up();
switch (offset) {
case CAR_RST_DEVICES_U: pcie.rst_u = val; break;
case CAR_CLK_OUT_ENB_U: pcie.enb_u = val; break;
@@ -409,12 +426,17 @@ void pcie_car_write(uint32_t offset, uint32_t val) {
case CAR_RST_DEVICES_V: pcie.rst_v = val; break;
case CAR_RST_DEV_V_SET: pcie.rst_v |= val; break;
case CAR_RST_DEV_V_CLR: pcie.rst_v &= ~val; break;
case CAR_RST_DEVICES_W: pcie.rst_w = val; break;
case CAR_RST_DEV_W_SET: pcie.rst_w |= val; break;
case CAR_RST_DEV_W_CLR: pcie.rst_w &= ~val; break;
case CAR_RST_DEVICES_Y: pcie.rst_y = val; break;
case CAR_PLLE_BASE: pcie.plle = (val & PLLE_BASE_ENABLE) != 0; break;
case CAR_PLLREFE_BASE: pcie.pllrefe = (val & PLLREFE_BASE_ENABLE) != 0; break;
default: break;
}
// MSELECT out of reset is one of the things CPU0 waits on.
if (!mselect_was_up && mselect_up())
ccplex_preconditions_changed(state);
}
// PLLE and PLLREFE do not follow the generic "ENABLE bit 30, LOCK bit 27 in
@@ -467,6 +489,9 @@ uint32_t mselect_read(EmuState *state, uint64_t addr) {
void mselect_write(EmuState *state, uint64_t addr, uint32_t val) {
(void)state;
// Writes from the BPMP go nowhere either, as with the AFI window.
if (bpmp_pcie_denied(addr))
return;
uint32_t off = (uint32_t)(addr - MSELECT_BASE) & 0xFFC;
// Held in reset, MSELECT latches nothing - which is exactly the state a
// payload is in when it thinks it configured the fabric and did not.
@@ -635,6 +660,8 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
mselect_complain(addr);
return 0xFFFFFFFF;
}
if (!pcie_aperture_enabled(addr))
return 0xFFFFFFFF;
// Root port register windows, 0x01000000 and 0x01001000.
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
@@ -679,10 +706,14 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F;
uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC;
uint32_t fn = (a >> 8) & 0x7;
// Register number: {AXI[27:24], AXI[7:0]} (TRM 34.3.3).
uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
link_update(state, 1);
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
return 0xFFFFFFFF; // unsupported request -> all ones
if (reg >= sizeof(pcie.ep))
return 0; // no extended capabilities
return pcie.ep[reg / 4];
}
@@ -695,13 +726,24 @@ uint32_t pcie_read(EmuState *state, uint64_t addr) {
return 0xFFFFFFFF;
if (!(pcie.ep[0x04 / 4] & 0x2)) // MEM space disabled
return 0xFFFFFFFF;
if ((pcie.ep[0x10 / 4] & ~0xFu) != PCIE_MEM_BASE) // BAR0 unassigned
// Decode against wherever software put the BARs: BAR0 is the 32 KiB
// register window (backplane window in its first 4 KiB, core
// registers above), BAR2 the 2 MiB TCM. Anything else is claimed by
// no function: all ones.
uint32_t a32 = (uint32_t)addr;
uint32_t bar0 = pcie.ep[0x10 / 4] & EP_BAR0_MASK;
uint32_t bar2 = pcie.ep[0x18 / 4] & EP_BAR2_MASK;
bool in_bar0 = bar0 && (a32 & EP_BAR0_MASK) == bar0;
bool in_bar2 = bar2 && (a32 & EP_BAR2_MASK) == bar2;
if (!in_bar0 && !in_bar2)
return 0xFFFFFFFF;
if (!radio_core_alive(state))
return 0xFFFFFFFF; // front-end answers, the die does not
if (in_bar2 || (a32 - bar0) >= 0x1000)
return 0; // modelled as quiet registers / RAM
uint32_t win = pcie.ep[BRCM_BAR0_WINDOW / 4] & ~0xFFFu;
uint32_t bp = win + ((uint32_t)(addr - PCIE_MEM_BASE) & 0xFFF);
uint32_t bp = win + ((a32 - bar0) & 0xFFF);
if (bp == BRCM_SI_ENUM_BASE)
return BRCM_4356_CHIPID;
return 0;
@@ -718,10 +760,15 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
mselect_complain(addr);
return;
}
if (!pcie_aperture_enabled(addr))
return;
if (addr >= PCIE_RP0_BASE && addr < PCIE_RP0_BASE + 0x2000) {
int port = (addr >= PCIE_RP1_BASE) ? 1 : 0;
pcie.rp[port].reg[(uint32_t)(addr & 0xFFC) / 4] = val;
uint32_t off = (uint32_t)(addr & 0xFFC);
if (off == RP_VEND_XP)
val &= ~RP_VEND_XP_DL_UP; // read-only: the link state
pcie.rp[port].reg[off / 4] = val;
return;
}
@@ -738,8 +785,10 @@ void pcie_write(EmuState *state, uint64_t addr, uint32_t val) {
if (addr >= PCIE_CS_BASE && addr < PCIE_CS_BASE + PCIE_CS_MODEL_SIZE) {
uint32_t a = (uint32_t)(addr - PCIE_CS_BASE);
uint32_t bus = (a >> 16) & 0xFF, dev = (a >> 11) & 0x1F;
uint32_t fn = (a >> 8) & 0x7, reg = a & 0xFC;
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state))
uint32_t fn = (a >> 8) & 0x7;
uint32_t reg = ((a >> 16) & 0xF00) | (a & 0xFC);
if (bus != 1 || dev != 0 || fn != 0 || !ep_reachable(state) ||
reg >= sizeof(pcie.ep))
return;
switch (reg) {
case 0x04: // command: only the low half is RW
+11 -8
View File
@@ -15,17 +15,20 @@ struct EmuState;
* (0x02000000), the endpoint's BAR0 backplane window, and the UPHY PLL P0
* calibration/lock state machine in the XUSB pad controller.
*
* The link only trains when the payload has satisfied every precondition
* real silicon and the CYW4356 datasheet impose -- power partition, clocks,
* resets, PLLE, UPHY, lane mux, IDDQ, and the refclk/PERST#/POR timing of
* Table 62. A payload that skips one gets a link that stays down and a
* `[pcie]` line on stdout naming what it missed.
* The link only trains once the payload has satisfied the preconditions
* this model checks -- power partition, AFI clock, resets, PLLE, UPHY, lane
* mux, IDDQ, and the refclk/PERST#/POR timing of Table 62. A payload that
* skips one gets a link that stays down and a `[pcie]` line on stdout naming
* what it missed. Not every step of the TRM's bring-up (34.3) is checked:
* the PCIe clock enable, PRSNT_MAP, PEX_BIAS_PWRD, the PEX_L1_RST_N pinmux
* and the AUX_MUX_LP0 clamps are not, so a sequence that leaves one out can
* train here and not on silicon.
*/
void pcie_reset(EmuState *state);
// 0x01000000..0x01003FFF (root ports, PADS, AFI), 0x02000000 config
// aperture, and the 0x13000000 BAR0 memory window.
// 0x01000000..0x01003FFF (root ports, PADS, AFI), the 0x02000000 config
// aperture and the 0x13000000 non-prefetchable memory window.
uint32_t pcie_read(EmuState *state, uint64_t addr);
void pcie_write(EmuState *state, uint64_t addr, uint32_t val);
@@ -40,7 +43,7 @@ void padctl_write(EmuState *state, uint64_t addr, uint32_t val);
// Clock-and-reset forwarding. The PCIe model needs PLLE/PLLREFE lock and the
// PCIE/AFI/PCIEXCLK/UPHY reset+enable bits, all of which live in CAR.
// pcie_car_read returns true when it wants to override the CAR model's answer.
void pcie_car_write(uint32_t offset, uint32_t val);
void pcie_car_write(EmuState *state, uint32_t offset, uint32_t val);
bool pcie_car_read(uint32_t offset, uint32_t *out);
// MSELECT clocked out of reset (RST_DEV_V bit 3 clear). The CCPLEX needs it
+265 -152
View File
@@ -1,12 +1,14 @@
#include "se_engine.h"
#include "../emu_state.h"
#include "memory_map.h"
#include "mmio.h"
#include <unicorn/unicorn.h>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <vector>
// =============================================================================
// Tegra X1 Security Engine (SE) emulation
@@ -41,25 +43,20 @@ static const uint32_t K[64] = {
#define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
uint32_t H[8] = {
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
};
// Total padded length: msg + 0x80 + zeros + 8-byte length, multiple of 64
uint64_t bitlen = (uint64_t)len * 8;
uint32_t padded_len = ((len + 1 + 8 + 63) / 64) * 64;
uint8_t *buf = (uint8_t*)std::calloc(1, padded_len);
std::memcpy(buf, msg, len);
buf[len] = 0x80;
for (int i = 0; i < 8; i++) buf[padded_len - 1 - i] = (uint8_t)(bitlen >> (i * 8));
for (uint32_t off = 0; off < padded_len; off += 64) {
static const uint32_t H0[8] = {
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
};
// Compress `nblocks` 64-byte blocks into the running state H.
static void blocks(uint32_t H[8], const uint8_t *p, size_t nblocks) {
for (size_t blk = 0; blk < nblocks; blk++, p += 64) {
uint32_t W[64];
for (int i = 0; i < 16; i++) {
W[i] = ((uint32_t)buf[off + i*4 + 0] << 24) |
((uint32_t)buf[off + i*4 + 1] << 16) |
((uint32_t)buf[off + i*4 + 2] << 8) |
((uint32_t)buf[off + i*4 + 3]);
W[i] = ((uint32_t)p[i*4 + 0] << 24) |
((uint32_t)p[i*4 + 1] << 16) |
((uint32_t)p[i*4 + 2] << 8) |
((uint32_t)p[i*4 + 3]);
}
for (int i = 16; i < 64; i++) {
uint32_t s0 = ROR32(W[i-15],7) ^ ROR32(W[i-15],18) ^ (W[i-15] >> 3);
@@ -79,13 +76,23 @@ static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d;
H[4]+=e; H[5]+=f; H[6]+=g; H[7]+=h;
}
std::free(buf);
for (int i = 0; i < 8; i++) {
out[i*4 + 0] = (uint8_t)(H[i] >> 24);
out[i*4 + 1] = (uint8_t)(H[i] >> 16);
out[i*4 + 2] = (uint8_t)(H[i] >> 8);
out[i*4 + 3] = (uint8_t)(H[i]);
}
}
// Hash the last `len` bytes of a message whose total length is `total_bits`,
// padding as FIPS 180-4 requires. Whole blocks go straight through; only the
// tail is copied.
static void final(uint32_t H[8], const uint8_t *msg, size_t len,
uint64_t total_bits) {
size_t whole = len / 64;
blocks(H, msg, whole);
uint8_t tail[128] = {0};
size_t rest = len - whole * 64;
std::memcpy(tail, msg + whole * 64, rest);
tail[rest] = 0x80;
size_t tail_len = (rest + 1 + 8 <= 64) ? 64 : 128;
for (int i = 0; i < 8; i++)
tail[tail_len - 1 - i] = (uint8_t)(total_bits >> (i * 8));
blocks(H, tail, tail_len / 64);
}
#undef ROR32
@@ -249,8 +256,33 @@ constexpr uint32_t SE_RNG_CONFIG_REG = 0x340;
constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords
constexpr uint32_t SE_STATUS_REG = 0x800;
constexpr uint32_t SE_ERR_STATUS_REG = 0x804;
constexpr uint32_t SE_CONTEXT_SAVE_CONFIG_REG = 0x070;
constexpr uint32_t SE_SHA_CONFIG_REG = 0x200;
constexpr uint32_t SE_SHA_MSG_LENGTH_REG = 0x204; // 4 dwords, in bits
constexpr uint32_t SE_SHA_MSG_LEFT_REG = 0x214; // 4 dwords, in bits
constexpr uint32_t SE_INT_OP_DONE = 1u << 4;
constexpr uint32_t SE_INT_ERR_STAT = 1u << 16;
constexpr uint32_t SE_OP_START = 1;
constexpr uint32_t SE_OP_CTX_SAVE = 3;
constexpr uint32_t ALG_RNG = 2;
constexpr uint32_t ALG_SHA = 3;
constexpr uint32_t MODE_SHA256 = 5;
constexpr uint32_t DST_SRK = 3;
constexpr uint32_t DST_RSAREG = 4;
constexpr uint32_t SHA_INIT_HASH = 1;
// SE_CONTEXT_SAVE_CONFIG: source in 31:29, AES key index in 11:8, word quad
// in 1:0 (bdk se_t210.h).
constexpr uint32_t CTX_SRC_AES_KEYTABLE = 2;
constexpr uint32_t CTX_SRC_SRK = 6;
// A linked-list entry's size field is 24 bits (bdk masks it the same way),
// which also bounds how much one operation can move: 16 MiB, 2^20 blocks.
constexpr uint32_t LL_SIZE_MASK = 0xFFFFFF;
constexpr uint32_t MAX_AES_BLOCKS = (LL_SIZE_MASK + 1) / 16;
constexpr uint32_t ALG_NOP = 0;
constexpr uint32_t ALG_AES_DEC = 1;
@@ -312,106 +344,141 @@ static uint32_t reg_err_status = 0;
static uint32_t reg_rng_config = 0;
static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs
// Secure random key for context save, and the CBC chain the saved blocks
// are encrypted under. See ctx_save().
static uint8_t srk[16] = {0};
static uint8_t ctx_chain[16] = {0};
// LL descriptor: { num, addr, size }. Hekate often uses num=0 (single descriptor).
struct LLDesc { uint32_t num, addr, size; };
static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) {
if (!ll_addr) return false;
if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false;
out->size &= LL_SIZE_MASK;
return true;
}
// Encrypt/decrypt a buffer in-place using the keyslot's key (assumes 128-bit).
// The operation touched memory it cannot reach: finish with an error, which
// bdk's _se_op_wait() reports instead of handing back a buffer of zeros.
static void op_fail(const char *what, uint32_t addr) {
std::printf("[se] %s: cannot access 0x%08X - operation failed\n", what, addr);
reg_int_status |= SE_INT_OP_DONE | SE_INT_ERR_STAT;
}
static inline void xor16(uint8_t *d, const uint8_t *s) {
for (int j = 0; j < 16; ++j) d[j] ^= s[j];
}
// SE_CRYPTO_LINEAR_CTR holds the counter as the driver wrote it, bytes in
// memory order; it counts as one big-endian 128-bit number.
static void ctr_add(uint32_t n) {
uint8_t *p = (uint8_t *)linear_ctr;
for (int j = 15; j >= 0 && n; --j) {
uint32_t v = p[j] + (n & 0xFF);
p[j] = (uint8_t)v;
n = (n >> 8) + (v >> 8);
}
}
// One AES operation over `blocks` 16-byte blocks, chained the way the SE
// datapath chains them. The configurations bdk's sec/se.c uses:
//
// ECB INPUT_MEMORY XOR_BYPASS out = AES(in)
// CBC enc INPUT_MEMORY XOR_TOP VCTRAM_AESOUT out = AES(in ^ v); v = out
// CBC dec INPUT_MEMORY XOR_BOTTOM VCTRAM_PREVMEM out = AES(in) ^ v; v = in
// OFB INPUT_AESOUT XOR_BOTTOM v = AES(v); out = v ^ in
// CTR INPUT_LNR_CTR XOR_BOTTOM out = AES(ctr) ^ in; ctr += n
//
// v, the vector RAM, starts from the slot's original or updated IV (IV_SEL).
// When the mode chains, the final v is left in the slot's UPDATED_IV: that is
// how bdk continues a chain into a trailing partial block, and how its CMAC
// feeds the last block after the others. With HASH enabled (CMAC) the last
// AES output goes to SE_HASH_RESULT.
static void run_aes_blocks(uint32_t slot, bool encrypt,
const uint8_t *in, uint8_t *out, size_t blocks,
uint32_t xor_pos, uint32_t input_sel,
uint32_t vctram_sel, uint32_t iv_sel,
bool ctr_mode, bool hash_mode) {
uint32_t ctr_step, bool hash_mode) {
uint8_t rk[176];
aes::key_expand(ks_table[slot].key, rk);
// Pick which IV to use for chaining. Hekate typically uses ORIGINAL_IV for
// CBC starts and switches to UPDATED_IV mid-CMAC; we honour that.
uint8_t chain[16];
if (iv_sel == IV_UPDATED) std::memcpy(chain, ks_table[slot].iv_upd, 16);
else std::memcpy(chain, ks_table[slot].iv_orig, 16);
uint8_t prev_in[16] = {0};
uint8_t hash_state[16] = {0}; // accumulator for HASH=1 (CMAC) — XOR top, encrypt
if (hash_mode) std::memcpy(hash_state, chain, 16);
uint8_t v[16];
std::memcpy(v, iv_sel == IV_UPDATED ? ks_table[slot].iv_upd
: ks_table[slot].iv_orig, 16);
uint8_t aes_out[16] = {0};
for (size_t i = 0; i < blocks; ++i) {
uint8_t in_block[16];
uint8_t out_block[16];
const uint8_t *mem = in + i * 16;
uint8_t a[16];
if (input_sel == INPUT_LNR_CTR) std::memcpy(a, linear_ctr, 16);
else if (input_sel == INPUT_AESOUT) std::memcpy(a, v, 16);
else std::memcpy(a, mem, 16);
if (input_sel == INPUT_LNR_CTR) {
// CTR mode input is the linear counter (big-endian 128-bit), per-block.
// Our linear_ctr[] is stored as 4 dwords little-endian; assemble.
uint8_t ctr_be[16];
for (int j = 0; j < 4; ++j) {
uint32_t w = linear_ctr[j];
ctr_be[j*4 + 0] = (w >> 0) & 0xFF;
ctr_be[j*4 + 1] = (w >> 8) & 0xFF;
ctr_be[j*4 + 2] = (w >> 16) & 0xFF;
ctr_be[j*4 + 3] = (w >> 24) & 0xFF;
}
std::memcpy(in_block, ctr_be, 16);
} else if (input_sel == INPUT_AESOUT) {
// Re-feeding previous AES output (used in some chained constructions).
std::memcpy(in_block, prev_in, 16);
} else {
std::memcpy(in_block, in + i*16, 16);
}
if (xor_pos == XOR_TOP) xor16(a, v);
if (encrypt) aes::encrypt_block(a, aes_out, rk);
else aes::decrypt_block(a, aes_out, rk);
// VCTRAM source: the value XORed at XOR_TOP / XOR_BOTTOM.
uint8_t vctram[16];
if (vctram_sel == VCTRAM_AESOUT) std::memcpy(vctram, prev_in, 16);
else if (vctram_sel == VCTRAM_PREVMEM) std::memcpy(vctram, (i==0)? chain : (in + (i-1)*16), 16);
else std::memcpy(vctram, chain, 16);
uint8_t *o = out + i * 16;
std::memcpy(o, aes_out, 16);
// After the core: CBC decrypt XORs the vector; OFB and CTR XOR the data.
if (xor_pos == XOR_BOTTOM) xor16(o, input_sel == INPUT_MEMORY ? v : mem);
if (xor_pos == XOR_TOP) {
for (int j = 0; j < 16; ++j) in_block[j] ^= vctram[j];
}
if (input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT)
std::memcpy(v, aes_out, 16);
else if (vctram_sel == VCTRAM_PREVMEM)
std::memcpy(v, mem, 16);
if (encrypt) aes::encrypt_block(in_block, out_block, rk);
else aes::decrypt_block(in_block, out_block, rk);
if (xor_pos == XOR_BOTTOM) {
// Output XOR with chain (CTR keystream XOR plaintext, etc.)
const uint8_t *xb = (input_sel == INPUT_LNR_CTR)
? (in + i*16) // CTR: XOR with plaintext from memory
: vctram;
for (int j = 0; j < 16; ++j) out_block[j] ^= xb[j];
}
if (out) std::memcpy(out + i*16, out_block, 16);
// Advance chain for next block.
if (xor_pos == XOR_BOTTOM && input_sel != INPUT_LNR_CTR) {
// CBC encrypt: chain = ciphertext = out_block
std::memcpy(chain, out_block, 16);
} else if (xor_pos == XOR_TOP) {
// CBC decrypt: chain = ciphertext (the input block we read)
std::memcpy(chain, in + i*16, 16);
}
std::memcpy(prev_in, out_block, 16);
if (ctr_mode) {
// Increment linear counter (big-endian 128-bit).
for (int j = 15; j >= 0; --j) {
uint8_t *p = (uint8_t*)linear_ctr;
p[j]++;
if (p[j]) break;
}
}
if (input_sel == INPUT_LNR_CTR) ctr_add(ctr_step);
}
if (hash_mode) {
// For HASH paths the final cipher block is exposed via SE_HASH_RESULT_REG.
std::memcpy(hash_result, prev_in, 16);
if (hash_mode) std::memcpy(hash_result, aes_out, 16);
bool chained = input_sel == INPUT_AESOUT || vctram_sel == VCTRAM_AESOUT ||
vctram_sel == VCTRAM_PREVMEM;
if (chained && blocks) std::memcpy(ks_table[slot].iv_upd, v, 16);
}
// SHA-256, one-shot or in parts (bdk _se_sha_hash_256). SHA_INIT_HASH starts
// from the standard initial state, SHA_CONTINUE from the state the previous
// part left in SE_HASH_RESULT - which is where the hardware keeps it, too.
// SE_SHA_MSG_LEFT says whether this is the last part: bdk passes one byte
// more than it feeds for any part but the last, so the engine pads the part
// only when LEFT equals the data it has, using the total from
// SE_SHA_MSG_LENGTH. HASH_RESULT holds the state as 8 dwords, most
// significant byte first; the driver byte-swaps them into the digest.
static void sha_op(EmuState *state) {
LLDesc in_ll{};
if (!read_ll(state->uc, reg_in_ll_addr, &in_ll) || !in_ll.size) {
reg_int_status |= SE_INT_OP_DONE;
return;
}
// Save updated IV (chain) for next call's IV_UPDATED.
std::memcpy(ks_table[slot].iv_upd, chain, 16);
std::vector<uint8_t> buf(in_ll.size);
if (uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size) != UC_ERR_OK) {
op_fail("SHA-256 input", in_ll.addr);
return;
}
auto reg64 = [](uint32_t off) {
return (uint64_t)spare_regs[off / 4] | ((uint64_t)spare_regs[off / 4 + 1] << 32);
};
uint64_t total_bits = reg64(SE_SHA_MSG_LENGTH_REG);
uint64_t left_bits = reg64(SE_SHA_MSG_LEFT_REG);
bool init = (spare_regs[SE_SHA_CONFIG_REG / 4] & 1) == SHA_INIT_HASH;
uint32_t H[8];
if (init) std::memcpy(H, sha256::H0, sizeof(H));
else std::memcpy(H, hash_result, sizeof(H));
bool last = left_bits <= (uint64_t)in_ll.size * 8;
if (last)
sha256::final(H, buf.data(), in_ll.size, total_bits);
else
sha256::blocks(H, buf.data(), in_ll.size / 64);
std::memcpy(hash_result, H, sizeof(H));
std::printf("[se] SHA-256 %s%s over %u bytes @0x%X -> %08X...\n",
init ? "" : "continued ", last ? "final" : "part",
in_ll.size, in_ll.addr, H[0]);
reg_int_status |= SE_INT_OP_DONE;
}
static void op_start(EmuState *state) {
@@ -423,37 +490,21 @@ static void op_start(EmuState *state) {
bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP);
bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP);
// ---- SHA-256 path ----
// ALG_SHA=3, MODE_SHA256=5, DST=DST_HASHREG. Driver flow: writes
// SE_SHA_MSG_LENGTH/LEFT, sets up IN_LL pointing at src/src_size, then
// OP_START. Output 32 bytes go into HASH_RESULT_REG as 8 big-endian dwords
// (driver byte_swap_32's each on read). We currently only model the
// oneshot case (SHA_INIT_HASH); save_process_header uses oneshot.
if (enc_alg == 3 /*ALG_SHA*/ && dst_kind == DST_HASHREG && enc_mode == 5 /*MODE_SHA256*/) {
LLDesc in_ll{};
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
if (!got_in || !in_ll.size) {
reg_int_status |= SE_INT_OP_DONE;
return;
}
std::vector<uint8_t> buf(in_ll.size, 0);
uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size);
uint8_t digest[32];
sha256::compute(buf.data(), in_ll.size, digest);
// Pack into HASH_RESULT_REG as 8 big-endian dwords (driver byteswaps).
for (int i = 0; i < 8; i++) {
hash_result[i] = ((uint32_t)digest[i*4 + 0] << 24) |
((uint32_t)digest[i*4 + 1] << 16) |
((uint32_t)digest[i*4 + 2] << 8) |
((uint32_t)digest[i*4 + 3]);
}
std::printf("[se] SHA-256 over %u bytes @0x%X -> %02X%02X%02X%02X...\n",
in_ll.size, in_ll.addr, digest[0], digest[1], digest[2], digest[3]);
if (enc_alg == ALG_SHA && dst_kind == DST_HASHREG && enc_mode == MODE_SHA256) {
sha_op(state);
return;
}
// RNG into the secure random key: the start of a context save. The key is
// fixed rather than random so runs stay reproducible.
if (enc_alg == ALG_RNG && dst_kind == DST_SRK) {
for (int i = 0; i < 16; ++i) srk[i] = (uint8_t)(0xA5 ^ (i * 0x1D));
std::memset(ctx_chain, 0, sizeof(ctx_chain));
reg_int_status |= SE_INT_OP_DONE;
return;
}
if (dst_kind == 4 /* DST_RSAREG */) {
if (dst_kind == DST_RSAREG) {
// RSA not implemented — leave output zero.
reg_int_status |= SE_INT_OP_DONE;
return;
@@ -470,46 +521,51 @@ static void op_start(EmuState *state) {
uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1;
uint32_t core_sel = (reg_crypto_config >> 8) & 0x1;
bool hash_en = (reg_crypto_config >> 0) & 0x1;
uint32_t ctr_cnt = (reg_crypto_config >> 11) & 0x1;
uint32_t ctr_step = (reg_crypto_config >> 11) & 0xFF;
uint32_t key_index = (reg_crypto_config >> 24) & 0xF;
bool encrypt = (core_sel == CORE_ENCRYPT);
uint32_t blocks = reg_block_count + 1;
// SE_CRYPTO_LAST_BLOCK is the index of the last block. Bounded by what one
// linked-list entry can describe, so a wild value cannot overflow the
// buffer size below.
uint32_t blocks = (reg_block_count % MAX_AES_BLOCKS) + 1;
uint32_t total_bytes = blocks * 16;
// Read input via IN_LL.
std::vector<uint8_t> in_buf, out_buf;
in_buf.resize(total_bytes, 0);
out_buf.resize(total_bytes, 0);
std::vector<uint8_t> in_buf(total_bytes, 0), out_buf(total_bytes, 0);
LLDesc in_ll{}, out_ll{};
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
bool got_out = read_ll(state->uc, reg_out_ll_addr, &out_ll);
(void)got_out;
if (got_in && in_ll.size && input_sel == INPUT_MEMORY) {
// Memory input is data for every mode: the block itself for ECB/CBC, what
// the keystream is XORed with for OFB/CTR.
if (got_in && in_ll.size) {
uint32_t copy = (in_ll.size < total_bytes) ? in_ll.size : total_bytes;
uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy);
if (uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy) != UC_ERR_OK) {
op_fail("AES input", in_ll.addr);
return;
}
}
run_aes_blocks(key_index, encrypt, in_buf.data(), out_buf.data(), blocks,
xor_pos, input_sel, vctram_sel, iv_sel,
(input_sel == INPUT_LNR_CTR) || ctr_cnt, hash_en);
xor_pos, input_sel, vctram_sel, iv_sel, ctr_step, hash_en);
if (dst_kind == DST_MEMORY) {
if (got_out && out_ll.size) {
uint32_t copy = (out_ll.size < total_bytes) ? out_ll.size : total_bytes;
uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy);
if (uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy) != UC_ERR_OK) {
op_fail("AES output", out_ll.addr);
return;
}
}
} else if (dst_kind == DST_KEYTABLE) {
// Unwrap-key path: store the (single-block) result in the destination slot.
// Unwrap-key path: the (single-block) result lands in the destination
// slot's selected word quad.
uint32_t dst_slot = (reg_keytable_dst >> 8) & 0xF;
uint32_t word_quad = reg_keytable_dst & 0x3;
uint8_t *target = (word_quad == 1)
? ks_table[dst_slot].key + 16
: ks_table[dst_slot].key + 0;
std::memcpy(target, out_buf.data(), 16);
Keyslot &k = ks_table[dst_slot];
uint8_t *target[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
std::memcpy(target[reg_keytable_dst & 0x3], out_buf.data(), 16);
}
// DST_HASHREG: hash_result is already populated by run_aes_blocks.
@@ -522,6 +578,40 @@ static void op_start(EmuState *state) {
got_in ? in_ll.addr : 0, got_out ? out_ll.addr : 0);
}
// SE_OP_CTX_SAVE, as bdk's se_aes_ctx_get_keys() drives it to read keyslots
// back: an RNG op seeds the secure random key (SRK); each save of an AES
// keytable quad writes that quad to memory encrypted under the SRK, CBC-
// chained from one save to the next; saving the SRK source deposits the key
// in PMC SECURE_SCRATCH4..7. The driver then loads the SRK into a slot and
// CBC-decrypts everything it saved in one pass with that slot's original IV,
// which it never sets - zero from reset - so the chain starts from zero.
static void ctx_save(EmuState *state) {
uint32_t cfg = spare_regs[SE_CONTEXT_SAVE_CONFIG_REG / 4];
uint32_t src = cfg >> 29;
if ((reg_config >> 2 & 0x7) == DST_MEMORY && src == CTX_SRC_AES_KEYTABLE) {
const Keyslot &k = ks_table[(cfg >> 8) & 0xF];
const uint8_t *quad[4] = {k.key, k.key + 16, k.iv_orig, k.iv_upd};
uint8_t blk[16], rk[176];
std::memcpy(blk, quad[cfg & 0x3], 16);
xor16(blk, ctx_chain);
aes::key_expand(srk, rk);
aes::encrypt_block(blk, ctx_chain, rk);
LLDesc out_ll{};
if (read_ll(state->uc, reg_out_ll_addr, &out_ll) && out_ll.size >= 16 &&
uc_mem_write(state->uc, out_ll.addr, ctx_chain, 16) != UC_ERR_OK) {
op_fail("context save output", out_ll.addr);
return;
}
} else if (src == CTX_SRC_SRK && reg_config != 0) {
for (int i = 0; i < 4; ++i) {
uint32_t w;
std::memcpy(&w, srk + i * 4, 4);
pmc_secure_scratch_write(4 + i, w);
}
}
reg_int_status |= SE_INT_OP_DONE;
}
// Keytable address layout: bits 4..7 = slot, bits 2..3 = quad, bits 0..1 = pkt
static void keytable_write(uint32_t addr, uint32_t val) {
uint32_t slot = (addr >> 4) & 0xF;
@@ -541,14 +631,19 @@ static void keytable_write(uint32_t addr, uint32_t val) {
// Lockpick's _derive_bis_keys may produce wrong values when our SE engine
// doesn't faithfully model some part of the chain; the override is a
// pragmatic shortcut that lets the BIS XTS layer succeed regardless.
// Two writes are never BIS keys and are left alone: clearing a slot (all
// zeros), and loading the context-save SRK (bdk puts it in slot 3).
if (quad == 0 && pkt == 3 && slot < 6) {
if (bis_override_present[slot]) {
static const uint8_t zero[16] = {0};
bool clear = std::memcmp(ks_table[slot].key, zero, 16) == 0;
bool is_srk = std::memcmp(ks_table[slot].key, srk, 16) == 0;
if (bis_override_present[slot] && !clear && !is_srk) {
std::memcpy(ks_table[slot].key, bis_override_keys[slot], 16);
std::printf("[se] slot %u BIS key overridden from prod.keys:", slot);
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
std::printf("\n");
} else {
std::printf("[se] slot %u key loaded (derived):", slot);
} else if (!clear) {
std::printf("[se] slot %u key loaded:", slot);
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
std::printf("\n");
}
@@ -574,8 +669,6 @@ static uint32_t keytable_read(uint32_t addr) {
} // namespace
#include <vector>
uint32_t se_engine_read(EmuState *state, uint64_t addr) {
uint32_t off = (uint32_t)(addr - SE_BASE);
if (off >= SE_HASH_RESULT_REG && off < SE_HASH_RESULT_REG + 16*4) {
@@ -616,10 +709,12 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
switch (off) {
case SE_OPERATION_REG:
reg_op = val;
// SE_OP_START runs the configured AES op; other op codes (RESTART_*,
// CTX_SAVE, ABORT) just need OP_DONE so the driver's _se_wait() exits.
if ((val & 0x7) == 1 /*SE_OP_START*/) {
// SE_OP_START runs the configured op and CTX_SAVE saves context;
// the others (RESTART_*) just need OP_DONE so _se_op_wait() exits.
if ((val & 0x7) == SE_OP_START) {
op_start(state);
} else if ((val & 0x7) == SE_OP_CTX_SAVE) {
ctx_save(state);
} else if ((val & 0x7) != 0 /*not ABORT*/) {
reg_int_status |= SE_INT_OP_DONE;
}
@@ -647,9 +742,27 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
(void)state;
}
// Keys a prod.keys file pre-loaded, which a soft reboot puts back.
static Keyslot ks_preload[16];
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]) {
if (slot >= 16) return;
std::memcpy(ks_table[slot].key, key, 16);
std::memcpy(ks_preload[slot].key, key, 16);
}
void se_engine_reset() {
std::memcpy(ks_table, ks_preload, sizeof(ks_table));
reg_config = reg_crypto_config = 0;
reg_in_ll_addr = reg_out_ll_addr = 0;
reg_block_count = reg_keytable_addr = reg_keytable_dst = 0;
reg_op = reg_int_status = reg_int_enable = 0;
reg_err_status = reg_rng_config = 0;
std::memset(linear_ctr, 0, sizeof(linear_ctr));
std::memset(hash_result, 0, sizeof(hash_result));
std::memset(spare_regs, 0, sizeof(spare_regs));
std::memset(srk, 0, sizeof(srk));
std::memset(ctx_chain, 0, sizeof(ctx_chain));
}
// ---- prod.keys parser -------------------------------------------------------
+12 -7
View File
@@ -10,17 +10,18 @@ struct EmuState;
// operations against an emulated 16-slot keytable.
//
// Currently implemented:
// * AES-128 ECB encrypt/decrypt (single + multi-block, DMA via LL descriptors)
// * AES-128 CBC encrypt/decrypt
// * AES-128 CTR mode
// * AES-128 ECB, CBC, OFB and CTR, single and multi-block, with the IV
// chained through UPDATED_IV the way bdk's partial-block path expects
// * AES-CMAC (HASH_ENABLE into SE_HASH_RESULT)
// * AES "unwrap" (decrypt and store result in destination keyslot)
// * SHA-256, one-shot and in parts (SHA_INIT_HASH / SHA_CONTINUE)
// * Context save of AES keyslots under a secure random key, as bdk's
// se_aes_ctx_get_keys() reads keys back
// * Keyslot programming (CRYPTO_KEYTABLE_ADDR/DATA)
// * Pre-population of keyslots from a Switch prod.keys file
//
// Not implemented (returns zero / no-op):
// * AES-CMAC (HASH+VCTRAM_AESOUT path)
// * SHA / RNG / RSA
// Each unimplemented op still completes (sets OP_DONE) so the boot doesn't hang.
// Not implemented: RNG output, RSA, AES-192/256 key sizes. Those operations
// still complete (set OP_DONE) so a payload does not hang on them.
uint32_t se_engine_read (EmuState *state, uint64_t addr);
void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
@@ -31,6 +32,10 @@ void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
// AES, so this is enough.
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]);
// Soft reboot: registers back to reset, keyslots back to what prod.keys
// pre-loaded.
void se_engine_reset();
// Parse a switch-style "prod.keys" file (lines of `name = hex_value`) and
// pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12,
// KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation