specter-mem 1.0.5

ARM64 memory manipulation framework for iOS/macOS — inline hooking, stealth code patching, hardware breakpoints, and shellcode loading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! # Hardware Breakpoint Hooking
//!
//! This module implements hooking using ARM64 hardware breakpoints (watchpoints/breakpoints).
//! This method is "stealthier" than inline patches as it doesn't modify the executable code,
//! but it is limited by the number of hardware debug registers (max 6).
//!
//! It uses Mach exception handling to catch the breakpoint exception and redirect execution.

use crate::memory::ffi::mach_exc::{
    task_get_exception_ports, task_set_exception_ports, task_set_state,
};
#[cfg(debug_assertions)]
use crate::utils::logger;
use libc::{pthread_create, sysctlbyname};
use mach2::kern_return::KERN_SUCCESS;
use mach2::mach_init::mach_thread_self;
use mach2::mach_port::{mach_port_allocate, mach_port_deallocate, mach_port_insert_right};
use mach2::message::{mach_msg, mach_msg_header_t, mach_msg_type_name_t};
use mach2::port::{MACH_PORT_NULL, MACH_PORT_RIGHT_RECEIVE, mach_port_t};
use mach2::task::task_threads;
use mach2::thread_act::thread_set_state;
use mach2::traps::mach_task_self;
use mach2::vm::mach_vm_deallocate;

use once_cell::sync::Lazy;
use parking_lot::Mutex;
use std::ffi::c_void;
use std::ptr;
use std::sync::atomic::{AtomicBool, Ordering};
use thiserror::Error;

use crate::memory::ffi::mach_exc::{
    ExceptionBehaviorT, ExceptionMaskT, KernReturnT, ThreadStateFlavor,
};

type ExceptionTypeT = i32;

const KERN_FAILURE: KernReturnT = 5;
const MACH_MSG_TYPE_MAKE_SEND: mach_msg_type_name_t = 20;
const EXC_MASK_BREAKPOINT: ExceptionMaskT = 1 << 6;
const EXCEPTION_STATE: ExceptionBehaviorT = 2;
const MACH_EXCEPTION_CODES: ExceptionBehaviorT = 0x80000000_u32 as i32;
const ARM_THREAD_STATE64: ThreadStateFlavor = 6;
const ARM_DEBUG_STATE64: ThreadStateFlavor = 15;
const ARM_DEBUG_STATE64_COUNT: u32 = 130;
const ARM_THREAD_STATE64_COUNT: u32 = 68;
const MAX_HOOKS: usize = 16;
const BCR_ENABLE: u64 = 0x1E5;
const MACH_RCV_MSG: i32 = 0x00000002;
const MACH_SEND_MSG: i32 = 0x00000001;
const MACH_MSG_TIMEOUT_NONE: u32 = 0;

#[repr(C)]
struct NdrRecord {
    mig_vers: u8,
    if_vers: u8,
    reserved1: u8,
    mig_encoding: u8,
    int_rep: u8,
    char_rep: u8,
    float_rep: u8,
    reserved2: u8,
}

#[repr(C)]
#[derive(Clone, Copy)]
struct ArmThreadState64 {
    x: [u64; 29],
    fp: u64,
    lr: u64,
    sp: u64,
    pc: u64,
    cpsr: u32,
    flags: u32,
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
struct ArmDebugState64 {
    bvr: [u64; 16],
    bcr: [u64; 16],
    wvr: [u64; 16],
    wcr: [u64; 16],
    mdscr_el1: u64,
}

#[repr(C)]
struct ExcRaiseStateRequest {
    head: mach_msg_header_t,
    ndr: NdrRecord,
    exception: ExceptionTypeT,
    code_cnt: u32,
    code: [i64; 2],
    flavor: i32,
    old_state_cnt: u32,
    old_state: [u32; 614],
}

#[repr(C)]
struct ExcRaiseStateReply {
    head: mach_msg_header_t,
    ndr: NdrRecord,
    ret_code: KernReturnT,
    flavor: i32,
    new_state_cnt: u32,
    new_state: [u32; 614],
}

#[derive(Error, Debug)]
/// Errors that can occur during breakpoint operations
pub enum BrkHookError {
    /// The maximum number of hooks has been reached
    #[error("Too many hooks (max {MAX_HOOKS})")]
    TooManyHooks,
    /// A hook already exists at the specified address
    #[error("Hook already exists at {0:#x}")]
    AlreadyExists(usize),
    /// The hardware limit for breakpoints has been exceeded
    #[error("Exceeds hardware breakpoints: {0}")]
    ExceedsHwBreakpoints(i32),
    /// Failed to set the thread state (debug registers)
    #[error("Failed to set debug state")]
    SetStateFailed,
    /// The specified hook was not found
    #[error("Hook not found at {0:#x}")]
    NotFound(usize),
    /// Failed to initialize the exception handler
    #[error("Initialization failed")]
    InitFailed,
}

struct HookEntry {
    old: usize,
    new: usize,
}

struct HookManager {
    server_port: mach_port_t,
    orig_handler_port: mach_port_t,
    hooks: [Option<HookEntry>; MAX_HOOKS],
    active_count: usize,
    hw_breakpoints: i32,
    initialized: bool,
}

impl HookManager {
    /// Creates a new empty hook manager
    const fn new() -> Self {
        const NONE: Option<HookEntry> = None;
        Self {
            server_port: MACH_PORT_NULL,
            orig_handler_port: MACH_PORT_NULL,
            hooks: [NONE; MAX_HOOKS],
            active_count: 0,
            hw_breakpoints: 6, // hardware limitiation is 6, we can't increase this!
            initialized: false,
        }
    }

    /// Finds a replacement address for a given target PC
    fn find_hook(&self, pc: usize) -> Option<usize> {
        self.hooks
            .iter()
            .flatten()
            .find_map(|h| (h.old == pc).then_some(h.new))
    }

    /// Registers a new hook in the manager
    fn add_hook(&mut self, old: usize, new: usize) -> Result<usize, BrkHookError> {
        if self.hooks.iter().flatten().any(|h| h.old == old) {
            return Err(BrkHookError::AlreadyExists(old));
        }
        for (i, slot) in self.hooks.iter_mut().enumerate() {
            if slot.is_none() {
                *slot = Some(HookEntry { old, new });
                self.active_count += 1;
                return Ok(i);
            }
        }
        Err(BrkHookError::TooManyHooks)
    }

    /// Removes a hook from the manager
    fn remove_hook(&mut self, old: usize) -> Result<(), BrkHookError> {
        for slot in self.hooks.iter_mut() {
            if let Some(hook) = slot
                && hook.old == old
            {
                *slot = None;
                self.active_count -= 1;
                return Ok(());
            }
        }
        Err(BrkHookError::NotFound(old))
    }
}

static MANAGER: Lazy<Mutex<HookManager>> = Lazy::new(|| Mutex::new(HookManager::new()));
static HANDLER_RUNNING: AtomicBool = AtomicBool::new(false);

/// Thread that handles Mach exceptions for breakpoints
extern "C" fn exception_handler_thread(_: *mut c_void) -> *mut c_void {
    HANDLER_RUNNING.store(true, Ordering::SeqCst);

    let server_port = MANAGER.lock().server_port;
    #[repr(C)]
    struct ExcMessage {
        head: mach_msg_header_t,
        body: [u8; 8192],
    }

    loop {
        let mut request: ExcMessage = unsafe { std::mem::zeroed() };
        let mut reply: ExcMessage = unsafe { std::mem::zeroed() };

        let kr = unsafe {
            mach_msg(
                &mut request.head,
                MACH_RCV_MSG,
                0,
                std::mem::size_of::<ExcMessage>() as u32,
                server_port,
                MACH_MSG_TIMEOUT_NONE,
                MACH_PORT_NULL,
            )
        };

        if kr != KERN_SUCCESS {
            continue;
        }

        if request.head.msgh_id == 2406 {
            let req_ptr = &request as *const _ as *const ExcRaiseStateRequest;
            let req = unsafe { &*req_ptr };
            let old_state_ptr = req.old_state.as_ptr() as *const ArmThreadState64;
            let old_state = unsafe { &*old_state_ptr };
            let pc = old_state.pc as usize;

            let replacement = { MANAGER.lock().find_hook(pc) };

            let reply_ptr = &mut reply as *mut _ as *mut ExcRaiseStateReply;
            let rep = unsafe { &mut *reply_ptr };

            rep.head.msgh_bits =
                (request.head.msgh_bits & 0xFF) | ((request.head.msgh_bits >> 8) & 0xFF) << 8;
            rep.head.msgh_remote_port = request.head.msgh_remote_port;
            rep.head.msgh_local_port = MACH_PORT_NULL;
            rep.head.msgh_id = request.head.msgh_id + 100;

            if let Some(new_pc) = replacement {
                let new_state_ptr = rep.new_state.as_mut_ptr() as *mut ArmThreadState64;
                unsafe {
                    ptr::copy_nonoverlapping(old_state, new_state_ptr, 1);
                    (*new_state_ptr).pc = new_pc as u64;
                }
                rep.new_state_cnt = ARM_THREAD_STATE64_COUNT;
                rep.flavor = ARM_THREAD_STATE64;
                rep.ret_code = KERN_SUCCESS;
                rep.ndr = NdrRecord {
                    mig_vers: 0,
                    if_vers: 0,
                    reserved1: 0,
                    mig_encoding: 0,
                    int_rep: 1,
                    char_rep: 0,
                    float_rep: 0,
                    reserved2: 0,
                };
                rep.head.msgh_size = 24 + 8 + 4 + 4 + 4 + (ARM_THREAD_STATE64_COUNT * 4);
            } else {
                rep.ret_code = KERN_FAILURE;
                rep.new_state_cnt = 0;
                rep.ndr = NdrRecord {
                    mig_vers: 0,
                    if_vers: 0,
                    reserved1: 0,
                    mig_encoding: 0,
                    int_rep: 1,
                    char_rep: 0,
                    float_rep: 0,
                    reserved2: 0,
                };
                rep.head.msgh_size = 44;
            }

            unsafe {
                mach_msg(
                    &mut reply.head,
                    MACH_SEND_MSG,
                    rep.head.msgh_size,
                    0,
                    MACH_PORT_NULL,
                    MACH_MSG_TIMEOUT_NONE,
                    MACH_PORT_NULL,
                );
            }
        }
    }
}

/// Initializes the global exception handler
unsafe fn init_exception_handler() -> Result<(), BrkHookError> {
    unsafe {
        let mut manager = MANAGER.lock();
        if manager.initialized {
            return Ok(());
        }

        let task = mach_task_self();
        let mut bp_count: i32 = 6;
        let mut size = std::mem::size_of::<i32>();
        let sysctl_name = b"hw.optional.breakpoint\0";
        sysctlbyname(
            sysctl_name.as_ptr() as *const i8,
            &mut bp_count as *mut _ as *mut c_void,
            &mut size,
            ptr::null_mut(),
            0,
        );
        manager.hw_breakpoints = bp_count;

        let mut masks = [0u32; 32];
        let mut mask_cnt: u32 = 32;
        let mut old_handlers = [MACH_PORT_NULL; 32];
        let mut old_behaviors = [0i32; 32];
        let mut old_flavors = [0i32; 32];

        if task_get_exception_ports(
            task,
            EXC_MASK_BREAKPOINT,
            masks.as_mut_ptr(),
            &mut mask_cnt,
            old_handlers.as_mut_ptr(),
            old_behaviors.as_mut_ptr(),
            old_flavors.as_mut_ptr(),
        ) == KERN_SUCCESS
            && mask_cnt > 0
        {
            manager.orig_handler_port = old_handlers[0];
        }

        let mut server_port: mach_port_t = MACH_PORT_NULL;
        if mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &mut server_port) != KERN_SUCCESS {
            return Err(BrkHookError::InitFailed);
        }

        if mach_port_insert_right(task, server_port, server_port, MACH_MSG_TYPE_MAKE_SEND)
            != KERN_SUCCESS
        {
            return Err(BrkHookError::InitFailed);
        }

        if task_set_exception_ports(
            task,
            EXC_MASK_BREAKPOINT,
            server_port,
            EXCEPTION_STATE | MACH_EXCEPTION_CODES,
            ARM_THREAD_STATE64,
        ) != KERN_SUCCESS
        {
            return Err(BrkHookError::InitFailed);
        }

        manager.server_port = server_port;
        manager.initialized = true;

        if !HANDLER_RUNNING.load(Ordering::SeqCst) {
            let mut thread_handle: usize = 0;
            pthread_create(
                &mut thread_handle,
                ptr::null(),
                exception_handler_thread,
                ptr::null_mut(),
            );
        }

        #[cfg(debug_assertions)]
        logger::info(&format!(
            "Breakpoint hooking initialized ({} HW breakpoints)",
            bp_count
        ));
        Ok(())
    }
}

/// Applies debug state (breakpoints) to all threads
unsafe fn apply_debug_state(manager: &HookManager) -> Result<(), BrkHookError> {
    unsafe {
        let task = mach_task_self();
        let mut state = ArmDebugState64::default();

        for (bp_idx, hook) in manager.hooks.iter().flatten().enumerate() {
            if bp_idx >= manager.hw_breakpoints as usize {
                break;
            }
            state.bvr[bp_idx] = hook.old as u64;
            state.bcr[bp_idx] = BCR_ENABLE;
        }

        if task_set_state(
            task,
            ARM_DEBUG_STATE64,
            &state as *const _ as *const c_void,
            ARM_DEBUG_STATE64_COUNT,
        ) != KERN_SUCCESS
        {
            return Err(BrkHookError::SetStateFailed);
        }

        let mut threads: *mut mach_port_t = ptr::null_mut();
        let mut thread_count: u32 = 0;
        if task_threads(task, &mut threads, &mut thread_count) == KERN_SUCCESS {
            for i in 0..thread_count as isize {
                let thread = *threads.offset(i);
                thread_set_state(
                    thread,
                    ARM_DEBUG_STATE64,
                    &state as *const _ as *mut u32,
                    ARM_DEBUG_STATE64_COUNT,
                );
                mach_port_deallocate(task, thread);
            }
            mach_vm_deallocate(
                task,
                threads as u64,
                (thread_count as u64) * std::mem::size_of::<mach_port_t>() as u64,
            );
        }

        Ok(())
    }
}

/// Installs a hardware breakpoint hook at a relative virtual address (RVA)
///
/// # Arguments
/// * `rva` - The relative virtual address to hook
/// * `replacement` - The address of the replacement function
///
/// # Returns
/// * `Result<Breakpoint, BrkHookError>` - The installed breakpoint or an error
pub unsafe fn install(rva: usize, replacement: usize) -> Result<Breakpoint, BrkHookError> {
    unsafe {
        let image_name = crate::config::get_target_image_name().ok_or(BrkHookError::InitFailed)?;
        let base = crate::memory::image::get_image_base(&image_name)
            .map_err(|_| BrkHookError::InitFailed)?;
        install_at_address(base + rva, replacement)
    }
}

/// Represents an installed hardware breakpoint
pub struct Breakpoint {
    /// The address being watched
    target: usize,
}

impl Breakpoint {
    /// Removes the breakpoint
    ///
    /// # Returns
    /// * `Result<(), BrkHookError>` - Result indicating success or failure
    pub fn remove(self) -> Result<(), BrkHookError> {
        unsafe { remove_at_address(self.target) }
    }

    /// Returns the target address of the breakpoint
    #[inline]
    pub fn target(&self) -> usize {
        self.target
    }

    /// Calls the original function by temporarily disabling the breakpoint
    ///
    /// # Type Parameters
    /// * `T` - The function pointer type for the original function
    /// * `F` - The callback closure type
    /// * `R` - The return type
    ///
    /// # Arguments
    /// * `callback` - A closure that takes the original function pointer and returns a result
    ///
    /// # Returns
    /// * `R` - The result of the callback
    #[inline]
    pub unsafe fn call_original<T, F, R>(&self, callback: F) -> R
    where
        T: Copy,
        F: FnOnce(T) -> R,
    {
        unsafe {
            let _ = suspend_self();
            let orig: T = std::mem::transmute_copy(&self.target);
            let res = callback(orig);
            let _ = resume_self();
            res
        }
    }
}

/// Installs a hardware breakpoint hook at an absolute address
///
/// # Arguments
/// * `target` - The absolute address to hook
/// * `replacement` - The address of the replacement function
///
/// # Returns
/// * `Result<Breakpoint, BrkHookError>` - The installed breakpoint or an error
pub unsafe fn install_at_address(
    target: usize,
    replacement: usize,
) -> Result<Breakpoint, BrkHookError> {
    unsafe {
        init_exception_handler()?;

        let mut manager = MANAGER.lock();

        if manager.active_count >= manager.hw_breakpoints as usize {
            return Err(BrkHookError::ExceedsHwBreakpoints(manager.hw_breakpoints));
        }

        manager.add_hook(target, replacement)?;
        apply_debug_state(&manager)?;

        #[cfg(debug_assertions)]
        logger::info(&format!("BrkHook: {:#x}{:#x}", target, replacement));

        Ok(Breakpoint { target })
    }
}

/// Removes a hardware breakpoint hook at an absolute address
///
/// # Arguments
/// * `target` - The absolute address where the hook is installed
///
/// # Returns
/// * `Result<(), BrkHookError>` - Result indicating success or failure
pub unsafe fn remove_at_address(target: usize) -> Result<(), BrkHookError> {
    unsafe {
        let mut manager = MANAGER.lock();
        manager.remove_hook(target)?;
        apply_debug_state(&manager)?;
        Ok(())
    }
}

/// Returns the number of active breakpoints
///
/// # Returns
/// * `usize` - The count of active breakpoints
pub fn active_count() -> usize {
    MANAGER.lock().active_count
}

/// Returns the maximum number of hardware breakpoints supported by the device
///
/// # Returns
/// * `i32` - The maximum number of breakpoints
pub fn max_breakpoints() -> i32 {
    MANAGER.lock().hw_breakpoints
}

/// Suspends the current thread (disables breakpoints for this thread)
///
/// Use this before calling the original function to avoid infinite recursion loops.
///
/// # Returns
/// * `Result<(), BrkHookError>` - Result indicating success or failure
pub unsafe fn suspend_self() -> Result<(), BrkHookError> {
    unsafe {
        let thread = mach_thread_self();
        let state = ArmDebugState64::default();

        if thread_set_state(
            thread,
            ARM_DEBUG_STATE64,
            &state as *const _ as *mut u32,
            ARM_DEBUG_STATE64_COUNT,
        ) != KERN_SUCCESS
        {
            return Err(BrkHookError::SetStateFailed);
        }

        mach_port_deallocate(mach_task_self(), thread);
        Ok(())
    }
}

/// Resumes the current thread (re-enables breakpoints for this thread)
///
/// Use this after calling the original function to re-arm the breakpoints.
///
/// # Returns
/// * `Result<(), BrkHookError>` - Result indicating success or failure
pub unsafe fn resume_self() -> Result<(), BrkHookError> {
    unsafe {
        let thread = mach_thread_self();
        let mut state = ArmDebugState64::default();

        {
            let manager = MANAGER.lock();
            for (bp_idx, hook) in manager.hooks.iter().flatten().enumerate() {
                if bp_idx >= manager.hw_breakpoints as usize {
                    break;
                }
                state.bvr[bp_idx] = hook.old as u64;
                state.bcr[bp_idx] = BCR_ENABLE;
            }
        }

        if thread_set_state(
            thread,
            ARM_DEBUG_STATE64,
            &state as *const _ as *mut u32,
            ARM_DEBUG_STATE64_COUNT,
        ) != KERN_SUCCESS
        {
            mach_port_deallocate(mach_task_self(), thread);
            return Err(BrkHookError::SetStateFailed);
        }

        mach_port_deallocate(mach_task_self(), thread);
        Ok(())
    }
}