Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b76bb7a0d2
|
||
|
|
c18c427af5
|
||
|
|
06123b5b7b
|
||
|
|
f30a4690df
|
||
|
|
b906ed044d
|
||
|
|
3c26590c7c
|
||
|
|
a22c9cd0ce
|
||
|
|
afc6724be1
|
||
|
|
6ba282fd87
|
||
|
|
a92b59c808
|
||
|
|
52b81d900c
|
||
|
|
868ad9c191
|
||
|
|
a62b11df3f
|
||
|
|
b09fdc5fbf
|
||
|
|
98689b682a
|
||
|
|
8d4c796cce
|
||
|
|
637160d3ea
|
||
|
|
30b22107a1
|
||
|
|
334c4761a2
|
||
|
|
5d795ec982
|
||
|
|
bd90e08a87
|
||
|
|
9eb953f84c
|
||
|
|
93bb675333
|
||
|
|
99db8bcd72
|
||
|
|
4477c81b81
|
||
|
|
a9a1c4870c
|
||
|
|
432ec8adea
|
||
|
|
f2da8b5328
|
||
|
|
bd51e3e2e2
|
+11
-8
@@ -1,23 +1,26 @@
|
||||
[package]
|
||||
name = "haxor"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "memory hacking library"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
readme = "README.md"
|
||||
repository = "https://codeberg.org/futile/haxor"
|
||||
license = "Apache-2.0"
|
||||
description = "memory hacking library"
|
||||
repository = "https://github.com/elituf/haxor"
|
||||
keywords = ["memory", "game", "hacking", "process"]
|
||||
|
||||
[dependencies]
|
||||
derive_more = { version = "1.0.0", features = ["display"] }
|
||||
log = "0.4.22"
|
||||
thiserror = "2.0.9"
|
||||
derive_more = { version = "2", features = ["debug", "display"] }
|
||||
log = "0.4"
|
||||
thiserror = "2"
|
||||
|
||||
[dependencies.windows]
|
||||
version = "0.58.0"
|
||||
version = "0.62"
|
||||
features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_Diagnostics_ToolHelp",
|
||||
"Win32_System_Diagnostics_Debug",
|
||||
]
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
## haxor
|
||||
memory hacking library
|
||||
windows external memory hacking library
|
||||
|
||||
## using
|
||||
```rust
|
||||
let proc = Process::from("notepad.exe")?;
|
||||
let proc = Process::find("notepad.exe")?;
|
||||
let some_val = proc.read_mem::<i32>(0xDEADBEEF)?;
|
||||
```
|
||||
|
||||
```rust
|
||||
let proc = Process::from(1337)?;
|
||||
let proc = Process::find(1337)?;
|
||||
let chain: Vec<usize> = vec![proc.base_address, 0x4B1D, 0x8, 0x12];
|
||||
let some_addr: usize = proc.resolve_pointer_chain(&chain)?;
|
||||
let some_val = proc.read_mem::<u8>(some_addr)?;
|
||||
|
||||
+6
-3
@@ -9,12 +9,15 @@ pub enum Error {
|
||||
/// there was a failure when reading or writing the process's memory
|
||||
#[error("failed to access process memory")]
|
||||
AccessMemoryError(String),
|
||||
/// there was a failure in building the Process or Module struct
|
||||
#[error("failed to create process")]
|
||||
CreateProcessError(String),
|
||||
/// there was a failure in creating a snapshot of processes or modules
|
||||
#[error("failed to create snapshot")]
|
||||
CreateSnapshotError(String),
|
||||
/// there was a failure in building the Process or Module struct
|
||||
#[error("failed to get process/module")]
|
||||
ProcessError(String),
|
||||
/// there was a failure in resolving a pointer chain
|
||||
#[error("failed to resolve pointer chain")]
|
||||
ResolvePointerChainError(String),
|
||||
/// there was a failure in conversion between integers
|
||||
#[error("failed to convert integer")]
|
||||
ConvertIntegerError(#[from] std::num::TryFromIntError),
|
||||
|
||||
@@ -4,5 +4,7 @@
|
||||
mod error;
|
||||
/// types and methods to ease the r/w of a process's memory
|
||||
pub mod process;
|
||||
mod sys;
|
||||
mod tests;
|
||||
|
||||
pub use error::Error;
|
||||
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
use crate::{
|
||||
Error,
|
||||
sys::{handle::Handle, memory, snapshot},
|
||||
};
|
||||
use derive_more::{Debug, derive::Display};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
/// a process running on the system
|
||||
pub struct Process {
|
||||
/// the process name (szExeFile)
|
||||
pub name: String,
|
||||
/// the process id (th32ProcessID)
|
||||
pub id: u32,
|
||||
/// the base address of the module with the name `name` (modBaseAddr)
|
||||
#[debug("0x{base_address:X}")]
|
||||
pub base_address: usize,
|
||||
/// the process handle (HANDLE)
|
||||
pub handle: Handle,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
/// initialize a `Process` from a pid or a process name
|
||||
///
|
||||
/// ### examples
|
||||
///
|
||||
/// ```rust
|
||||
/// let proc = Process::find(1337)?;
|
||||
/// ```
|
||||
///
|
||||
/// ```rust
|
||||
/// let proc = Process::find("notepad.exe")?;
|
||||
/// ```
|
||||
pub fn find<T: Into<Identifier>>(identifier: T) -> Result<Self, Error> {
|
||||
let identifier = identifier.into();
|
||||
let snapshot = snapshot::ProcessSnapshot::get_processes()?
|
||||
.into_iter()
|
||||
.find(|snapshot| match identifier {
|
||||
Identifier::Pid(pid) => snapshot.id == pid,
|
||||
Identifier::Name(ref name) => snapshot.name == *name,
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::ProcessError(format!(
|
||||
"failed to find a process with identifier `{identifier}`",
|
||||
))
|
||||
})?;
|
||||
let mut process = Self {
|
||||
name: snapshot.name,
|
||||
id: snapshot.id,
|
||||
base_address: 0,
|
||||
handle: Handle::from_pid(snapshot.id)?,
|
||||
};
|
||||
process.base_address = process.module(&process.name)?.base_address;
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
/// get a `Module` of a `Process` by name (case-insensitive)
|
||||
pub fn module<T: AsRef<str>>(&self, name: T) -> Result<Module, Error> {
|
||||
let name = name.as_ref();
|
||||
let Some(snapshot) = snapshot::ModuleSnapshot::get_modules(self.id)?
|
||||
.into_iter()
|
||||
.find(|snapshot| name.eq_ignore_ascii_case(&snapshot.name))
|
||||
else {
|
||||
return Err(Error::ProcessError(format!(
|
||||
"failed to find a module with identifier `{name}`",
|
||||
)));
|
||||
};
|
||||
let module = Module {
|
||||
process_id: self.id,
|
||||
name: snapshot.name,
|
||||
path: snapshot.path,
|
||||
base_address: snapshot.base_address,
|
||||
base_size: snapshot.base_size,
|
||||
};
|
||||
Ok(module)
|
||||
}
|
||||
|
||||
/// get all `Module`s of a `Process`
|
||||
pub fn modules(&self) -> Result<Vec<Module>, Error> {
|
||||
Ok(snapshot::ModuleSnapshot::get_modules(self.id)?
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|snapshot| Module {
|
||||
process_id: self.id,
|
||||
name: snapshot.name,
|
||||
path: snapshot.path,
|
||||
base_address: snapshot.base_address,
|
||||
base_size: snapshot.base_size,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// follow a pointer chain to the end and return an address
|
||||
pub fn resolve_pointer_chain<T: AsRef<[usize]>>(&self, chain: T) -> Result<usize, Error> {
|
||||
let chain = chain.as_ref();
|
||||
if chain.is_empty() {
|
||||
return Err(Error::ResolvePointerChainError("chain was empty".into()));
|
||||
}
|
||||
if chain.len() == 1 {
|
||||
return Ok(chain[0]);
|
||||
}
|
||||
let mut address = chain[0];
|
||||
for &offset in &chain[1..(chain.len() - 1)] {
|
||||
address += offset;
|
||||
address = self.read_mem(address)?;
|
||||
}
|
||||
Ok(address + chain.last().expect("chain should have a last element"))
|
||||
}
|
||||
|
||||
/// read a given `address` of process's memory
|
||||
pub fn read_mem<T: Default>(&self, address: usize) -> Result<T, Error> {
|
||||
let mut value = Default::default();
|
||||
memory::read(&self.handle, address, &mut value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// write a `value` at given `address` of process's memory
|
||||
pub fn write_mem<T>(&self, address: usize, mut value: T) -> Result<(), Error> {
|
||||
memory::write(&self.handle, address, &mut value)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
/// a module running within a process
|
||||
pub struct Module {
|
||||
/// the parent process id (th32ProcessID)
|
||||
pub process_id: u32,
|
||||
/// the module name (szModule)
|
||||
pub name: String,
|
||||
/// the module executable path (szExePath)
|
||||
pub path: String,
|
||||
/// the module base address (modBaseAddr)
|
||||
#[debug("0x{base_address:X}")]
|
||||
pub base_address: usize,
|
||||
/// the module base size (modBaseSize)
|
||||
#[debug("0x{base_size:X}")]
|
||||
pub base_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Display)]
|
||||
/// an identifier for searching for a process
|
||||
pub enum Identifier {
|
||||
/// process id to search for
|
||||
Pid(u32),
|
||||
/// process name to search for
|
||||
Name(String),
|
||||
}
|
||||
|
||||
impl From<u32> for Identifier {
|
||||
fn from(value: u32) -> Self {
|
||||
Self::Pid(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Identifier {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::Name(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Identifier {
|
||||
fn from(value: String) -> Self {
|
||||
Self::Name(value)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use std::ops::Deref;
|
||||
|
||||
use windows::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
|
||||
use windows::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_ALL_ACCESS, PROCESS_VM_READ, PROCESS_VM_WRITE,
|
||||
};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Handle(pub HANDLE);
|
||||
|
||||
unsafe impl Send for Handle {}
|
||||
unsafe impl Sync for Handle {}
|
||||
|
||||
impl Deref for Handle {
|
||||
type Target = HANDLE;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
if let Err(why) = CloseHandle(**self) {
|
||||
log::error!("failed to close handle: {why}");
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
pub fn from_pid(pid: u32) -> Result<Self, crate::Error> {
|
||||
let handle = unsafe {
|
||||
OpenProcess(PROCESS_ALL_ACCESS, false, pid)
|
||||
.or_else(|_| OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid))
|
||||
.map_err(|why| {
|
||||
crate::Error::ObtainHandleError(format!(
|
||||
"failed to open process with needed access: {why}",
|
||||
))
|
||||
})?
|
||||
};
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return Err(crate::Error::ObtainHandleError(
|
||||
"failed to get a valid handle".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(Self(handle))
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
#![allow(clippy::module_inception)]
|
||||
|
||||
mod handle;
|
||||
mod memory;
|
||||
mod module;
|
||||
mod process;
|
||||
mod snapshot;
|
||||
|
||||
pub use module::Module;
|
||||
pub use process::{Identifier, Process};
|
||||
@@ -1,14 +0,0 @@
|
||||
#[derive(Debug, Default)]
|
||||
/// a module running within a process
|
||||
pub struct Module {
|
||||
/// the parent process id (th32ProcessID)
|
||||
pub process_id: u32,
|
||||
/// the module name (szModule)
|
||||
pub name: String,
|
||||
/// the module executable path (szExePath)
|
||||
pub path: String,
|
||||
/// the module base address (modBaseAddr)
|
||||
pub base_address: usize,
|
||||
/// the module base size (modBaseSize)
|
||||
pub base_size: usize,
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
use super::{handle::Handle, memory, module::Module, snapshot};
|
||||
|
||||
use derive_more::derive::Display;
|
||||
|
||||
#[derive(Display)]
|
||||
/// an identifier for searching for a process
|
||||
pub enum Identifier {
|
||||
/// the process id
|
||||
Pid(u32),
|
||||
/// the process name
|
||||
Name(String),
|
||||
}
|
||||
|
||||
impl From<u32> for Identifier {
|
||||
fn from(value: u32) -> Self {
|
||||
Self::Pid(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for Identifier {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::Name(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
/// a process running on the system
|
||||
pub struct Process {
|
||||
/// the process name (szExeFile)
|
||||
pub name: String,
|
||||
/// the process id (th32ProcessID)
|
||||
pub id: u32,
|
||||
/// the base address of the module with the same name as `name` (modBaseAddr)
|
||||
pub base_address: usize,
|
||||
/// the process handle (HANDLE)
|
||||
pub handle: Handle,
|
||||
}
|
||||
|
||||
unsafe impl Send for Process {}
|
||||
unsafe impl Sync for Process {}
|
||||
|
||||
impl Process {
|
||||
/// initialize a `Process` from a pid or a process name
|
||||
pub fn from<T: Into<Identifier>>(identifier: T) -> Result<Self, crate::Error> {
|
||||
let identifier = identifier.into();
|
||||
let Some(snapshot) = (match identifier {
|
||||
Identifier::Pid(pid) => snapshot::ProcessSnapshot::get_processes()?
|
||||
.into_iter()
|
||||
.find(|snapshot| snapshot.id == pid),
|
||||
Identifier::Name(ref name) => snapshot::ProcessSnapshot::get_processes()?
|
||||
.into_iter()
|
||||
.find(|snapshot| snapshot.name == *name),
|
||||
}) else {
|
||||
return Err(crate::Error::CreateProcessError(format!(
|
||||
"failed to find a process with identifier `{identifier}`",
|
||||
)));
|
||||
};
|
||||
let mut process = Self {
|
||||
name: snapshot.name,
|
||||
id: snapshot.id,
|
||||
base_address: 0,
|
||||
handle: Handle::from_pid(snapshot.id)?,
|
||||
};
|
||||
process.base_address = process.module(&process.name)?.base_address;
|
||||
Ok(process)
|
||||
}
|
||||
|
||||
/// get the `Module` of a `Process` by name
|
||||
pub fn module(&self, name: &str) -> Result<Module, crate::Error> {
|
||||
let Some(snapshot) = snapshot::ModuleSnapshot::get_modules(self.id)?
|
||||
.into_iter()
|
||||
.find(|snapshot| snapshot.name == name)
|
||||
else {
|
||||
return Err(crate::Error::CreateProcessError(format!(
|
||||
"failed to find a module with identifier `{name}`",
|
||||
)));
|
||||
};
|
||||
let module = Module {
|
||||
process_id: self.id,
|
||||
name: snapshot.name,
|
||||
path: snapshot.path,
|
||||
base_address: snapshot.base_address,
|
||||
base_size: snapshot.base_size,
|
||||
};
|
||||
Ok(module)
|
||||
}
|
||||
|
||||
/// follow a pointer chain to the end and return an address
|
||||
pub fn resolve_pointer_chain(&self, chain: &[usize]) -> Result<usize, crate::Error> {
|
||||
let mut chain = chain.to_vec();
|
||||
let mut address = chain.remove(0);
|
||||
while chain.len() > 1 {
|
||||
address += chain.remove(0);
|
||||
address = self.read_mem(address)?;
|
||||
}
|
||||
Ok(address + chain.remove(0))
|
||||
}
|
||||
|
||||
/// read a given `address` of process's memory
|
||||
pub fn read_mem<T: Default>(&self, address: usize) -> Result<T, crate::Error> {
|
||||
let mut value = Default::default();
|
||||
memory::read(&self.handle, address, &mut value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// write a `value` at given `address` of process's memory
|
||||
pub fn write_mem<T: Default>(&self, address: usize, mut value: T) -> Result<(), crate::Error> {
|
||||
memory::write(&self.handle, address, &mut value)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
#![allow(clippy::module_name_repetitions)]
|
||||
|
||||
use windows::Win32::System::Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, Module32FirstW, Module32NextW, Process32FirstW, Process32NextW,
|
||||
MODULEENTRY32W, PROCESSENTRY32W, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, TH32CS_SNAPPROCESS,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProcessSnapshot {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl ProcessSnapshot {
|
||||
pub fn get_processes() -> Result<Vec<Self>, crate::Error> {
|
||||
let snapshot = unsafe {
|
||||
match CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) {
|
||||
Ok(snapshot) => snapshot,
|
||||
Err(why) => {
|
||||
return Err(crate::Error::CreateSnapshotError(format!(
|
||||
"failed to create process snapshot: {why}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut process_entry_32_w = PROCESSENTRY32W {
|
||||
dwSize: u32::try_from(size_of::<PROCESSENTRY32W>())?,
|
||||
..Default::default()
|
||||
};
|
||||
unsafe {
|
||||
match Process32FirstW(snapshot, &mut process_entry_32_w) {
|
||||
Ok(()) => {}
|
||||
Err(why) => {
|
||||
return Err(crate::Error::CreateSnapshotError(format!(
|
||||
"failed to get first process from snapshot: {why}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
}
|
||||
let mut processes = Vec::new();
|
||||
loop {
|
||||
let name = String::from_utf16_lossy(&process_entry_32_w.szExeFile)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
let process = Self {
|
||||
id: process_entry_32_w.th32ProcessID,
|
||||
name,
|
||||
};
|
||||
processes.push(process);
|
||||
unsafe {
|
||||
if Process32NextW(snapshot, &mut process_entry_32_w).is_err() {
|
||||
break;
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(processes)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ModuleSnapshot {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub base_address: usize,
|
||||
pub base_size: usize,
|
||||
}
|
||||
|
||||
impl ModuleSnapshot {
|
||||
pub fn get_modules(pid: u32) -> Result<Vec<Self>, crate::Error> {
|
||||
let snapshot = unsafe {
|
||||
match CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid) {
|
||||
Ok(snapshot) => snapshot,
|
||||
Err(why) => {
|
||||
return Err(crate::Error::CreateSnapshotError(format!(
|
||||
"failed to create module snapshot: {why}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut module_entry_32_w = MODULEENTRY32W {
|
||||
dwSize: u32::try_from(size_of::<MODULEENTRY32W>())?,
|
||||
..Default::default()
|
||||
};
|
||||
unsafe {
|
||||
match Module32FirstW(snapshot, &mut module_entry_32_w) {
|
||||
Ok(()) => {}
|
||||
Err(why) => {
|
||||
return Err(crate::Error::CreateSnapshotError(format!(
|
||||
"failed to get first module from snapshot: {why}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut modules = Vec::new();
|
||||
loop {
|
||||
let name = String::from_utf16_lossy(&module_entry_32_w.szModule)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
let path = String::from_utf16_lossy(&module_entry_32_w.szExePath)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
let module = Self {
|
||||
name,
|
||||
path,
|
||||
base_address: module_entry_32_w.modBaseAddr as usize,
|
||||
base_size: module_entry_32_w.modBaseSize as usize,
|
||||
};
|
||||
modules.push(module);
|
||||
unsafe {
|
||||
if Module32NextW(snapshot, &mut module_entry_32_w).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(modules)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod handle;
|
||||
pub mod memory;
|
||||
pub mod snapshot;
|
||||
@@ -0,0 +1,46 @@
|
||||
use crate::Error;
|
||||
use std::ops::Deref;
|
||||
use windows::Win32::{
|
||||
Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE},
|
||||
System::Threading::{OpenProcess, PROCESS_ALL_ACCESS, PROCESS_VM_READ, PROCESS_VM_WRITE},
|
||||
};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Handle(pub HANDLE);
|
||||
|
||||
unsafe impl Send for Handle {}
|
||||
unsafe impl Sync for Handle {}
|
||||
|
||||
impl Deref for Handle {
|
||||
type Target = HANDLE;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
if let Err(why) = unsafe { CloseHandle(**self) } {
|
||||
log::error!("failed to close handle: {why}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
pub fn from_pid(pid: u32) -> Result<Self, Error> {
|
||||
let handle = unsafe { OpenProcess(PROCESS_ALL_ACCESS, false, pid) }
|
||||
.or_else(|_| unsafe { OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid) })
|
||||
.map_err(|why| {
|
||||
Error::ObtainHandleError(format!(
|
||||
"failed to open process with needed access: {why}",
|
||||
))
|
||||
})?;
|
||||
if handle == INVALID_HANDLE_VALUE {
|
||||
return Err(Error::ObtainHandleError(
|
||||
"failed to get a valid handle".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(Self(handle))
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,29 @@
|
||||
use super::handle::Handle;
|
||||
|
||||
use crate::{Error, sys::handle::Handle};
|
||||
use std::{ffi::c_void, ptr};
|
||||
|
||||
use windows::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory};
|
||||
|
||||
pub fn read<T>(handle: &Handle, address: usize, value: &mut T) -> Result<(), crate::Error> {
|
||||
pub fn read<T>(handle: &Handle, address: usize, value: &mut T) -> Result<(), Error> {
|
||||
unsafe {
|
||||
match ReadProcessMemory(
|
||||
ReadProcessMemory(
|
||||
handle.0,
|
||||
address as *const c_void,
|
||||
(ptr::from_mut::<T>(value)).cast::<c_void>(),
|
||||
size_of::<T>(),
|
||||
None,
|
||||
) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(why) => Err(crate::Error::AccessMemoryError(format!(
|
||||
"failed to read memory: {why}"
|
||||
))),
|
||||
}
|
||||
)
|
||||
}
|
||||
.map_err(|why| Error::AccessMemoryError(format!("failed to read memory: {why}")))
|
||||
}
|
||||
|
||||
pub fn write<T>(handle: &Handle, address: usize, value: &mut T) -> Result<(), crate::Error> {
|
||||
pub fn write<T>(handle: &Handle, address: usize, value: &mut T) -> Result<(), Error> {
|
||||
unsafe {
|
||||
match WriteProcessMemory(
|
||||
WriteProcessMemory(
|
||||
handle.0,
|
||||
address as *const c_void,
|
||||
(ptr::from_mut::<T>(value)).cast::<c_void>(),
|
||||
size_of::<T>(),
|
||||
None,
|
||||
) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(why) => Err(crate::Error::AccessMemoryError(format!(
|
||||
"failed to write memory: {why}"
|
||||
))),
|
||||
}
|
||||
)
|
||||
}
|
||||
.map_err(|why| Error::AccessMemoryError(format!("failed to write memory: {why}")))
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use crate::Error;
|
||||
use windows::Win32::System::Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, MODULEENTRY32W, Module32FirstW, Module32NextW, PROCESSENTRY32W,
|
||||
Process32FirstW, Process32NextW, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, TH32CS_SNAPPROCESS,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProcessSnapshot {
|
||||
pub id: u32,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl ProcessSnapshot {
|
||||
pub fn get_processes() -> Result<Vec<Self>, Error> {
|
||||
let snapshot =
|
||||
unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }.map_err(|why| {
|
||||
Error::CreateSnapshotError(format!("failed to create process snapshot: {why}"))
|
||||
})?;
|
||||
let mut process_entry_32_w = PROCESSENTRY32W {
|
||||
dwSize: u32::try_from(size_of::<PROCESSENTRY32W>())?,
|
||||
..Default::default()
|
||||
};
|
||||
unsafe { Process32FirstW(snapshot, &raw mut process_entry_32_w) }.map_err(|why| {
|
||||
Error::CreateSnapshotError(format!("failed to get first process from snapshot: {why}"))
|
||||
})?;
|
||||
let mut processes = Vec::new();
|
||||
loop {
|
||||
let name = String::from_utf16_lossy(&process_entry_32_w.szExeFile)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
let process = Self {
|
||||
id: process_entry_32_w.th32ProcessID,
|
||||
name,
|
||||
};
|
||||
processes.push(process);
|
||||
if unsafe { Process32NextW(snapshot, &raw mut process_entry_32_w) }.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(processes)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ModuleSnapshot {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub base_address: usize,
|
||||
pub base_size: usize,
|
||||
}
|
||||
|
||||
impl ModuleSnapshot {
|
||||
pub fn get_modules(pid: u32) -> Result<Vec<Self>, Error> {
|
||||
let snapshot =
|
||||
unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, pid) }
|
||||
.map_err(|why| {
|
||||
Error::CreateSnapshotError(format!("failed to create module snapshot: {why}"))
|
||||
})?;
|
||||
let mut module_entry_32_w = MODULEENTRY32W {
|
||||
dwSize: u32::try_from(size_of::<MODULEENTRY32W>())?,
|
||||
..Default::default()
|
||||
};
|
||||
unsafe { Module32FirstW(snapshot, &raw mut module_entry_32_w) }.map_err(|why| {
|
||||
Error::CreateSnapshotError(format!("failed to get first module from snapshot: {why}"))
|
||||
})?;
|
||||
let mut modules = Vec::new();
|
||||
loop {
|
||||
let name = String::from_utf16_lossy(&module_entry_32_w.szModule)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
let path = String::from_utf16_lossy(&module_entry_32_w.szExePath)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
let module = Self {
|
||||
name,
|
||||
path,
|
||||
base_address: module_entry_32_w.modBaseAddr as usize,
|
||||
base_size: module_entry_32_w.modBaseSize as usize,
|
||||
};
|
||||
modules.push(module);
|
||||
if unsafe { Module32NextW(snapshot, &raw mut module_entry_32_w).is_err() } {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(modules)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::process::*;
|
||||
|
||||
#[test]
|
||||
fn resolve_pointer_chain_empty() {
|
||||
let myself = Process::find(std::process::id()).unwrap();
|
||||
let result = myself.resolve_pointer_chain(&[]);
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_pointer_chain_single() {
|
||||
let myself = Process::find(std::process::id()).unwrap();
|
||||
let result = myself.resolve_pointer_chain(&[myself.base_address]);
|
||||
assert_eq!(result.unwrap(), myself.base_address);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_pointer_chain_multiple() {
|
||||
let myself = Process::find(std::process::id()).unwrap();
|
||||
let target_value = 1337;
|
||||
let target_ptr = &target_value as *const i32 as usize;
|
||||
let base_ptr = &target_ptr as *const usize as usize;
|
||||
let address = myself.resolve_pointer_chain(&[base_ptr, 0x0, 0x0]).unwrap();
|
||||
assert_eq!(address, target_ptr);
|
||||
let value = myself.read_mem::<i32>(address).unwrap();
|
||||
assert_eq!(value, target_value);
|
||||
}
|
||||
Reference in New Issue
Block a user