barebone: Run a copy in a Windows arm64 process

Four things stood between a placed copy and a running one.

The copy asked the translation control register for the page size,
which only the kernel may do. Tell it the answer instead.

Making written code visible asked for cache maintenance a process may
not do, thus ask the system. The kernel half asked for the whole
instruction cache, which says nothing about the other processors nor
about writes still in the data cache, thus do it line by line.

The guard refuses a call to an address the memory manager never
handed out, and a thread starts by way of such a call. Give the copy
memory the manager knows about, say which addresses in it may be
called, and start the thread on a jump the guard accepts.

Give the ground back only once the thread that carried the copy is
gone.

Listing threads is the asking half's own business: walk the list the
process keeps rather than every list on the machine, ask the manager
before reading an address the walk worked out, and fill in the
registers only for a caller that asked for them.

Leave the session server alone: it refuses code of its own and is
critical, thus a copy placed there stops the machine.
This commit is contained in:
Ole André Vadla Ravnås committed 2026-09-16 17:34:12 +02:00
1 parent 287c75d8a7
commit d959ad23a6
10 files changed
+598 -193

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ SECTIONS {
_PsGetCurrentThread = .; . += 8;
_PsGetThreadProcess = .; . += 8;
_PsGetThreadId = .; . += 8;
_PsGetThreadTeb = .; . += 8;
_PsGetContextThread = .; . += 8;
_PsSetContextThread = .; . += 8;
_KeStackAttachProcess = .; . += 8;
+1
View File
@@ -40,6 +40,7 @@ SECTIONS {
_PsGetCurrentThread = .; . += 4;
_PsGetThreadProcess = .; . += 4;
_PsGetThreadId = .; . += 4;
_PsGetThreadTeb = .; . += 4;
_PsGetContextThread = .; . += 4;
_PsSetContextThread = .; . += 4;
_KeStackAttachProcess = .; . += 4;
@@ -45,6 +45,7 @@ SECTIONS {
_PsGetCurrentThread = .; . += 8;
_PsGetThreadProcess = .; . += 8;
_PsGetThreadId = .; . += 8;
_PsGetThreadTeb = .; . += 8;
_PsGetContextThread = .; . += 8;
_PsSetContextThread = .; . += 8;
_KeStackAttachProcess = .; . += 8;
+8 -5
View File
@@ -347,7 +347,7 @@ pub extern "C" fn _gum_process_enumerate_ranges(
pub extern "C" fn gum_barebone_on_thread_registry_activating(registry: *mut GumThreadRegistry) {
unsafe { THREAD_REGISTRY = registry };
kernel::enumerate_threads(&mut |thread| announce_thread(thread.id));
kernel::enumerate_threads(&mut |thread| announce_thread(thread.id), false);
if kernel::watches_threads() {
kernel::watch_threads(announce_thread, announce_thread_is_gone);
@@ -446,11 +446,13 @@ fn announce_thread_is_gone(id: u32) {
static mut THREAD_REGISTRY: *mut GumThreadRegistry = ptr::null_mut();
#[unsafe(no_mangle)]
pub extern "C" fn gum_barebone_enumerate_threads(func: GumFoundThreadFunc, user_data: gpointer) {
pub extern "C" fn gum_barebone_enumerate_threads(func: GumFoundThreadFunc, user_data: gpointer,
flags: GumThreadFlags) {
let Some(emit) = func else {
return;
};
let wanted = (flags & GumThreadFlags_GUM_THREAD_FLAGS_CPU_CONTEXT) != 0;
kernel::enumerate_threads(&mut |thread| {
let mut details: GumThreadDetails = unsafe { core::mem::zeroed() };
details.flags = 0;
@@ -462,13 +464,14 @@ pub extern "C" fn gum_barebone_enumerate_threads(func: GumFoundThreadFunc, user_
}
unsafe { emit(&details, user_data) };
});
}, wanted);
}
#[unsafe(no_mangle)]
pub extern "C" fn gum_barebone_find_thread_by_id(thread_id: GumThreadId, _flags: GumThreadFlags)
pub extern "C" fn gum_barebone_find_thread_by_id(thread_id: GumThreadId, flags: GumThreadFlags)
-> *mut GumThreadDetails {
let Some(thread) = kernel::find_thread(thread_id as u32) else {
let wanted = (flags & GumThreadFlags_GUM_THREAD_FLAGS_CPU_CONTEXT) != 0;
let Some(thread) = kernel::find_thread(thread_id as u32, wanted) else {
return ptr::null_mut();
};
+6 -14
View File
@@ -134,24 +134,16 @@ pub extern "C" fn __aeabi_uwrite8(value: u64, address: *mut u8) -> u64 {
value
}
#[cfg(all(target_arch = "aarch64", not(any(feature = "linux-injected", feature = "xnu-core"))))]
#[unsafe(no_mangle)]
pub extern "C" fn __clear_cache(_start: *const u8, _end: *const u8) {
unsafe {
core::arch::asm!(
"ic iallu", // Invalidate all instruction caches
"dsb sy", // Data synchronization barrier
"isb", // Instruction synchronization barrier
options(nomem, nostack),
);
}
}
// Invalidating the whole instruction cache is the kernel's to do, and the copy runs where that
// instruction is not allowed. Line by line is what both halves may ask for.
#[cfg(all(target_arch = "aarch64", any(feature = "linux-injected", feature = "xnu-core")))]
#[cfg(target_arch = "aarch64")]
#[unsafe(no_mangle)]
pub extern "C" fn __clear_cache(start: *const u8, end: *const u8) {
#[cfg(feature = "winnt")]
if crate::winnt_user::flush_code(start, end) {
return;
}
#[cfg(feature = "xnu-core")]
let told = crate::kernel::cache_shape();
#[cfg(not(feature = "xnu-core"))]
+23 -14
View File
@@ -1114,8 +1114,8 @@ pub struct Primitives {
pub protect: fn(u64, usize, u32) -> bool,
pub protection_at: fn(usize) -> u32,
pub enumerate_ranges: fn(&mut dyn FnMut(u64, u64, u32)),
pub enumerate_threads: fn(&mut dyn FnMut(ThreadInfo)),
pub find_thread: fn(u32) -> Option<ThreadInfo>,
pub enumerate_threads: fn(&mut dyn FnMut(ThreadInfo), bool),
pub find_thread: fn(u32, bool) -> Option<ThreadInfo>,
pub modify_thread: fn(u32, &mut dyn FnMut(&mut CpuState)) -> bool,
}
@@ -1252,14 +1252,17 @@ mod kernel {
unsafe { get_cur_thread_handle() as u64 }
}
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
super::enumerate_ring_zero_threads(found)
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
super::enumerate_ring_zero_threads(found, with_registers)
}
pub fn find_thread(id: u32) -> Option<ThreadInfo> {
pub fn find_thread(id: u32, with_registers: bool) -> Option<ThreadInfo> {
let thread = super::ring_zero_thread(id)?;
Some(ThreadInfo { id, cpu_state: super::thread_cpu_state(thread) })
Some(ThreadInfo {
id,
cpu_state: with_registers.then(|| super::thread_cpu_state(thread)).flatten(),
})
}
pub fn modify_thread(id: u32, change: &mut dyn FnMut(&mut CpuState)) -> bool {
@@ -1643,12 +1646,12 @@ pub fn install_interrupt_handler(
if handle == 0 { -1 } else { 0 }
}
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
(primitives().enumerate_threads)(found)
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
(primitives().enumerate_threads)(found, with_registers)
}
pub fn find_thread(id: u32) -> Option<ThreadInfo> {
(primitives().find_thread)(id)
pub fn find_thread(id: u32, with_registers: bool) -> Option<ThreadInfo> {
(primitives().find_thread)(id, with_registers)
}
pub fn modify_thread(id: u32, change: &mut dyn FnMut(&mut CpuState)) -> bool {
@@ -1690,9 +1693,12 @@ pub fn thread_handle_of(pid: u32, id: u32) -> Option<u32> {
// The threads of one process, as the copy in it sees them. Ring 3 of this system reaches both
// the services and the memory the kernel keeps, thus the copy walks the same list the kernel
// half does and keeps what belongs to it, registers and all.
pub fn enumerate_threads_of(pid: u32, found: &mut dyn FnMut(ThreadInfo)) {
pub fn enumerate_threads_of(pid: u32, found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
enumerate_thread_handles_of(pid, &mut |thread, id| {
found(ThreadInfo { id, cpu_state: thread_cpu_state(thread) });
found(ThreadInfo {
id,
cpu_state: with_registers.then(|| thread_cpu_state(thread)).flatten(),
});
});
}
@@ -1734,13 +1740,16 @@ fn ring_zero_thread(id: u32) -> Option<u32> {
None
}
fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo)) {
fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
let vm = unsafe { get_sys_vm_handle() };
let first = unsafe { get_initial_thread_handle(vm) };
let mut thread = first;
while thread != 0 {
found(ThreadInfo { id: thread, cpu_state: thread_cpu_state(thread) });
found(ThreadInfo {
id: thread,
cpu_state: with_registers.then(|| thread_cpu_state(thread)).flatten(),
});
let next = unsafe { get_next_thread_handle(thread) };
thread = if next == first { 0 } else { next };
+7 -4
View File
@@ -262,14 +262,17 @@ fn enumerate_ranges(found: &mut dyn FnMut(u64, u64, u32)) {
}
}
fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo)) {
crate::win9x::enumerate_threads_of(current_process_id(), found)
fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo), with_registers: bool) {
crate::win9x::enumerate_threads_of(current_process_id(), found, with_registers)
}
fn find_thread(id: u32) -> Option<crate::kernel::ThreadInfo> {
fn find_thread(id: u32, with_registers: bool) -> Option<crate::kernel::ThreadInfo> {
let thread = crate::win9x::thread_handle_of(current_process_id(), id)?;
Some(crate::kernel::ThreadInfo { id, cpu_state: crate::win9x::thread_cpu_state(thread) })
Some(crate::kernel::ThreadInfo {
id,
cpu_state: with_registers.then(|| crate::win9x::thread_cpu_state(thread)).flatten(),
})
}
fn modify_thread(id: u32, change: &mut dyn FnMut(&mut crate::kernel::CpuState)) -> bool {
+378 -104
View File
@@ -18,7 +18,6 @@ pub use crate::winnt_user::{
resume_process, spawn_process, thread_entry_points, thread_exit_slot, thread_start_slot,
ThreadEntryPoints,
};
use crate::winnt_paging::{GUM_PAGE_EXECUTE, GUM_PAGE_READ};
#[cfg(target_arch = "x86")]
#[cfg(target_arch = "x86")]
@@ -116,9 +115,20 @@ pub fn free_code(ptr: *mut u8, size: usize) {
}
pub fn page_size() -> usize {
let told = unsafe { PAGE_SIZE_IN_PROCESS };
if told != 0 {
return told;
}
crate::gum::page_size_the_kernel_runs_with()
}
pub(crate) fn be_told_page_size(size: usize) {
unsafe { PAGE_SIZE_IN_PROCESS = size };
}
static mut PAGE_SIZE_IN_PROCESS: usize = 0;
pub fn alloc_heap(size: usize) -> *mut u8 {
alloc(size)
}
@@ -1386,29 +1396,30 @@ const INVALID_OPCODE: u32 = 6;
const GENERAL_PROTECTION: u32 = 13;
const PAGE_FAULT: u32 = 14;
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
(primitives().enumerate_threads)(found)
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
(primitives().enumerate_threads)(found, with_registers)
}
pub fn find_thread(id: u32) -> Option<ThreadInfo> {
(primitives().find_thread)(id)
pub fn find_thread(id: u32, with_registers: bool) -> Option<ThreadInfo> {
(primitives().find_thread)(id, with_registers)
}
pub fn modify_thread(id: u32, change: &mut dyn FnMut(&mut CpuState)) -> bool {
(primitives().modify_thread)(id, change)
}
fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo)) {
fn enumerate_ring_zero_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
let Some(layout) = thread_layout() else {
found(ThreadInfo { id: current_thread_id() as u32, cpu_state: None });
return;
};
let _ = layout;
enumerate_thread_objects(&mut |thread| unsafe {
let ours = unsafe { (_PsGetThreadProcess)((_PsGetCurrentThread)()) };
walk_threads_of(ours, &mut |thread| unsafe {
found(ThreadInfo {
id: (_PsGetThreadId)(thread),
cpu_state: capture(thread),
cpu_state: with_registers.then(|| capture(thread)).flatten(),
});
});
}
@@ -1437,6 +1448,7 @@ fn modify_ring_zero_thread(id: u32, change: &mut dyn FnMut(&mut CpuState)) -> bo
}
}
fn ring_zero_thread(id: u32) -> Option<*mut c_void> {
let mut wanted = core::ptr::null_mut();
enumerate_thread_objects(&mut |thread| unsafe {
@@ -1449,26 +1461,42 @@ fn ring_zero_thread(id: u32) -> Option<*mut c_void> {
}
fn enumerate_thread_objects(found: &mut dyn FnMut(*mut c_void)) {
enumerate_processes(&mut |process| walk_threads_of(process.handle, found));
}
fn walk_threads_of(process: *mut c_void, found: &mut dyn FnMut(*mut c_void)) {
let Some(layout) = thread_layout() else {
return;
};
enumerate_processes(&mut |process| unsafe {
let head = process.handle as usize + layout.head;
let mut entry = (head as *const usize).read_volatile();
while entry != head && entry != 0 {
found((entry - layout.entry) as *mut c_void);
entry = (entry as *const usize).read_volatile();
unsafe {
let head = process as usize + layout.head;
let mut node = head;
for _ in 0..MAX_THREADS_PER_PROCESS {
let Some(next) = try_read_pointer(node) else {
return;
};
node = next;
if node == head || node < layout.entry {
return;
}
let thread = (node - layout.entry) as *mut c_void;
if !names_a_thread_of(process, thread) {
return;
}
found(thread);
}
});
}
}
// The kernel gives the registers of a thread only if the thread has a user-mode part. If the
// thread runs only in the kernel, the kernel reads after the end of its stack and stops the
// machine. A thread also cannot ask about itself.
unsafe fn capture(thread: *mut c_void) -> Option<CpuState> {
unsafe {
if (_PsGetProcessPeb)((_PsGetThreadProcess)(thread)).is_null() {
if (_PsGetThreadTeb)(thread).is_null() {
return None;
}
if thread == (_PsGetCurrentThread)() {
@@ -1492,6 +1520,46 @@ static mut CONTEXT: [u8; CONTEXT_SIZE + CONTEXT_ALIGNMENT] = [0; CONTEXT_SIZE +
// No export gives the position of the thread list in a process. Thus calculate both offsets:
// the caller is on the list, and its own links go back into its process.
unsafe fn list_holds_threads_of(process: usize, layout: ThreadLayout) -> bool {
unsafe {
let head = process + layout.head;
let Some(mut node) = try_read_pointer(head) else {
return false;
};
if try_read_pointer(node + POINTER_SIZE) != Some(head) {
return false;
}
let mut vouched = 0;
while node != head && vouched != THREADS_TO_VOUCH_FOR {
if node < layout.entry {
return false;
}
if !names_a_thread_of(process as *mut c_void, (node - layout.entry) as *mut c_void) {
return false;
}
let Some(next) = try_read_pointer(node) else {
return false;
};
node = next;
vouched += 1;
}
vouched != 0
}
}
fn names_a_thread_of(process: *mut c_void, thread: *mut c_void) -> bool {
unsafe {
(_MmIsAddressValid)(thread as *const c_void) != 0
&& (_PsGetThreadProcess)(thread) == process
&& (_PsGetThreadId)(thread) != 0
}
}
const THREADS_TO_VOUCH_FOR: usize = 2;
fn thread_layout() -> Option<ThreadLayout> {
unsafe {
if let Some(known) = THREAD_LAYOUT {
@@ -1502,12 +1570,17 @@ fn thread_layout() -> Option<ThreadLayout> {
let process = (_PsGetThreadProcess)(me as *mut c_void) as usize;
for entry in (MIN_THREAD_ENTRY_OFFSET..MAX_OBJECT_SIZE).step_by(POINTER_SIZE) {
let mut node = try_read_pointer(me + entry)?;
let Some(mut node) = try_read_pointer(me + entry) else {
continue;
};
for _ in 0..MAX_THREADS_PER_PROCESS {
if node >= process && node < process + MAX_OBJECT_SIZE {
let layout = ThreadLayout { head: node - process, entry };
THREAD_LAYOUT = Some(layout);
return Some(layout);
if list_holds_threads_of(process, layout) {
THREAD_LAYOUT = Some(layout);
return Some(layout);
}
break;
}
let Some(next) = try_read_pointer(node) else {
break;
@@ -1531,6 +1604,10 @@ static mut THREAD_LAYOUT: Option<ThreadLayout> = None;
// This walk uses calculated addresses, thus read through Gum, which recovers from a fault.
unsafe fn try_read_pointer(address: usize) -> Option<usize> {
unsafe {
if (_MmIsAddressValid)(address as *const c_void) == 0 {
return None;
}
let mut read: crate::bindings::gsize = 0;
let data = crate::bindings::gum_memory_read(address as *const c_void, POINTER_SIZE as crate::bindings::gsize,
&mut read);
@@ -1788,6 +1865,22 @@ unsafe fn read_from(process: *mut c_void, address: usize, out: &mut [u8]) -> boo
}
}
unsafe fn write_to(process: *mut c_void, address: usize, bytes: &[u8]) -> bool {
unsafe {
let mut copied: usize = 0;
let status = (_MmCopyVirtualMemory)(
(_PsGetThreadProcess)((_PsGetCurrentThread)()),
bytes.as_ptr() as *const c_void,
process,
address as *mut c_void,
bytes.len(),
KERNEL_MODE as u8,
&mut copied,
);
status >= 0 && copied == bytes.len()
}
}
unsafe fn read_word_from(process: *mut c_void, address: usize) -> Option<usize> {
let mut word = [0u8; POINTER_SIZE];
if !unsafe { read_from(process, address, &mut word) } {
@@ -1919,8 +2012,6 @@ pub fn place_agent_in_process(pid: u32) -> bool {
return true;
}
put_a_copy_in_the_session_server(pid);
let library = loader_library();
let mut placed = Placement::default();
@@ -1942,51 +2033,20 @@ pub fn place_agent_in_process(pid: u32) -> bool {
let mut wake: *mut c_void = core::ptr::null_mut();
let mut work = || unsafe {
let private = alloc(private_size);
if private.is_null() {
let whole = put_image_in_process(process, private_offset, shared_size, private_size);
if whole == 0 {
return;
}
core::ptr::write_bytes(private, 0, private_size);
let shared_mdl = (_IoAllocateMdl)(own.base_address as *mut c_void, shared_size as u32, 0, 0,
core::ptr::null_mut());
let private_mdl = (_IoAllocateMdl)(private as *mut c_void, private_size as u32, 0, 0,
core::ptr::null_mut());
if shared_mdl.is_null() || private_mdl.is_null() {
return;
}
(_MmBuildMdlForNonPagedPool)(shared_mdl);
(_MmBuildMdlForNonPagedPool)(private_mdl);
placed.shared_mdl = shared_mdl;
placed.private_mdl = private_mdl;
vouch_for_range(process, whole, shared_size);
placed.seen_by_process = whole;
let mut apc_state = [0usize; APC_STATE_WORDS];
(_KeStackAttachProcess)(process, apc_state.as_mut_ptr() as *mut u8);
// The memory manager selects the address of the code. The distance to the writable half is a
// property of the image, thus the code asks for that address.
for _ in 0..MAX_PLACEMENT_TRIES {
let text = (_MmMapLockedPagesSpecifyCache)(shared_mdl, USER_MODE, MM_CACHED,
core::ptr::null_mut(), 0, NORMAL_PAGE_PRIORITY);
if text.is_null() {
break;
}
crate::libc::__clear_cache(whole as *const u8, (whole + shared_size as u64) as *const u8);
let wanted = (text as usize + private_offset) as *mut c_void;
if (_MmMapLockedPagesSpecifyCache)(private_mdl, USER_MODE, MM_CACHED, wanted, 0,
NORMAL_PAGE_PRIORITY) == wanted {
// The mapping gives no permission to execute.
protect(text as u64, shared_size, GUM_PAGE_READ | GUM_PAGE_EXECUTE);
crate::install_writable_half(text as usize, private as usize);
placed.seen_by_process = text as u64;
placed.writable_from_here = private as u64;
break;
}
(_MmUnmapLockedPages)(text, shared_mdl);
}
if placed.seen_by_process != 0 {
{
let arena = alloc(ARENA_SIZE);
core::ptr::write_bytes(arena, 0, ARENA_SIZE);
@@ -2007,6 +2067,7 @@ pub fn place_agent_in_process(pid: u32) -> bool {
(arena.add(TARGET_WAKE_HANDLE as usize) as *mut u64)
.write(open_event_in_current_process(wake) as u64);
(arena.add(LOADER_LIBRARY as usize) as *mut u64).write(library);
(arena.add(PAGE_SIZE_IN_USE as usize) as *mut u64).write(page_size() as u64);
(arena.add(IMAGE_BASE as usize) as *mut u64)
.write(placed.seen_by_process);
(arena.add(IMAGE_SIZE as usize) as *mut u64)
@@ -2030,11 +2091,9 @@ pub fn place_agent_in_process(pid: u32) -> bool {
started: false,
text: placed.seen_by_process,
size: own.size as u64,
private: placed.writable_from_here,
private_size,
stack: 0,
shared_mdl: placed.shared_mdl,
private_mdl: placed.private_mdl,
step: 0,
carrier: core::ptr::null_mut(),
arena_mdl: placed.arena_mdl,
})
};
@@ -2046,11 +2105,8 @@ pub fn place_agent_in_process(pid: u32) -> bool {
#[derive(Default)]
pub struct Placement {
pub seen_by_process: u64,
pub writable_from_here: u64,
pub arena_seen_by_process: u64,
pub arena_here: u64,
pub shared_mdl: *mut c_void,
pub private_mdl: *mut c_void,
pub arena_mdl: *mut c_void,
}
@@ -2094,24 +2150,38 @@ pub fn detach_from_process(pid: u32) -> bool {
});
let mut work = || unsafe {
if !process.is_null() {
let mut apc_state = [0usize; APC_STATE_WORDS];
(_KeStackAttachProcess)(process, apc_state.as_mut_ptr() as *mut u8);
(_MmUnmapLockedPages)(target.text as *mut c_void, target.shared_mdl);
(_MmUnmapLockedPages)((target.text + target.private_offset()) as *mut c_void,
target.private_mdl);
(_MmUnmapLockedPages)(target.seen as *mut c_void, target.arena_mdl);
(_KeUnstackDetachProcess)(apc_state.as_mut_ptr() as *mut u8);
let mut carried_out = target.carrier.is_null();
if !target.carrier.is_null() {
let patience: i64 = -(LEAVE_PATIENCE_US * 10);
carried_out = (_ZwWaitForSingleObject)(target.carrier, 0, &patience) == 0;
(_ZwClose)(target.carrier);
}
(_IoFreeMdl)(target.shared_mdl);
(_IoFreeMdl)(target.private_mdl);
(_IoFreeMdl)(target.arena_mdl);
if carried_out {
if !process.is_null() {
let mut apc_state = [0usize; APC_STATE_WORDS];
(_KeStackAttachProcess)(process, apc_state.as_mut_ptr() as *mut u8);
free(target.private as *mut u8, target.private_size);
free(target.arena as *mut u8, ARENA_SIZE);
(_MmUnmapLockedPages)(target.seen as *mut c_void, target.arena_mdl);
(_KeUnstackDetachProcess)(apc_state.as_mut_ptr() as *mut u8);
let mut process_handle: *mut c_void = core::ptr::null_mut();
let process_type = (_PsProcessType as *const *mut c_void).read();
if (_ObOpenObjectByPointer)(process, 0, core::ptr::null_mut(), PROCESS_ALL_ACCESS,
process_type, KERNEL_MODE as u32, &mut process_handle) >= 0 {
for taken in [target.text, target.stack, target.step] {
if taken != 0 {
free_in_process(process_handle, taken);
}
}
(_ZwClose)(process_handle);
}
}
(_IoFreeMdl)(target.arena_mdl);
free(target.arena as *mut u8, ARENA_SIZE);
}
if !target.wake.is_null() {
(_ZwClose)(target.wake);
@@ -2144,6 +2214,7 @@ fn copy_has_left(target: &Target) -> bool {
}
const LEAVE_ATTEMPTS: u32 = 40;
const LEAVE_PATIENCE_US: i64 = 2_000_000;
const LEAVE_SLICE_US: u64 = 50_000;
pub fn stop_copies() {
@@ -2179,8 +2250,11 @@ pub fn start_agent_in_process(pid: u32) -> u32 {
}
let mut stack = 0u64;
let mut step = 0u64;
let mut carrier: *mut c_void = core::ptr::null_mut();
let mut work = || {
create_user_thread(process, arena, seen, bootstrap, entry, &mut stack);
create_user_thread(process, arena, seen, bootstrap, entry, &mut stack, &mut step,
&mut carrier);
};
on_kernel_stack(&mut work);
@@ -2188,6 +2262,8 @@ pub fn start_agent_in_process(pid: u32) -> u32 {
let target = targets().get_mut(&pid).unwrap();
target.started = true;
target.stack = stack;
target.step = step;
target.carrier = carrier;
};
}
@@ -2199,6 +2275,54 @@ pub fn start_agent_in_process(pid: u32) -> u32 {
observed
}
fn put_image_in_process(process: *mut c_void, private_offset: usize, shared_size: usize,
private_size: usize) -> u64 {
let own = unsafe { &*core::ptr::addr_of!(crate::OWN_RANGE) };
let mut process_handle: *mut c_void = core::ptr::null_mut();
unsafe {
let process_type = (_PsProcessType as *const *mut c_void).read();
if (_ObOpenObjectByPointer)(process, 0, core::ptr::null_mut(), PROCESS_ALL_ACCESS,
process_type, KERNEL_MODE as u32, &mut process_handle) < 0 {
return 0;
}
}
let whole = allocate_in_process(process_handle, own.size as usize, PAGE_EXECUTE_READWRITE);
let carried = whole != 0 && carry_image_across(process, whole, private_offset, shared_size,
private_size);
if whole != 0 && !carried {
free_in_process(process_handle, whole);
}
unsafe { (_ZwClose)(process_handle) };
if carried { whole } else { 0 }
}
fn carry_image_across(process: *mut c_void, whole: u64, private_offset: usize, shared_size: usize,
private_size: usize) -> bool {
let own = unsafe { &*core::ptr::addr_of!(crate::OWN_RANGE) };
let private = alloc(private_size);
if private.is_null() {
return false;
}
unsafe {
crate::install_writable_half(whole as usize, private as usize);
let text = core::slice::from_raw_parts(own.base_address as *const u8, shared_size);
let half = core::slice::from_raw_parts(private as *const u8, private_size);
let carried = write_to(process, whole as usize, text)
&& write_to(process, (whole + private_offset as u64) as usize, half);
free(private, private_size);
carried
}
}
fn put_a_copy_in_the_session_server(pid: u32) {
let server = session_server_pid();
if server == 0 || server == pid || arena_for_pid(server).is_some() {
@@ -2404,6 +2528,7 @@ fn synthesize_zw_stub(index: u32) -> usize {
at += bytes.len();
};
emit_zw_stub(template, stub, index, &mut put);
crate::libc::__clear_cache(stub, stub.add(ZW_STUB_SIZE));
}
stub as usize
@@ -2473,7 +2598,7 @@ unsafe fn emit_zw_stub(template: *const u8, stub: *mut u8, index: u32,
// ntdll's stub for a service begins by loading the same index that the kernel uses.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn service_index_of(ntdll: usize, name: &[u8]) -> u32 {
fn service_index_of(_process: *mut c_void, ntdll: usize, name: &[u8]) -> u32 {
let stub = export(ntdll, name);
if stub == 0 {
return 0;
@@ -2592,7 +2717,7 @@ fn name_is_in(process: *mut c_void, name: usize, wanted: &[u8]) -> bool {
const MAX_EXPORT_NAME: usize = 64;
fn create_user_thread(process: *mut c_void, arena_here: u64, arena_seen: u64, _bootstrap: u64,
entry: u64, stack: &mut u64) -> bool {
entry: u64, stack: &mut u64, step: &mut u64, carrier: &mut *mut c_void) -> bool {
unsafe {
let mut process_handle: *mut c_void = core::ptr::null_mut();
let process_type = (_PsProcessType as *const *mut c_void).read();
@@ -2602,7 +2727,7 @@ fn create_user_thread(process: *mut c_void, arena_here: u64, arena_seen: u64, _b
}
let created = start_thread_in_process(process, process_handle, arena_here, arena_seen,
entry, stack);
entry, stack, step, carrier);
(_ZwClose)(process_handle);
@@ -2613,7 +2738,8 @@ fn create_user_thread(process: *mut c_void, arena_here: u64, arena_seen: u64, _b
// The thread is made the way the system makes them, thus it arrives with a block of its own and
// ntdll accepts calls from it.
fn start_thread_in_process(process: *mut c_void, process_handle: *mut c_void, arena_here: u64,
arena_seen: u64, entry: u64, remembered: &mut u64) -> bool {
arena_seen: u64, entry: u64, remembered: &mut u64, step: &mut u64,
carrier: &mut *mut c_void) -> bool {
let stack = allocate_in_process(process_handle, STACK_SIZE, PAGE_READWRITE);
if stack == 0 {
return false;
@@ -2659,13 +2785,9 @@ fn start_thread_in_process(process: *mut c_void, process_handle: *mut c_void, ar
((teb + INITIAL_TEB_STACK_LIMIT) as *mut usize).write(stack as usize);
((teb + INITIAL_TEB_ALLOCATION_BASE) as *mut usize).write(stack as usize);
let mut thread: *mut c_void = core::ptr::null_mut();
let mut client_id = [0usize; 2];
let status = start(&mut thread, process_handle, &mut client_id, context, teb, entry,
arena_seen, create);
if status >= 0 {
(_ZwClose)(thread);
}
let status = start(carrier, process_handle, &mut client_id, context, teb, entry,
arena_seen, create, process, ntdll, step);
status >= 0
}
@@ -2704,7 +2826,8 @@ const SERVICE_NAME: &[u8] = b"NtCreateThreadEx";
unsafe fn start(thread: *mut *mut c_void, process_handle: *mut c_void, client_id: &mut [usize; 2],
context: u64, teb: u64, _entry: u64, _argument: u64,
create: windows_fn!(*mut *mut c_void, u32, *mut c_void, *mut c_void, *mut c_void, *mut u8,
*mut c_void, u8, => i32)) -> i32 {
*mut c_void, u8, => i32), _process: *mut c_void, _ntdll: usize,
_step: &mut u64) -> i32 {
unsafe {
create(thread, THREAD_ALL_ACCESS, core::ptr::null_mut(), process_handle,
client_id.as_mut_ptr() as *mut c_void, context as *mut u8, teb as *mut c_void, 0)
@@ -2715,16 +2838,156 @@ unsafe fn start(thread: *mut *mut c_void, process_handle: *mut c_void, client_id
unsafe fn start(thread: *mut *mut c_void, process_handle: *mut c_void, _client_id: &mut [usize; 2],
_context: u64, _teb: u64, entry: u64, argument: u64,
create: windows_fn!(*mut *mut c_void, u32, *mut c_void, *mut c_void, *mut c_void, *mut u8,
*mut c_void, u8, => i32)) -> i32 {
*mut c_void, u8, => i32), process: *mut c_void, ntdll: usize,
taken: &mut u64) -> i32 {
unsafe {
let step = step_to(process, process_handle, ntdll, entry);
if step == 0 {
return STATUS_NOT_FOUND;
}
*taken = step;
let create_ex: windows_fn!(*mut *mut c_void, u32, *mut c_void, *mut c_void, *mut c_void,
*mut c_void, u32, usize, usize, usize, *mut c_void => i32) =
core::mem::transmute(create);
create_ex(thread, THREAD_ALL_ACCESS, core::ptr::null_mut(), process_handle,
entry as *mut c_void, argument as *mut c_void, 0, 0, 0, 0, core::ptr::null_mut())
step as *mut c_void, argument as *mut c_void, 0, 0, 0, 0, core::ptr::null_mut())
}
}
#[cfg(target_arch = "aarch64")]
fn step_to(process: *mut c_void, process_handle: *mut c_void, ntdll: usize, entry: u64) -> u64 {
let step = allocate_in_process(process_handle, STEP_SIZE, PAGE_EXECUTE_READWRITE);
if step == 0 {
return 0;
}
unsafe {
let mut apc_state = [0usize; APC_STATE_WORDS];
(_KeStackAttachProcess)(process, apc_state.as_mut_ptr() as *mut u8);
(step as *mut u32).write(LOAD_STEP_TARGET);
((step + 4) as *mut u32).write(BRANCH_TO_STEP_TARGET);
((step + 8) as *mut u64).write(entry);
crate::libc::__clear_cache(step as *const u8, (step + STEP_SIZE as u64) as *const u8);
(_KeUnstackDetachProcess)(apc_state.as_mut_ptr() as *mut u8);
}
let_the_guard_know(process, process_handle, ntdll, step);
step
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn vouch_for_range(_process: *mut c_void, _base: u64, _size: usize) {}
#[cfg(target_arch = "aarch64")]
fn vouch_for_range(process: *mut c_void, base: u64, size: usize) {
let mut process_handle: *mut c_void = core::ptr::null_mut();
unsafe {
let process_type = (_PsProcessType as *const *mut c_void).read();
if (_ObOpenObjectByPointer)(process, 0, core::ptr::null_mut(), PROCESS_ALL_ACCESS,
process_type, KERNEL_MODE as u32, &mut process_handle) < 0 {
return;
}
}
let ntdll = loader_library() as usize;
let index = service_index_of(process, ntdll, b"NtSetInformationVirtualMemory");
if index != 0 {
let mut at = 0;
while at < size {
let span = (size - at).min(VOUCHED_SPAN);
vouch_for(index, process_handle, base + at as u64, span);
at += span;
}
}
unsafe { (_ZwClose)(process_handle) };
}
#[cfg(target_arch = "aarch64")]
fn vouch_for(index: u32, process_handle: *mut c_void, base: u64, span: usize) {
let wanted = alloc((span / CALL_TARGET_GRAIN) * 16);
if wanted.is_null() {
return;
}
unsafe {
let entries = wanted as *mut u64;
let count = span / CALL_TARGET_GRAIN;
for slot in 0..count {
entries.add(slot * 2).write((slot * CALL_TARGET_GRAIN) as u64);
entries.add(slot * 2 + 1).write(CALL_TARGET_IS_VALID);
}
let tell: windows_fn!(*mut c_void, u32, usize, *mut u8, *mut u8, u32 => i32) =
core::mem::transmute(synthesize_zw_stub(index));
let mut range = [base, span as u64];
let mut taken = 0u32;
let mut list = [
count as u64,
&mut taken as *mut u32 as u64,
wanted as u64,
0,
0,
];
tell(process_handle, CFG_CALL_TARGET_INFORMATION, 1, range.as_mut_ptr() as *mut u8,
list.as_mut_ptr() as *mut u8, CALL_TARGET_LIST_SIZE);
}
free(wanted, (span / CALL_TARGET_GRAIN) * 16);
}
#[cfg(target_arch = "aarch64")]
const CALL_TARGET_GRAIN: usize = 16;
#[cfg(target_arch = "aarch64")]
const VOUCHED_SPAN: usize = 0x10000;
#[cfg(target_arch = "aarch64")]
fn let_the_guard_know(process: *mut c_void, process_handle: *mut c_void, ntdll: usize, step: u64) {
let index = service_index_of(process, ntdll, b"NtSetInformationVirtualMemory");
if index == 0 {
return;
}
unsafe {
let tell: windows_fn!(*mut c_void, u32, usize, *mut u8, *mut u8, u32 => i32) =
core::mem::transmute(synthesize_zw_stub(index));
let mut range = [step, STEP_SIZE as u64];
let mut wanted = [0u64, CALL_TARGET_IS_VALID];
let mut taken = 0u32;
let mut list = [
1u64,
&mut taken as *mut u32 as u64,
wanted.as_mut_ptr() as u64,
0,
0,
];
tell(process_handle, CFG_CALL_TARGET_INFORMATION, 1, range.as_mut_ptr() as *mut u8,
list.as_mut_ptr() as *mut u8, CALL_TARGET_LIST_SIZE);
}
}
#[cfg(target_arch = "aarch64")]
const CFG_CALL_TARGET_INFORMATION: u32 = 2;
#[cfg(target_arch = "aarch64")]
const CALL_TARGET_IS_VALID: u64 = 1;
#[cfg(target_arch = "aarch64")]
const CALL_TARGET_LIST_SIZE: u32 = 40;
#[cfg(target_arch = "aarch64")]
const STEP_SIZE: usize = 0x1000;
#[cfg(target_arch = "aarch64")]
const LOAD_STEP_TARGET: u32 = 0x5800_0050;
#[cfg(target_arch = "aarch64")]
const BRANCH_TO_STEP_TARGET: u32 = 0xd61f_0200;
#[cfg(target_arch = "aarch64")]
const STATUS_NOT_FOUND: i32 = -1_073_741_275;
// The argument travels in a register here, and the stack only has to be aligned the way a call
// would have left it.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
@@ -2749,6 +3012,13 @@ fn seed_stack(process: *mut c_void, top: u64, argument: u64) -> u64 {
sp
}
fn free_in_process(process_handle: *mut c_void, address: u64) {
let mut base = address as *mut u8;
let mut region = 0usize;
unsafe { (_ZwFreeVirtualMemory)(process_handle, &mut base, &mut region, MEM_RELEASE) };
}
fn allocate_in_process(process_handle: *mut c_void, size: usize, protection: u32) -> u64 {
let mut address: *mut u8 = core::ptr::null_mut();
let mut region = size;
@@ -2783,8 +3053,8 @@ pub struct Primitives {
pub protect: fn(u64, usize, u32) -> bool,
pub protection_at: fn(usize) -> u32,
pub enumerate_ranges: fn(&mut dyn FnMut(u64, u64, u32)),
pub enumerate_threads: fn(&mut dyn FnMut(ThreadInfo)),
pub find_thread: fn(u32) -> Option<ThreadInfo>,
pub enumerate_threads: fn(&mut dyn FnMut(ThreadInfo), bool),
pub find_thread: fn(u32, bool) -> Option<ThreadInfo>,
pub modify_thread: fn(u32, &mut dyn FnMut(&mut CpuState)) -> bool,
pub wait: fn(*const u8, Option<u64>, &mut dyn FnMut() -> bool),
pub wake: fn(*const u8),
@@ -2870,14 +3140,17 @@ mod kernel {
crate::winnt_paging::enumerate_ranges(found)
}
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo)) {
super::enumerate_ring_zero_threads(found)
pub fn enumerate_threads(found: &mut dyn FnMut(ThreadInfo), with_registers: bool) {
super::enumerate_ring_zero_threads(found, with_registers)
}
pub fn find_thread(id: u32) -> Option<ThreadInfo> {
pub fn find_thread(id: u32, with_registers: bool) -> Option<ThreadInfo> {
let thread = super::ring_zero_thread(id)?;
Some(ThreadInfo { id, cpu_state: unsafe { super::capture(thread) } })
Some(ThreadInfo {
id,
cpu_state: with_registers.then(|| unsafe { super::capture(thread) }).flatten(),
})
}
pub fn modify_thread(id: u32, change: &mut dyn FnMut(&mut CpuState)) -> bool {
@@ -3161,6 +3434,7 @@ pub(crate) const IMAGE_BASE: u64 = 0x50;
pub(crate) const IMAGE_SIZE: u64 = 0x58;
pub(crate) const OBSERVED_THREAD: u64 = 0x40;
pub(crate) const LOADER_LIBRARY: u64 = 0x60;
pub(crate) const PAGE_SIZE_IN_USE: u64 = 0x68;
pub(crate) const REGISTER_PROCESS: u64 = 0x18;
pub(crate) const REGISTER_THREAD: u64 = 0x1c;
@@ -3357,11 +3631,9 @@ struct Target {
introduced: bool,
text: u64,
size: u64,
private: u64,
private_size: usize,
stack: u64,
shared_mdl: *mut c_void,
private_mdl: *mut c_void,
step: u64,
carrier: *mut c_void,
arena_mdl: *mut c_void,
}
@@ -4306,6 +4578,7 @@ kernel_abi! {
static _PsGetCurrentThread: windows_fn!( => *mut c_void);
static _PsGetThreadProcess: windows_fn!(*mut c_void => *mut c_void);
static _PsGetThreadId: windows_fn!(*mut c_void => u32);
static _PsGetThreadTeb: windows_fn!(*mut c_void => *mut c_void);
static _PsGetContextThread: windows_fn!(*mut c_void, *mut u8, u8 => i32);
static _PsSetContextThread: windows_fn!(*mut c_void, *mut u8, u8 => i32);
static _KeStackAttachProcess: windows_fn!(*mut c_void, *mut u8);
@@ -4352,6 +4625,7 @@ kernel_abi! {
*const u32,
=> i32);
static _ZwClose: windows_fn!(*mut c_void => i32);
static _ZwWaitForSingleObject: windows_fn!(*mut c_void, u8, *const i64 => i32);
static _ZwCreateEvent: windows_fn!(*mut *mut c_void, u32, *mut c_void, u32, u8 => i32);
static _ExAllocatePool2: windows_fn!(u64, usize, u32 => *mut c_void);
static _MmCopyVirtualMemory: windows_fn!(*mut c_void, *const c_void, *mut c_void, *mut c_void,
+94 -52
View File
@@ -79,6 +79,10 @@ pub extern "C" fn frida_winnt_user_main(arena: usize) {
((arena + crate::winnt::IMAGE_SIZE as usize) as *const u64).read_volatile())
};
crate::winnt::be_told_page_size(
unsafe { ((arena + crate::winnt::PAGE_SIZE_IN_USE as usize) as *const u64).read_volatile() }
as usize);
crate::gthread::use_thread_slots(&SLOTS);
unsafe { crate::run_constructors() };
@@ -132,6 +136,16 @@ pub static USER: Primitives = Primitives {
shared_data,
};
pub(crate) fn flush_code(start: *const u8, end: *const u8) -> bool {
let Some(api) = (unsafe { (*core::ptr::addr_of!(USER_API)).as_ref() }) else {
return false;
};
unsafe { (api.flush_code)(CURRENT_PROCESS, start as *mut u8, end as usize - start as usize) };
true
}
pub(crate) fn yield_entry_point() -> usize {
unsafe { user_api().yield_execution as usize }
}
@@ -153,6 +167,7 @@ fn resolve_user_api() {
create_event: core::mem::transmute(export(ntdll, b"NtCreateEvent")),
close: core::mem::transmute(export(ntdll, b"NtClose")),
exit_thread: core::mem::transmute(export(ntdll, b"RtlExitUserThread")),
flush_code: core::mem::transmute(export(ntdll, b"NtFlushInstructionCache")),
create_heap: core::mem::transmute(export(ntdll, b"RtlCreateHeap")),
add_fault_handler: core::mem::transmute(
export(ntdll, b"RtlAddVectoredExceptionHandler")),
@@ -827,6 +842,7 @@ struct UserApi {
query_memory: windows_fn!(*mut c_void, *mut u8, u32, *mut u8, usize, *mut usize => i32),
yield_execution: windows_fn!( => i32),
wait_for_object: windows_fn!(*mut c_void, u8, *const i64 => i32),
flush_code: windows_fn!(*mut c_void, *mut u8, usize => i32),
set_event: windows_fn!(*mut c_void, *mut u32 => i32),
create_event: windows_fn!(*mut *mut c_void, u32, *mut c_void, u32, u8 => i32),
close: windows_fn!(*mut c_void => i32),
@@ -1169,55 +1185,77 @@ fn enumerate_ranges(found: &mut dyn FnMut(u64, u64, u32)) {
}
}
fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo)) {
let api = thread_list_api();
unsafe {
let snapshot = (api.create_snapshot)(SNAP_THREAD, 0);
if snapshot == INVALID_HANDLE {
return;
}
let ours = current_process_id();
let mut entry = [0u32; THREAD_ENTRY_WORDS];
entry[0] = (THREAD_ENTRY_WORDS * 4) as u32;
let mut more = (api.first)(snapshot, entry.as_mut_ptr() as *mut u8);
while more != 0 {
if entry[THREAD_ENTRY_OWNER] == ours {
let id = entry[THREAD_ENTRY_ID];
found(crate::kernel::ThreadInfo { id, cpu_state: registers_of(id) });
}
entry[0] = (THREAD_ENTRY_WORDS * 4) as u32;
more = (api.next)(snapshot, entry.as_mut_ptr() as *mut u8);
}
(api.close)(snapshot);
}
fn enumerate_threads(found: &mut dyn FnMut(crate::kernel::ThreadInfo), with_registers: bool) {
for_each_thread(&mut |id| {
found(crate::kernel::ThreadInfo {
id,
cpu_state: with_registers.then(|| registers_of(id)).flatten(),
});
true
});
}
// A thread cannot ask the system about itself: what comes back describes the asking, not the
// thread as a script would want to see it.
fn find_thread(id: u32) -> Option<crate::kernel::ThreadInfo> {
fn find_thread(id: u32, with_registers: bool) -> Option<crate::kernel::ThreadInfo> {
let mut found = false;
for_each_thread(&mut |seen| {
found = seen == id;
!found
});
found.then(|| crate::kernel::ThreadInfo {
id,
cpu_state: with_registers.then(|| registers_of(id)).flatten(),
})
}
fn for_each_thread(visit: &mut dyn FnMut(u32) -> bool) {
let api = thread_list_api();
let mut thread: *mut c_void = core::ptr::null_mut();
unsafe {
let snapshot = (api.create_snapshot)(SNAP_THREAD, 0);
if snapshot == INVALID_HANDLE {
for _ in 0..MAX_THREADS_PER_PROCESS {
let mut next: *mut c_void = core::ptr::null_mut();
let status = (api.next_thread)(CURRENT_PROCESS, thread,
THREAD_QUERY_LIMITED_INFORMATION, 0, 0, &mut next);
if !thread.is_null() {
(api.close)(thread);
}
if status < 0 {
return;
}
if next.is_null() {
return;
}
thread = next;
if let Some(id) = id_of_thread(api, thread) {
if !visit(id) {
(api.close)(thread);
return;
}
}
}
if !thread.is_null() {
(api.close)(thread);
}
}
}
const MAX_THREADS_PER_PROCESS: usize = 4096;
unsafe fn id_of_thread(api: &ThreadListApi, thread: *mut c_void) -> Option<u32> {
let mut basic = [0u8; THREAD_BASIC_INFORMATION_SIZE];
unsafe {
if (api.query_thread)(thread, THREAD_BASIC_INFORMATION, basic.as_mut_ptr(),
basic.len() as u32, core::ptr::null_mut()) < 0 {
return None;
}
let ours = current_process_id();
let mut found = false;
let mut entry = [0u32; THREAD_ENTRY_WORDS];
entry[0] = (THREAD_ENTRY_WORDS * 4) as u32;
let mut more = (api.first)(snapshot, entry.as_mut_ptr() as *mut u8);
while more != 0 && !found {
found = entry[THREAD_ENTRY_OWNER] == ours && entry[THREAD_ENTRY_ID] == id;
entry[0] = (THREAD_ENTRY_WORDS * 4) as u32;
more = (api.next)(snapshot, entry.as_mut_ptr() as *mut u8);
}
(api.close)(snapshot);
found.then(|| crate::kernel::ThreadInfo { id, cpu_state: registers_of(id) })
Some(basic.as_ptr().add(THREAD_BASIC_ID_OFFSET).cast::<usize>().read_unaligned() as u32)
}
}
@@ -1286,10 +1324,10 @@ fn thread_list_api() -> &'static ThreadListApi {
if (*core::ptr::addr_of!(THREAD_LIST_API)).is_none() {
let library = module_base(peb(), b"kernel32.dll");
THREAD_LIST_API = Some(ThreadListApi {
create_snapshot: core::mem::transmute(
export(library, b"CreateToolhelp32Snapshot")),
first: core::mem::transmute(export(library, b"Thread32First")),
next: core::mem::transmute(export(library, b"Thread32Next")),
next_thread: core::mem::transmute(
export(loader_library(), b"NtGetNextThread")),
query_thread: core::mem::transmute(
export(loader_library(), b"NtQueryInformationThread")),
open: core::mem::transmute(export(library, b"OpenThread")),
get_context: core::mem::transmute(
export(loader_library(), b"NtGetContextThread")),
@@ -1305,9 +1343,8 @@ fn thread_list_api() -> &'static ThreadListApi {
}
struct ThreadListApi {
create_snapshot: windows_fn!(u32, u32 => *mut c_void),
first: windows_fn!(*mut c_void, *mut u8 => i32),
next: windows_fn!(*mut c_void, *mut u8 => i32),
next_thread: windows_fn!(*mut c_void, *mut c_void, u32, u32, u32, *mut *mut c_void => i32),
query_thread: windows_fn!(*mut c_void, u32, *mut u8, u32, *mut u32 => i32),
open: windows_fn!(u32, i32, u32 => *mut c_void),
get_context: windows_fn!(*mut c_void, *mut u8 => i32),
set_context: windows_fn!(*mut c_void, *const u8 => i32),
@@ -1318,11 +1355,16 @@ struct ThreadListApi {
static mut THREAD_LIST_API: Option<ThreadListApi> = None;
const SNAP_THREAD: u32 = 0x4;
const INVALID_HANDLE: *mut c_void = usize::MAX as *mut c_void;
const THREAD_ENTRY_WORDS: usize = 7;
const THREAD_ENTRY_ID: usize = 2;
const THREAD_ENTRY_OWNER: usize = 3;
const THREAD_QUERY_LIMITED_INFORMATION: u32 = 0x0800;
const THREAD_BASIC_INFORMATION: u32 = 0;
#[cfg(target_pointer_width = "64")]
const THREAD_BASIC_INFORMATION_SIZE: usize = 0x30;
#[cfg(target_pointer_width = "64")]
const THREAD_BASIC_ID_OFFSET: usize = 0x18;
#[cfg(target_pointer_width = "32")]
const THREAD_BASIC_INFORMATION_SIZE: usize = 0x1c;
#[cfg(target_pointer_width = "32")]
const THREAD_BASIC_ID_OFFSET: usize = 0x0c;
fn wait(token: *const u8, timeout_us: Option<u64>, check: &mut dyn FnMut() -> bool) {
let slot = slot_for_token(token);
+79
View File
@@ -315,11 +315,29 @@ namespace Frida.BareboneTest {
h.run ();
});
GLib.Test.add_func ("/Barebone/WinNt/arm64-fires-a-timer-in-live-guest", () => {
var h = new Harness ((h) =>
winnt_arm64_fires_a_timer_in_live_guest.begin (h as Harness));
h.run ();
});
GLib.Test.add_func ("/Barebone/WinNt/arm64-enumerates-threads-in-live-guest", () => {
var h = new Harness ((h) =>
winnt_arm64_enumerates_threads_in_live_guest.begin (h as Harness));
h.run ();
});
GLib.Test.add_func ("/Barebone/WinNt/arm64-hooks-kernel-function-in-live-guest", () => {
var h = new Harness ((h) => winnt_arm64_hooks_kernel_function_in_live_guest.begin (h as Harness));
h.run ();
});
GLib.Test.add_func ("/Barebone/WinNt/arm64-injects-into-process-in-live-guest", () => {
var h = new SlowHarness ((h) =>
winnt_arm64_injects_into_process_in_live_guest.begin (h as SlowHarness));
h.run ();
});
GLib.Test.add_func ("/Barebone/WinNt/arm64-keeps-kernel-hook-in-live-guest", () => {
var h = new SlowHarness ((h) => winnt_arm64_keeps_kernel_hook_in_live_guest.begin (h as SlowHarness));
h.run ();
@@ -4452,6 +4470,21 @@ FAIL: %s
"send(1 + 1);", "\"payload\":2");
}
private async void winnt_arm64_fires_a_timer_in_live_guest (Harness h) {
yield run_script_in_live_guest (h, parallels_config_from_environment (h, "WINNT_ARM64"), """
const before = Date.now();
setTimeout(() => { send({ late: Date.now() - before >= 2000 }); }, 3000);
""", "\"late\":true");
}
private async void winnt_arm64_enumerates_threads_in_live_guest (Harness h) {
yield run_script_in_live_guest (h, parallels_config_from_environment (h, "WINNT_ARM64"), """
const threads = Process.enumerateThreads();
const sane = threads.length > 0 && threads.every(t => t.id !== 0);
send({ sane });
""", "\"sane\":true");
}
private async void winnt_arm64_agent_recovers_from_exception_in_live_guest (Harness h) {
yield run_script_in_live_guest (h, parallels_config_from_environment (h, "WINNT_ARM64"), """
let caught = 'no';
@@ -4464,6 +4497,52 @@ FAIL: %s
""", "\"caught\":\"yes\"");
}
private async void winnt_arm64_injects_into_process_in_live_guest (SlowHarness h) {
var config = parallels_config_from_environment (h, "WINNT_ARM64");
if (config == null)
return;
var manager = new DeviceManager ();
try {
var device = yield manager.add_barebone_device (config);
uint pid = yield find_program (device, "explorer.exe");
assert_true (pid != 0);
var session = yield device.attach (pid, null, null);
assert_nonnull (session);
var script = yield session.create_script ("""
recv('ping', () => { send(Process.id >>> 0); });
send('ready');
""", null, null);
var messages = new Gee.ArrayList<string> ();
script.message.connect ((json, data) => {
messages.add (json);
});
yield script.load (null);
while (messages.size < 1)
yield h.process_events ();
assert_true (messages[0].contains ("ready"));
script.post ("""{"type":"ping"}""");
while (messages.size < 2)
yield h.process_events ();
assert_true (messages[1].contains (pid.to_string ()));
} catch (GLib.Error e) {
printerr ("\nFAIL: %s\n\n", e.message);
assert_not_reached ();
} finally {
try {
yield manager.close (null);
} catch (GLib.Error e) {
}
}
h.done ();
}
private async void winnt_arm64_hooks_kernel_function_in_live_guest (Harness h) {
yield run_script_in_live_guest (h, parallels_config_from_environment (h, "WINNT_ARM64"), """
const kernel = Process.enumerateModules().find(m => m.name === 'ntoskrnl.exe');