Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions litebox_shim_windows/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1093,6 +1093,32 @@ impl<Platform: ShimPlatform, FS: ShimFS> Task<Platform, FS> {
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtDeviceIoControlFile {
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
} => {
let status = self.sys_nt_device_io_control_file(
file_handle,
event,
apc_routine,
apc_context,
io_status_block,
io_control_code,
input_buffer,
input_buffer_length,
output_buffer,
output_buffer_length,
);
(status, ContinueOperation::Resume)
}
SyscallRequest::NtApphelpCacheControl {
service_class,
service_data,
Expand Down
36 changes: 17 additions & 19 deletions litebox_shim_windows/src/loader/pe.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,7 +35,7 @@ use crate::syscalls::process::{INITIAL_PROCESS_ID, INITIAL_THREAD_ID};
use crate::{MutPtr, ShimFS};

const NTDLL_WRITABLE_SECTIONS: &[&[u8]] = &[b".mrdata"];
const NTDLL_PATHS: &[&str] = &["/Windows/System32/ntdll.dll", "/windows/system32/ntdll.dll"];
const NTDLL_PATH: &str = "/Windows/System32/ntdll.dll";
const RUNTIME_FUNCTION_ENTRY_SIZE: usize = 12;
const ZERO_CHUNK: [u8; PAGE_SIZE] = [0; PAGE_SIZE];
const FILE_CHUNK_BYTES: usize = 64 * 1024;
Expand DownExpand Up@@ -1038,26 +1038,24 @@ fn load_ntdll<Platform: crate::ShimPlatform, FS: crate::ShimFS>(
fs: Arc<FS>,
page_manager: &crate::WindowsPageManager<Platform>,
) -> Result<Option<LoadedNtDll>, WindowsLoadError> {
for path in NTDLL_PATHS {
match load_image_with_writable_sections(
fs.clone(),
path,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = path; "Loaded guest ntdll.dll");
return Ok(Some(LoadedNtDll { image, exports }));
}
Err(error) if is_missing_file_error(&error) => {}
Err(error) => return Err(error),
match load_image_with_writable_sections(
fs,
NTDLL_PATH,
platform,
page_manager,
NTDLL_WRITABLE_SECTIONS,
) {
Ok(image) => {
let exports = ntdll_exports::<Platform>(&image)?;
litebox_util_log::debug!(path:% = NTDLL_PATH; "Loaded guest ntdll.dll");
Ok(Some(LoadedNtDll { image, exports }))
}
Err(error) if is_missing_file_error(&error) => {
litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}
Err(error) => Err(error),
}

litebox_util_log::debug!("Guest ntdll.dll was not found in the initial filesystem");
Ok(None)
}

fn load_image<Platform: crate::ShimPlatform, FS: ShimFS>(
Expand Down
306 changes: 306 additions & 0 deletions litebox_shim_windows/src/syscalls/condrv.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows console driver support.

use core::mem::size_of;

use int_enum::IntEnum;
use litebox::platform::{RawConstPointer as _, RawMutPointer as _};
use litebox_common_windows::nt_status::NtStatus;
use zerocopy::{FromBytes, Immutable, IntoBytes};

use crate::nt_types::IoStatusBlock;
use crate::{ConstPtr, MutPtr};

const FILE_DEVICE_CONSOLE: u32 = 0x50;
const CD_SERVER_EA_NAME: &[u8] = b"server";

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
pub(crate) enum CondrvObject {
Input = 0,
Output = 1,
Server = 2,
Reference = 3,
Connect = 4,
}

impl CondrvObject {
pub(crate) fn from_device_name(name: &str) -> Result<Self, NtStatus> {
match Self::from_component(name) {
Some(object @ (Self::Input | Self::Output | Self::Server)) => Ok(object),
Some(Self::Reference) => Err(NtStatus::INVALID_HANDLE),
Some(Self::Connect) => Err(NtStatus::OBJECT_TYPE_MISMATCH),
None => Err(NtStatus::OBJECT_NAME_NOT_FOUND),
}
}

fn from_component(name: &str) -> Option<Self> {
if name.eq_ignore_ascii_case("Input") {
Some(Self::Input)
} else if name.eq_ignore_ascii_case("Output") {
Some(Self::Output)
} else if name.eq_ignore_ascii_case("Server") {
Some(Self::Server)
} else if name.eq_ignore_ascii_case("Reference") {
Some(Self::Reference)
} else if name.eq_ignore_ascii_case("Connect") {
Some(Self::Connect)
} else {
None
}
}

pub(crate) fn relative_child(self, name: &str) -> Result<Self, NtStatus> {
let name = name.strip_prefix('\\').ok_or(NtStatus::NOT_FOUND)?;
let child = Self::from_component(name).ok_or(NtStatus::NOT_FOUND)?;

match (self, child) {
(Self::Server, Self::Server | Self::Reference)
| (Self::Reference, Self::Server | Self::Connect | Self::Input | Self::Output)
| (Self::Input | Self::Output, Self::Server | Self::Input | Self::Output) => Ok(child),
(Self::Server, Self::Input | Self::Output) => Err(NtStatus::INVALID_DEVICE_STATE),
(Self::Reference | Self::Input | Self::Output, Self::Reference) => {
Err(NtStatus::OBJECT_TYPE_MISMATCH)
}
(Self::Server | Self::Input | Self::Output, Self::Connect) | (Self::Connect, _) => {
Err(NtStatus::INVALID_HANDLE)
}
}
}

pub(crate) fn handle_path(self) -> &'static str {
match self {
Self::Input => "/dev/stdin",
Self::Output => "/dev/stdout",
Self::Server => r"\Device\ConDrv\Server",
Self::Reference => r"\Device\ConDrv\Reference",
Self::Connect => r"\Device\ConDrv\Connect",
}
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum IoControlMethod {
Buffered = 0,
InDirect = 1,
OutDirect = 2,
Neither = 3,
}

bitflags::bitflags! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct IoControlAccess: u32 {
const ANY = 0;
const READ = 1;
const WRITE = 2;
const _ = !0;
}
}

#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, IntEnum, PartialEq)]
enum ConsoleIoControlFunction {
LaunchServer = 13,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes)]
struct FileFullEaInformation {
next_entry_offset: u32,
flags: u8,
ea_name_length: u8,
ea_value_length: u16,
}

#[cfg(test)]
pub(crate) fn ea_buffer(name: &[u8], value_length: usize) -> alloc::vec::Vec<u8> {
let header = FileFullEaInformation {
next_entry_offset: 0,
flags: 0,
ea_name_length: u8::try_from(name.len()).unwrap(),
ea_value_length: u16::try_from(value_length).unwrap(),
};
let mut buffer = alloc::vec::Vec::new();
buffer.extend_from_slice(header.as_bytes());
buffer.extend_from_slice(name);
buffer.push(0);
buffer.resize(buffer.len() + value_length, 0);
buffer
}

pub(crate) fn validate_connect_server_ea<Platform: crate::ShimPlatform>(
ea_buffer: Option<ConstPtr<Platform, u8>>,
ea_length: u32,
) -> Result<(), NtStatus> {
let Some(ea_buffer) = ea_buffer else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let ea_length = ea_length as usize;
let Some(entry) = ConstPtr::<Platform, FileFullEaInformation>::from_usize(ea_buffer.as_usize())
.read_at_offset(0)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};

let name_offset = size_of::<FileFullEaInformation>();
let name_length = entry.ea_name_length as usize;
let value_length = entry.ea_value_length as usize;
let value_offset = name_offset
.checked_add(name_length)
.and_then(|offset| offset.checked_add(1))
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
let entry_length = value_offset
.checked_add(value_length)
.ok_or(NtStatus::EAS_NOT_SUPPORTED)?;
if entry_length > ea_length {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(name_address) = ea_buffer.as_usize().checked_add(name_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
let Some(name_with_nul) =
ConstPtr::<Platform, u8>::from_usize(name_address).to_owned_slice(name_length + 1)
else {
return Err(NtStatus::ACCESS_VIOLATION);
};
let Some((&0, name)) = name_with_nul.split_last() else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
if !name.eq_ignore_ascii_case(CD_SERVER_EA_NAME) {
return Err(NtStatus::EAS_NOT_SUPPORTED);
}

let Some(value_address) = ea_buffer.as_usize().checked_add(value_offset) else {
return Err(NtStatus::EAS_NOT_SUPPORTED);
};
// The ConDrv "server" EA value format is undocumented; probe the declared payload without
// interpreting it until its semantics are understood.
if ConstPtr::<Platform, u8>::from_usize(value_address)
.to_owned_slice(value_length)
.is_none()
{
return Err(NtStatus::ACCESS_VIOLATION);
}

Ok(())
}

pub(crate) fn handle_ioctl<Platform: crate::ShimPlatform>(
condrv_object: CondrvObject,
io_status_block: MutPtr<Platform, IoStatusBlock>,
io_control_code: u32,
input_buffer: Option<ConstPtr<Platform, u8>>,
input_buffer_length: u32,
output_buffer: Option<MutPtr<Platform, u8>>,
output_buffer_length: u32,
) -> NtStatus {
let device_type = io_control_code >> 16;
let access = IoControlAccess::from_bits_retain((io_control_code >> 14) & 0x3);
let function = (io_control_code >> 2) & 0xfff;
let method = IoControlMethod::try_from(io_control_code & 0x3);

if device_type != FILE_DEVICE_CONSOLE || method != Ok(IoControlMethod::Neither) {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL shape"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
}

let Ok(function) = ConsoleIoControlFunction::try_from(function) else {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL function"
);
return complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0);
};

match (condrv_object, function) {
(CondrvObject::Server, ConsoleIoControlFunction::LaunchServer)
if access.is_empty()
&& input_buffer.is_some()
&& input_buffer_length != 0
&& output_buffer.is_none()
&& output_buffer_length == 0 =>
{
if input_buffer
.and_then(|input_buffer| input_buffer.read_at_offset(0))
.is_none()
{
return complete_ioctl::<Platform>(io_status_block, NtStatus::ACCESS_VIOLATION, 0);
}
complete_ioctl::<Platform>(io_status_block, NtStatus::SUCCESS, 0)
}
_ => {
litebox_util_log::debug!(
condrv_object:? = condrv_object,
function:? = function,
io_control_code:% = format_args!("{io_control_code:#x}");
"Unsupported ConDrv IOCTL for object"
);
complete_ioctl::<Platform>(io_status_block, NtStatus::NOT_SUPPORTED, 0)
}
}
}

pub(crate) fn complete_ioctl<Platform: crate::ShimPlatform>(
io_status_block: MutPtr<Platform, IoStatusBlock>,
status: NtStatus,
information: usize,
) -> NtStatus {
if io_status_block
.write_at_offset(0, IoStatusBlock::new(status, information))
.is_none()
{
return NtStatus::ACCESS_VIOLATION;
}
status
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn relative_children_match_host_parse_contexts() {
use CondrvObject::{Connect, Input, Output, Reference, Server};

for (parent, name, expected) in [
(Server, r"\Server", Ok(Server)),
(Server, r"\Reference", Ok(Reference)),
(Server, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Server, r"\Input", Err(NtStatus::INVALID_DEVICE_STATE)),
(Server, r"\Output", Err(NtStatus::INVALID_DEVICE_STATE)),
(Reference, r"\Server", Ok(Server)),
(Reference, r"\Connect", Ok(Connect)),
(Reference, r"\Input", Ok(Input)),
(Reference, r"\Output", Ok(Output)),
(
Reference,
r"\Reference",
Err(NtStatus::OBJECT_TYPE_MISMATCH),
),
(Input, r"\Server", Ok(Server)),
(Input, r"\Input", Ok(Input)),
(Input, r"\Output", Ok(Output)),
(Input, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Input, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
(Output, r"\Server", Ok(Server)),
(Output, r"\Input", Ok(Input)),
(Output, r"\Output", Ok(Output)),
(Output, r"\Reference", Err(NtStatus::OBJECT_TYPE_MISMATCH)),
(Output, r"\Connect", Err(NtStatus::INVALID_HANDLE)),
] {
assert_eq!(parent.relative_child(name), expected, "{parent:?} + {name}");
}

assert_eq!(Server.relative_child("Reference"), Err(NtStatus::NOT_FOUND));
assert_eq!(Server.relative_child(r"\Missing"), Err(NtStatus::NOT_FOUND));
}
}
Loading