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

@ -0,0 +1,67 @@
/*
* cert_extract.h -- Device certificate extraction via lockdownd.
*
* Pulls the three certificate blobs that the activation record needs
* directly from a connected device's lockdownd service:
*
* - DeviceCertificate
* - AccountTokenCertificate
* - UniqueDeviceCertificate
*
* Each is returned as a raw byte blob (DER-encoded X.509 in practice).
* The caller owns the buffer and must release it with cert_blob_free().
*/
#ifndef CERT_EXTRACT_H
#define CERT_EXTRACT_H
#include <stddef.h>
#include <libimobiledevice/lockdown.h>
typedef struct {
unsigned char *data;
size_t len;
} cert_blob_t;
/*
* cert_blob_free -- Release a cert_blob_t's backing buffer.
*
* Safe to call on a NULL pointer or a zeroed blob. After the call,
* blob->data is NULL and blob->len is zero.
*/
void cert_blob_free(cert_blob_t *blob);
/*
* cert_extract_device_certificate -- Read the DeviceCertificate.
*
* Queries the key "DeviceCertificate" in domain
* "com.apple.mobile.lockdown". On success returns 0 and populates *out;
* on any failure returns -1 and leaves *out zeroed.
*/
int cert_extract_device_certificate(lockdownd_client_t client,
cert_blob_t *out);
/*
* cert_extract_account_token_certificate -- Read the AccountTokenCertificate.
*
* Tries, in order:
* 1. key "AccountTokenCertificate" (NULL domain)
* 2. key "ActivationStateDeadline" (NULL domain)
* 3. first element of "CertificateChain" array (NULL domain)
*
* Returns 0 on success and populates *out; -1 on failure.
*/
int cert_extract_account_token_certificate(lockdownd_client_t client,
cert_blob_t *out);
/*
* cert_extract_unique_device_certificate -- Read the UniqueDeviceCertificate.
*
* Queries the key "UniqueDeviceCertificate" in domain
* "com.apple.mobile.activation". Returns 0 on success, -1 on failure.
*/
int cert_extract_unique_device_certificate(lockdownd_client_t client,
cert_blob_t *out);
#endif /* CERT_EXTRACT_H */

View file

@ -12,6 +12,7 @@
#include <stdint.h>
#include <plist/plist.h>
#include <libimobiledevice/lockdown.h>
#include "device/device.h"
/*
@ -19,6 +20,9 @@
* Returns a new plist dict containing all required activation fields.
* Caller must free with record_free() or plist_free().
* Returns NULL on error.
*
* Equivalent to record_build_with_client(dev, NULL): cert fields are
* left as empty-blob placeholders.
*/
plist_t record_build(const device_info_t *dev);
@ -27,9 +31,27 @@ plist_t record_build(const device_info_t *dev);
* Uses the FActivation/drmHandshake variant with additional fields
* required for A12 and newer chipsets (SEP-aware activation).
* Returns a new plist dict, or NULL on error. Caller must free.
*
* Equivalent to record_build_a12_with_client(dev, NULL).
*/
plist_t record_build_a12(const device_info_t *dev);
/*
* record_build_with_client -- As record_build, but when `client` is
* non-NULL, pull DeviceCertificate / AccountTokenCertificate /
* UniqueDeviceCertificate from lockdownd and embed them in the record.
* Falls back to empty-blob placeholders if extraction fails.
*/
plist_t record_build_with_client(const device_info_t *dev,
lockdownd_client_t client);
/*
* record_build_a12_with_client -- As record_build_a12, but with live
* cert extraction when `client` is non-NULL (see above).
*/
plist_t record_build_a12_with_client(const device_info_t *dev,
lockdownd_client_t client);
/*
* record_to_xml -- Serialize an activation record to XML string.
* On success, *len is set to the byte length (excluding NUL).

View file

@ -0,0 +1,49 @@
/*
* signer.h -- ECDSA P-256 signing and verification helpers.
*
* Thin wrapper over OpenSSL 3.x EVP API. All signatures are ECDSA over
* SHA-256, DER-encoded (not raw r||s). Keys are read from and written
* to PEM files on disk.
*/
#ifndef SIGNER_H
#define SIGNER_H
#include <stddef.h>
/*
* signer_ecdsa_sign -- Sign a byte buffer with an EC private key on disk.
*
* Reads a P-256 private key from `pem_path`, signs `data[len]` (SHA-256
* first), and returns the DER-encoded signature via *sig / *sig_len.
*
* The output buffer is malloc'd and the caller must free() it.
* Returns 0 on success, -1 on any failure.
*/
int signer_ecdsa_sign(const char *pem_path,
const unsigned char *data, size_t len,
unsigned char **sig, size_t *sig_len);
/*
* signer_ecdsa_verify -- Verify a DER-encoded ECDSA signature.
*
* Returns 1 if `sig[sig_len]` is a valid signature over SHA-256 of
* `data[len]` under the public key in `pem_path`. Returns 0 if the
* signature is well-formed but invalid, and -1 on any system error
* (bad file, malformed PEM, OOM, etc.).
*/
int signer_ecdsa_verify(const char *pem_path,
const unsigned char *data, size_t len,
const unsigned char *sig, size_t sig_len);
/*
* signer_generate_test_keypair -- Write a fresh P-256 keypair to disk.
*
* Intended for tests. Produces two files: an unencrypted PKCS#8 private
* PEM and a SubjectPublicKeyInfo PEM. Overwrites existing files.
* Returns 0 on success, -1 on failure.
*/
int signer_generate_test_keypair(const char *priv_pem_path,
const char *pub_pem_path);
#endif /* SIGNER_H */

View file

@ -0,0 +1,24 @@
/*
* path_a_ramdisk_internal.h -- Helpers shared between the ramdisk
* orchestrator and the SSH poll helper (path_a_ramdisk_poll.c).
*
* Internal to the bypass module; not part of the public API.
*/
#ifndef BYPASS_PATH_A_RAMDISK_INTERNAL_H
#define BYPASS_PATH_A_RAMDISK_INTERNAL_H
/*
* poll_ssh_ready -- wait until a TCP connection to 127.0.0.1:<port>
* succeeds, or until timeout_sec seconds elapse.
*
* Returns 0 when SSH is reachable, -1 on timeout or fatal socket error.
*
* The environment variable TR4MPASS_TEST_SSH_READY acts as a test hook:
* "1" -- return 0 immediately
* "0" -- return -1 immediately
* any other value -- perform the real socket poll.
*/
int path_a_ramdisk_poll_ssh(int port, int timeout_sec);
#endif /* BYPASS_PATH_A_RAMDISK_INTERNAL_H */

View file

@ -0,0 +1,66 @@
/*
* path_a_ssh_internal.h -- SSH helper wrappers shared between the
* Path A jailbreak and mobileactivationd-replacement flows.
*
* Not a public API; internal to the bypass module. The wrappers hide
* the raw libssh2 session/channel lifecycle so that path_a_ssh.c only
* deals in high-level "open / exec / scp / close" operations.
*/
#ifndef BYPASS_PATH_A_SSH_INTERNAL_H
#define BYPASS_PATH_A_SSH_INTERNAL_H
#include <stddef.h>
#include <sys/types.h>
/* Opaque session handle owned by path_a_ssh_helpers.c. */
typedef struct ssh_sess ssh_sess_t;
/*
* ssh_open -- Establish a libssh2 session with password authentication.
*
* host/user/password must be non-NULL. On success *sess_out is set to a
* heap-allocated handle that the caller frees with ssh_close(). Returns
* 0 on success, -1 on any failure (socket, handshake, auth).
*/
int ssh_open(ssh_sess_t **sess_out, const char *host, int port,
const char *user, const char *password);
/*
* ssh_exec -- Run a single command over SSH and capture its stdout.
*
* If exit_code_out is non-NULL the remote exit status is written there.
* If stdout_buf/stdout_cap are non-zero, up to (stdout_cap-1) bytes of
* stdout are copied; the buffer is always NUL-terminated on success.
*
* Returns 0 on a successful RPC round-trip (regardless of remote exit
* code) or -1 if the channel / transport itself failed.
*/
int ssh_exec(ssh_sess_t *sess, const char *cmd, int *exit_code_out,
char *stdout_buf, size_t stdout_cap);
/*
* ssh_scp_upload -- Push a local file to remote_path via SCP.
*
* The destination inode is created with the given unix mode. Returns 0
* on success, -1 on any error (read failure, SCP channel rejection,
* truncated write).
*/
int ssh_scp_upload(ssh_sess_t *sess, const char *local_path,
const char *remote_path, mode_t mode);
/*
* ssh_close -- Disconnect and free a session created by ssh_open. Safe
* to call with a NULL handle.
*/
void ssh_close(ssh_sess_t *sess);
/*
* ssh_global_init / ssh_global_exit -- Reference-counted libssh2_init
* wrappers. Helpers call them from ssh_open/ssh_close so tests do not
* need to coordinate global init. Not for direct use.
*/
int ssh_global_init(void);
void ssh_global_exit(void);
#endif /* BYPASS_PATH_A_SSH_INTERNAL_H */

36
include/cli/cli_flags.h Normal file
View file

@ -0,0 +1,36 @@
/*
* cli_flags.h -- Bypass-pipeline CLI flag parsing for tr4mpass.
*
* main.c owns the existing short flags (--verbose, --dry-run,
* --detect-only, --force-path-a/b, --cpid, --ecid) and passes argv
* here for a second parse that translates --ramdisk, --ssh-host etc
* into setenv() calls. The env vars are consumed later by Phase 2B
* (ramdisk staging) and Phase 2C (SSH jailbreak).
*
* The helper here is intentionally additive: unknown flags are
* ignored (getopt_long returns '?' when the short option list is
* empty) and the existing flags in main.c remain untouched.
*/
#ifndef TR4MPASS_CLI_FLAGS_H
#define TR4MPASS_CLI_FLAGS_H
/*
* Parse argv for bypass-pipeline env overrides and apply them via
* setenv(..., 1). This is called after main.c's own getopt_long
* loop so the short flags already consumed by main.c remain visible
* to getopt via argv -- we simply skip anything we do not recognize.
*
* Returns 0 on success, -1 on argument errors (e.g. flag missing
* value). Help output for the new flags is produced by
* cli_flags_print_help() so main.c --help can delegate.
*/
int cli_parse_bypass_flags(int argc, char *argv[]);
/*
* Print the bypass-pipeline flag block used by --help. Kept separate
* so main.c keeps responsibility for the overall usage banner.
*/
void cli_flags_print_help(void);
#endif /* TR4MPASS_CLI_FLAGS_H */

63
include/util/env_config.h Normal file
View file

@ -0,0 +1,63 @@
/*
* env_config.h -- Thin wrapper around getenv that logs a warning when
* required tr4mpass environment variables are missing.
*
* Centralizes lookup, defaulting, and summary printing for every
* TR4MPASS_* variable used by the bypass pipeline. Phase 2B and 2C
* read configuration through these helpers; Phase 2D (this module)
* supplies CLI-flag shims in src/cli/cli_flags.c that set the env
* vars before the bypass code reads them.
*/
#ifndef TR4MPASS_ENV_CONFIG_H
#define TR4MPASS_ENV_CONFIG_H
#include <stddef.h>
/*
* Recognized TR4MPASS_* environment variables. Update the table in
* env_config.c when adding new names so --verbose keeps printing the
* complete picture.
*/
#define TR4MPASS_ENV_RAMDISK_PATH "TR4MPASS_RAMDISK_PATH"
#define TR4MPASS_ENV_IBSS_PATH "TR4MPASS_IBSS_PATH"
#define TR4MPASS_ENV_IBEC_PATH "TR4MPASS_IBEC_PATH"
#define TR4MPASS_ENV_DEVICETREE_PATH "TR4MPASS_DEVICETREE_PATH"
#define TR4MPASS_ENV_TRUSTCACHE_PATH "TR4MPASS_TRUSTCACHE_PATH"
#define TR4MPASS_ENV_PATCHED_MAD "TR4MPASS_PATCHED_MAD"
#define TR4MPASS_ENV_SSH_HOST "TR4MPASS_SSH_HOST"
#define TR4MPASS_ENV_SSH_PORT "TR4MPASS_SSH_PORT"
#define TR4MPASS_ENV_SSH_USER "TR4MPASS_SSH_USER"
#define TR4MPASS_ENV_SSH_PASSWORD "TR4MPASS_SSH_PASSWORD"
#define TR4MPASS_ENV_SIGNING_KEY "TR4MPASS_SIGNING_KEY"
#define TR4MPASS_ENV_RAMDISK_TIMEOUT "TR4MPASS_RAMDISK_TIMEOUT"
/*
* Return the value of `name` from the environment. When the variable
* is not set, `default_value` is returned (which may itself be NULL).
* An empty string ("") is returned as-is and is *not* replaced with
* the default -- callers that treat empty as unset must check.
*/
const char *env_get(const char *name, const char *default_value);
/*
* Parse `name` as a base-10 integer. Returns `default_value` if the
* variable is unset, empty, or cannot be fully consumed as a number.
*/
int env_get_int(const char *name, int default_value);
/*
* Verify every name in `names[0..count)` is set and non-empty.
* Returns 0 when all are present. Returns -1 and writes a warning
* listing every missing name when at least one is absent.
*/
int env_require_all(const char *const *names, size_t count);
/*
* Dump the current value of every TR4MPASS_* variable to stdout.
* Secrets (password, signing key) are abbreviated; paths are printed
* verbatim; unset variables print "<unset>".
*/
void env_print_tr4mpass_summary(void);
#endif /* TR4MPASS_ENV_CONFIG_H */