mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
Provide bounded synchronous guest file IO on a synthetic drive
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
1 parent
dcf7122082
commit
6a60749939
7 files changed
+351
-14
No files matched your search
@@ -11,6 +11,8 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
|
||||
|
||||
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
@@ -970,22 +970,13 @@ impl SymbolDb {
|
||||
false,
|
||||
"CreateFile — stub returning INVALID_HANDLE_VALUE",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"CreateFileW",
|
||||
false,
|
||||
"CreateFileW — stub returning INVALID_HANDLE_VALUE",
|
||||
);
|
||||
self.win32_stub(m, "ReadFile", false, "ReadFile — stub returning FALSE");
|
||||
self.win32_stub(m, "WriteFile", false, "WriteFile — stub returning FALSE");
|
||||
for module in [m, "kernel32.dll"] {
|
||||
for symbol in ["CreateFileW", "ReadFile", "WriteFile", "GetFileSizeEx"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub");
|
||||
self.win32_stub(m, "GetFileSize", false, "GetFileSize — stub returning 0");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetFileSizeEx",
|
||||
false,
|
||||
"GetFileSizeEx — stub returning 0",
|
||||
);
|
||||
self.win32_stub(m, "SetFilePointerEx", false, "SetFilePointerEx — stub");
|
||||
self.win32_stub(
|
||||
m,
|
||||
|
||||
@@ -388,6 +388,21 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn check_write(&self, address: u64, size: usize) -> Result<(), MemoryError> {
|
||||
let region = self
|
||||
.regions
|
||||
.iter()
|
||||
.find(|region| region.contains(address, size))
|
||||
.ok_or(MemoryError::UnmappedAddress(address))?;
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
mod crt;
|
||||
mod events;
|
||||
mod files;
|
||||
mod heap;
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
@@ -117,6 +118,7 @@ impl Clock for SystemClock {
|
||||
|
||||
enum GuestObject {
|
||||
Thread(u32),
|
||||
File(files::OpenFile),
|
||||
Waitable {
|
||||
state: Arc<Mutex<events::Waitable>>,
|
||||
access: u32,
|
||||
@@ -128,6 +130,7 @@ struct ObjectState {
|
||||
priority: i32,
|
||||
last_handle: u64,
|
||||
handles: BTreeMap<u64, GuestObject>,
|
||||
files: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl ObjectState {
|
||||
@@ -367,6 +370,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
match thread.handles.get(&source) {
|
||||
Some(GuestObject::Thread(rights)) => (*rights, None),
|
||||
Some(GuestObject::Waitable { state, access }) => (*access, Some(Arc::clone(state))),
|
||||
Some(GuestObject::File(_)) => return s.fail(ERROR_NOT_SUPPORTED, 0),
|
||||
None => return s.fail(ERROR_INVALID_HANDLE, 0),
|
||||
}
|
||||
};
|
||||
@@ -394,6 +398,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
registry.set_status(KERNEL32, "DuplicateHandle", ServiceStatus::Partial);
|
||||
|
||||
events::register(registry, &state);
|
||||
files::register(registry, &state);
|
||||
crt::register(registry);
|
||||
crt::register_heap(registry);
|
||||
crt::register_errno(registry);
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded synthetic C: drive with no host filesystem mapping.
|
||||
|
||||
use super::{
|
||||
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS,
|
||||
ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState,
|
||||
};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::sync::Arc;
|
||||
|
||||
const FILE_API: &str = "api-ms-win-core-file-l1-1-0.dll";
|
||||
const INVALID_HANDLE: u64 = u64::MAX;
|
||||
const READ: u32 = 0x8000_0000;
|
||||
const WRITE: u32 = 0x4000_0000;
|
||||
const FILE_NOT_FOUND: u32 = 2;
|
||||
const FILE_EXISTS: u32 = 80;
|
||||
const ALREADY_EXISTS: u32 = 183;
|
||||
const INVALID_NAME: u32 = 123;
|
||||
const SHARING_VIOLATION: u32 = 32;
|
||||
const DISK_FULL: u32 = 112;
|
||||
const MAX_FILES: usize = 256;
|
||||
const MAX_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_TRANSFER: usize = 1024 * 1024;
|
||||
|
||||
pub(super) struct OpenFile {
|
||||
path: String,
|
||||
position: usize,
|
||||
access: u32,
|
||||
share: u32,
|
||||
}
|
||||
|
||||
fn flat_guest_name(memory: &GuestMemory, address: u64) -> Result<Option<String>, MemoryError> {
|
||||
if address == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
for index in 0..260 {
|
||||
let slot = address
|
||||
.checked_add(index * 2)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let unit = memory.read_u16(slot)?;
|
||||
if unit == 0 {
|
||||
let Ok(path) = String::from_utf16(&units) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = path.replace('/', "\\").to_ascii_lowercase();
|
||||
let name = path.strip_prefix("c:\\").unwrap_or(&path);
|
||||
let device = name.split('.').next().unwrap_or_default();
|
||||
if name.is_empty()
|
||||
|| name.ends_with([' ', '.'])
|
||||
|| name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || "\\/:*?\"<>|".contains(c))
|
||||
|| matches!(device, "con" | "prn" | "aux" | "nul")
|
||||
|| (device.len() == 4
|
||||
&& (device.starts_with("com") || device.starts_with("lpt"))
|
||||
&& device.as_bytes()[3].is_ascii_digit())
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
return Ok(Some(name.to_owned()));
|
||||
}
|
||||
units.push(unit);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn share_mask(access: u32) -> u32 {
|
||||
u32::from(access & READ != 0) | (u32::from(access & WRITE != 0) << 1)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let open = Arc::clone(state);
|
||||
registry.register(KERNEL32, "CreateFileW", move |args, _, memory| {
|
||||
let access = args.rdx as u32;
|
||||
let share = args.r8 as u32;
|
||||
let disposition = args.get(4, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let flags = args.get(5, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let template = args.get(6, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if args.r9 != 0
|
||||
|| template != 0
|
||||
|| !matches!(flags, 0 | 0x80)
|
||||
|| access & !(READ | WRITE) != 0
|
||||
|| share & !3 != 0
|
||||
{
|
||||
return open.fail(ERROR_NOT_SUPPORTED, INVALID_HANDLE);
|
||||
}
|
||||
if !(1..=5).contains(&disposition) {
|
||||
return open.fail(ERROR_INVALID_PARAMETER, INVALID_HANDLE);
|
||||
}
|
||||
if matches!(disposition, 2 | 5) && access & WRITE == 0 {
|
||||
return open.fail(ERROR_ACCESS_DENIED, INVALID_HANDLE);
|
||||
}
|
||||
let Some(path) = flat_guest_name(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return open.fail(INVALID_NAME, INVALID_HANDLE);
|
||||
};
|
||||
let mut objects = open.objects.lock().expect("guest object state");
|
||||
let exists = objects.files.contains_key(&path);
|
||||
if exists && disposition == 1 {
|
||||
return open.fail(FILE_EXISTS, INVALID_HANDLE);
|
||||
}
|
||||
if !exists && matches!(disposition, 3 | 5) {
|
||||
return open.fail(FILE_NOT_FOUND, INVALID_HANDLE);
|
||||
}
|
||||
for object in objects.handles.values() {
|
||||
if let GuestObject::File(file) = object
|
||||
&& file.path == path
|
||||
&& (share_mask(access) & !file.share != 0 || share_mask(file.access) & !share != 0)
|
||||
{
|
||||
return open.fail(SHARING_VIOLATION, INVALID_HANDLE);
|
||||
}
|
||||
}
|
||||
let Some(handle) = objects.next_handle() else {
|
||||
return open.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE);
|
||||
};
|
||||
if !exists {
|
||||
if objects.files.len() >= MAX_FILES {
|
||||
return open.fail(DISK_FULL, INVALID_HANDLE);
|
||||
}
|
||||
objects.files.insert(path.clone(), Vec::new());
|
||||
} else if matches!(disposition, 2 | 5) {
|
||||
*objects.files.get_mut(&path).expect("existing file") = Vec::new();
|
||||
}
|
||||
if matches!(disposition, 2 | 4) {
|
||||
open.fail(if exists { ALREADY_EXISTS } else { 0 }, 0)?;
|
||||
}
|
||||
objects.insert_handle(
|
||||
handle,
|
||||
GuestObject::File(OpenFile {
|
||||
path,
|
||||
position: 0,
|
||||
access,
|
||||
share,
|
||||
}),
|
||||
);
|
||||
Ok(handle)
|
||||
});
|
||||
|
||||
let size = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetFileSizeEx", move |args, _, memory| {
|
||||
let objects = size.objects.lock().expect("guest object state");
|
||||
let Some(GuestObject::File(file)) = objects.handles.get(&args.rcx) else {
|
||||
return size.fail(ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let bytes = objects
|
||||
.files
|
||||
.get(&file.path)
|
||||
.expect("open file exists")
|
||||
.len();
|
||||
if args.rdx == 0 || memory.write_u64(args.rdx, bytes as u64).is_err() {
|
||||
return size.fail(ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for (symbol, writing) in [("ReadFile", false), ("WriteFile", true)] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, _, memory| {
|
||||
if args.get(4, memory).map_err(ExitReason::MemoryFault)? != 0 {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let count = args.r8 as u32 as usize;
|
||||
if count > MAX_TRANSFER {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut objects = state.objects.lock().expect("guest object state");
|
||||
let super::ObjectState { handles, files, .. } = &mut *objects;
|
||||
let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else {
|
||||
return state.fail(ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let required = if writing { WRITE } else { READ };
|
||||
if file.access & required == 0 {
|
||||
return state.fail(ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
if args.r9 == 0 || memory.check_write(args.r9, 4).is_err() {
|
||||
return state.fail(ERROR_NOACCESS, 0);
|
||||
}
|
||||
|
||||
let used = if writing {
|
||||
files.values().map(Vec::len).sum::<usize>()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let data = files.get_mut(&file.path).expect("open file exists");
|
||||
let position = file.position;
|
||||
let transferred = if writing {
|
||||
if count == 0 {
|
||||
0
|
||||
} else {
|
||||
let end = position + count;
|
||||
let growth = end.saturating_sub(data.len());
|
||||
if growth > MAX_BYTES - used {
|
||||
return state.fail(DISK_FULL, 0);
|
||||
}
|
||||
let mut input = vec![0; count];
|
||||
if args.rdx == 0 || memory.read_bytes(args.rdx, &mut input).is_err() {
|
||||
return state.fail(ERROR_NOACCESS, 0);
|
||||
}
|
||||
if growth != 0 {
|
||||
data.try_reserve_exact(growth)
|
||||
.map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?;
|
||||
data.resize(end, 0);
|
||||
}
|
||||
data[position..end].copy_from_slice(&input);
|
||||
count
|
||||
}
|
||||
} else {
|
||||
let start = position.min(data.len());
|
||||
let transferred = count.min(data.len() - start);
|
||||
if transferred != 0
|
||||
&& (args.rdx == 0
|
||||
|| memory
|
||||
.write_bytes(args.rdx, &data[start..start + transferred])
|
||||
.is_err())
|
||||
{
|
||||
return state.fail(ERROR_NOACCESS, 0);
|
||||
}
|
||||
transferred
|
||||
};
|
||||
memory
|
||||
.write_u32(args.r9, transferred as u32)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
file.position += transferred;
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
|
||||
for symbol in ["CreateFileW", "GetFileSizeEx", "ReadFile", "WriteFile"] {
|
||||
registry.alias(FILE_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -1121,6 +1121,85 @@ fn test_guest_crt_string_length_through_iat() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_guest_synthetic_file_io_through_iat() {
|
||||
const IMAGE: u64 = 0x140000000;
|
||||
const MODULE: &str = "api-ms-win-core-file-l1-1-0.dll";
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let open = |name: &str, access: u64, disposition: u64| {
|
||||
let mut code = vec![0x48, 0x83, 0xec, 0x48];
|
||||
for (register, value) in [
|
||||
([0x48, 0xb9], IMAGE + 0x1080),
|
||||
([0x48, 0xba], access),
|
||||
([0x49, 0xb8], 0),
|
||||
([0x49, 0xb9], 0),
|
||||
] {
|
||||
code.extend_from_slice(®ister);
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
for (offset, value) in [(0x20, disposition), (0x28, 0x80), (0x30, 0)] {
|
||||
code.extend_from_slice(&[0x48, 0xb8]);
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code.extend_from_slice(&[0x48, 0x89, 0x44, 0x24, offset]);
|
||||
}
|
||||
append_import_call(&mut code, 0x2060);
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]);
|
||||
code.resize(0x80, 0);
|
||||
code.extend(name.encode_utf16().chain([0]).flat_map(u16::to_le_bytes));
|
||||
let bytes = TestPeBuilder::new(IMAGE, 0x1000)
|
||||
.add_import(MODULE, "CreateFileW")
|
||||
.code(&code)
|
||||
.build();
|
||||
let mut imports = ImportRegistry::new();
|
||||
register_standard_services(&mut imports, state.clone());
|
||||
let result = run_synthetic_startup(
|
||||
&bytes,
|
||||
StartupLayout {
|
||||
image_base: IMAGE,
|
||||
stack_top: PROCESS_FIXTURE_STACK_TOP,
|
||||
tls_base: 0x300000000,
|
||||
},
|
||||
imports,
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
|
||||
result.execution.final_state.get(Register::Rax)
|
||||
};
|
||||
let call = |symbol, args: &[u64]| call_service_fixture(&state, "kernel32.dll", symbol, args);
|
||||
let output = PROCESS_FIXTURE_OUTPUT;
|
||||
assert_eq!(open("C:/../outside", 0x4000_0000, 2), u64::MAX);
|
||||
let writer = open("C:/Sample.dat", 0x4000_0000, 2);
|
||||
assert_ne!(writer, u64::MAX);
|
||||
assert_eq!(open("sample.dat", 0x8000_0000, 3), u64::MAX);
|
||||
let wrote = call("WriteFile", &[writer, output, 4, output + 8, 0]);
|
||||
assert_eq!(wrote.execution.final_state.get(Register::Rax), 1);
|
||||
assert_eq!(wrote.image.memory.read_u32(output + 8).unwrap(), 4);
|
||||
assert_eq!(
|
||||
call("CloseHandle", &[writer])
|
||||
.execution
|
||||
.final_state
|
||||
.get(Register::Rax),
|
||||
1
|
||||
);
|
||||
|
||||
let reader = open("sample.DAT", 0x8000_0000, 3);
|
||||
assert_ne!(reader, u64::MAX);
|
||||
let size = call("GetFileSizeEx", &[reader, output]);
|
||||
assert_eq!(size.execution.final_state.get(Register::Rax), 1);
|
||||
assert_eq!(size.image.memory.read_u64(output).unwrap(), 4);
|
||||
let read = call("ReadFile", &[reader, output + 8, 8, output, 0]);
|
||||
assert_eq!(read.execution.final_state.get(Register::Rax), 1);
|
||||
assert_eq!(read.image.memory.read_u32(output).unwrap(), 4);
|
||||
assert_eq!(
|
||||
read.image.memory.read_u64(output + 8).unwrap(),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
let eof = call("ReadFile", &[reader, output + 8, 8, output, 0]);
|
||||
assert_eq!(eof.execution.final_state.get(Register::Rax), 1);
|
||||
assert_eq!(eof.image.memory.read_u32(output).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_guest_semaphore_counts_through_iat() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
|
||||
@@ -192,6 +192,16 @@ clamps the result and sets ERANGE. Scans have a 1 MiB input budget. The long-lon
|
||||
Microsoft's _strtoi64, _strtoui64, _wcstoi64, and _wcstoui64 apply the
|
||||
same rules with 64-bit results.
|
||||
|
||||
### Synthetic guest files
|
||||
|
||||
The runtime exposes an in-memory C: drive through CreateFileW, ReadFile,
|
||||
WriteFile, GetFileSizeEx, and CloseHandle. It supports root-level UTF-16
|
||||
names, ASCII case folding, synchronous I/O, per-handle positions, and
|
||||
read/write sharing. Paths cannot access host files. The drive supports
|
||||
256 files and 16 MiB of data, with a 1 MiB limit per transfer.
|
||||
Directories, persistence, asynchronous I/O, and file handle duplication
|
||||
remain outside this subset.
|
||||
|
||||
### Event and semaphore signaling
|
||||
|
||||
The synthetic runtime supports unnamed manual-reset and auto-reset events
|
||||
|
||||
Reference in new issue
Block a user