25 Commits
Author SHA1 Message Date
futile 1ed4cc4980 use handle.is_invalid() instead of comparison 2025-12-07 11:36:44 +00:00
futile cb1c6b936e use derive_more for Deref implementation on Handle 2025-12-07 11:35:04 +00:00
futile fb910d7237 nicer import 2025-12-07 11:33:02 +00:00
futile d951a1ebed use derive_more for From implementations on Identifier 2025-12-07 11:30:48 +00:00
futile 6bd77dbe37 remove unnecessary Win32_Foundation feature from windows import 2025-12-07 11:18:46 +00:00
futile cbdcb32fc3 use correct paths for internal Error 2025-12-07 11:05:53 +00:00
futile b76bb7a0d2 0.3.0 2025-12-05 15:18:39 +00:00
futile c18c427af5 process: move Identifier code to the bottom 2025-12-04 08:06:30 +00:00
futile 06123b5b7b process: improve type ergonomics 2025-12-04 08:05:37 +00:00
futile f30a4690df process: better doc on Process::find 2025-12-04 08:05:03 +00:00
futile b906ed044d cargo fmt 2025-12-04 06:02:08 +00:00
futile 3c26590c7c process: fix panic on single item chains 2025-12-04 05:59:35 +00:00
futile a22c9cd0ce add some basic unit tests 2025-12-04 05:59:20 +00:00
futile afc6724be1 improve resolve_pointer_chain implementation 2025-12-04 05:22:42 +00:00
futile 6ba282fd87 update readme 2025-12-04 05:22:38 +00:00
futile a92b59c808 process: rename from to find 2025-12-04 04:16:03 +00:00
futile 52b81d900c process: update Process base_address doc a little 2025-12-04 04:15:51 +00:00
futile 868ad9c191 rename CreateProcessError to ProcessError 2025-12-04 04:15:16 +00:00
futile a62b11df3f process: make searching for a module case-insensitive 2025-12-04 04:13:08 +00:00
futile b09fdc5fbf process: remove Default constraint on write_mem 2025-12-04 04:11:35 +00:00
futile 98689b682a remove redundant Send + Sync impls on Process 2025-12-03 16:06:15 +00:00
futile 8d4c796cce update readme 2025-12-03 14:03:40 +00:00
futile 637160d3ea format addresses and sizes as hex 2025-12-03 13:47:06 +00:00
futile 30b22107a1 add a modules function to Process 2025-12-03 13:37:57 +00:00
futile 334c4761a2 process: clarify that module is case-sensitive 2025-12-03 13:25:18 +00:00
9 changed files with 121 additions and 70 deletions
+12 -8
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "haxor" name = "haxor"
version = "0.2.0" version = "0.3.0"
edition = "2024" edition = "2024"
readme = "README.md" readme = "README.md"
license = "Apache-2.0" license = "Apache-2.0"
@@ -9,15 +9,19 @@ repository = "https://github.com/elituf/haxor"
keywords = ["memory", "game", "hacking", "process"] keywords = ["memory", "game", "hacking", "process"]
[dependencies] [dependencies]
derive_more = { version = "2", features = ["display"] } derive_more = { version = "2", features = [
"debug",
"deref",
"display",
"from",
] }
log = "0.4" log = "0.4"
thiserror = "2" thiserror = "2"
windows = { version = "0.62", features = [
[dependencies.windows]
version = "0.62"
features = [
"Win32_Foundation",
"Win32_System_Threading", "Win32_System_Threading",
"Win32_System_Diagnostics_ToolHelp", "Win32_System_Diagnostics_ToolHelp",
"Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_Debug",
] ] }
[lib]
doctest = false
+3 -3
View File
@@ -1,14 +1,14 @@
## haxor ## haxor
memory hacking library windows external memory hacking library
## using ## using
```rust ```rust
let proc = Process::from("notepad.exe")?; let proc = Process::find("notepad.exe")?;
let some_val = proc.read_mem::<i32>(0xDEADBEEF)?; let some_val = proc.read_mem::<i32>(0xDEADBEEF)?;
``` ```
```rust ```rust
let proc = Process::from(1337)?; let proc = Process::find(1337)?;
let chain: Vec<usize> = vec![proc.base_address, 0x4B1D, 0x8, 0x12]; let chain: Vec<usize> = vec![proc.base_address, 0x4B1D, 0x8, 0x12];
let some_addr: usize = proc.resolve_pointer_chain(&chain)?; let some_addr: usize = proc.resolve_pointer_chain(&chain)?;
let some_val = proc.read_mem::<u8>(some_addr)?; let some_val = proc.read_mem::<u8>(some_addr)?;
+6 -3
View File
@@ -9,12 +9,15 @@ pub enum Error {
/// there was a failure when reading or writing the process's memory /// there was a failure when reading or writing the process's memory
#[error("failed to access process memory")] #[error("failed to access process memory")]
AccessMemoryError(String), 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 /// there was a failure in creating a snapshot of processes or modules
#[error("failed to create snapshot")] #[error("failed to create snapshot")]
CreateSnapshotError(String), 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 /// there was a failure in conversion between integers
#[error("failed to convert integer")] #[error("failed to convert integer")]
ConvertIntegerError(#[from] std::num::TryFromIntError), ConvertIntegerError(#[from] std::num::TryFromIntError),
+1
View File
@@ -5,5 +5,6 @@ mod error;
/// types and methods to ease the r/w of a process's memory /// types and methods to ease the r/w of a process's memory
pub mod process; pub mod process;
mod sys; mod sys;
mod tests;
pub use error::Error; pub use error::Error;
+62 -40
View File
@@ -1,29 +1,8 @@
use crate::{ use crate::{
Error, error::Error,
sys::{handle::Handle, memory, snapshot}, sys::{handle::Handle, memory, snapshot},
}; };
use derive_more::derive::Display; use derive_more::{Debug, Display, From};
#[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())
}
}
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
/// a process running on the system /// a process running on the system
@@ -32,18 +11,26 @@ pub struct Process {
pub name: String, pub name: String,
/// the process id (th32ProcessID) /// the process id (th32ProcessID)
pub id: u32, pub id: u32,
/// the base address of the module with the same name as `name` (modBaseAddr) /// the base address of the module with the name `name` (modBaseAddr)
#[debug("0x{base_address:X}")]
pub base_address: usize, pub base_address: usize,
/// the process handle (HANDLE) /// the process handle (HANDLE)
pub handle: Handle, pub handle: Handle,
} }
unsafe impl Send for Process {}
unsafe impl Sync for Process {}
impl Process { impl Process {
/// initialize a `Process` from a pid or a process name /// initialize a `Process` from a pid or a process name
pub fn from<T: Into<Identifier>>(identifier: T) -> Result<Self, Error> { ///
/// ### 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 identifier = identifier.into();
let snapshot = snapshot::ProcessSnapshot::get_processes()? let snapshot = snapshot::ProcessSnapshot::get_processes()?
.into_iter() .into_iter()
@@ -52,7 +39,7 @@ impl Process {
Identifier::Name(ref name) => snapshot.name == *name, Identifier::Name(ref name) => snapshot.name == *name,
}) })
.ok_or_else(|| { .ok_or_else(|| {
Error::CreateProcessError(format!( Error::ProcessError(format!(
"failed to find a process with identifier `{identifier}`", "failed to find a process with identifier `{identifier}`",
)) ))
})?; })?;
@@ -66,13 +53,14 @@ impl Process {
Ok(process) Ok(process)
} }
/// get a `Module` of a `Process` by name /// get a `Module` of a `Process` by name (case-insensitive)
pub fn module(&self, name: &str) -> Result<Module, Error> { 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)? let Some(snapshot) = snapshot::ModuleSnapshot::get_modules(self.id)?
.into_iter() .into_iter()
.find(|snapshot| snapshot.name == name) .find(|snapshot| name.eq_ignore_ascii_case(&snapshot.name))
else { else {
return Err(Error::CreateProcessError(format!( return Err(Error::ProcessError(format!(
"failed to find a module with identifier `{name}`", "failed to find a module with identifier `{name}`",
))); )));
}; };
@@ -86,15 +74,36 @@ impl Process {
Ok(module) 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 /// follow a pointer chain to the end and return an address
pub fn resolve_pointer_chain(&self, chain: &[usize]) -> Result<usize, Error> { pub fn resolve_pointer_chain<T: AsRef<[usize]>>(&self, chain: T) -> Result<usize, Error> {
let mut chain = chain.to_vec(); let chain = chain.as_ref();
let mut address = chain.remove(0); if chain.is_empty() {
while chain.len() > 1 { return Err(Error::ResolvePointerChainError("chain was empty".into()));
address += chain.remove(0); }
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)?; address = self.read_mem(address)?;
} }
Ok(address + chain.remove(0)) Ok(address + chain.last().expect("chain should have a last element"))
} }
/// read a given `address` of process's memory /// read a given `address` of process's memory
@@ -105,7 +114,7 @@ impl Process {
} }
/// write a `value` at given `address` of process's memory /// write a `value` at given `address` of process's memory
pub fn write_mem<T: Default>(&self, address: usize, mut value: T) -> Result<(), Error> { pub fn write_mem<T>(&self, address: usize, mut value: T) -> Result<(), Error> {
memory::write(&self.handle, address, &mut value)?; memory::write(&self.handle, address, &mut value)?;
Ok(()) Ok(())
} }
@@ -121,7 +130,20 @@ pub struct Module {
/// the module executable path (szExePath) /// the module executable path (szExePath)
pub path: String, pub path: String,
/// the module base address (modBaseAddr) /// the module base address (modBaseAddr)
#[debug("0x{base_address:X}")]
pub base_address: usize, pub base_address: usize,
/// the module base size (modBaseSize) /// the module base size (modBaseSize)
#[debug("0x{base_size:X}")]
pub base_size: usize, pub base_size: usize,
} }
#[derive(Display, From)]
/// an identifier for searching for a process
pub enum Identifier {
/// process id to search for
#[from(u32)]
Pid(u32),
/// process name to search for
#[from(&str, String)]
Name(String),
}
+5 -13
View File
@@ -1,24 +1,16 @@
use crate::Error; use crate::error::Error;
use std::ops::Deref; use derive_more::Deref;
use windows::Win32::{ use windows::Win32::{
Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}, Foundation::{CloseHandle, HANDLE},
System::Threading::{OpenProcess, PROCESS_ALL_ACCESS, PROCESS_VM_READ, PROCESS_VM_WRITE}, System::Threading::{OpenProcess, PROCESS_ALL_ACCESS, PROCESS_VM_READ, PROCESS_VM_WRITE},
}; };
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Deref, Clone)]
pub struct Handle(pub HANDLE); pub struct Handle(pub HANDLE);
unsafe impl Send for Handle {} unsafe impl Send for Handle {}
unsafe impl Sync 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 { impl Drop for Handle {
fn drop(&mut self) { fn drop(&mut self) {
if let Err(why) = unsafe { CloseHandle(**self) } { if let Err(why) = unsafe { CloseHandle(**self) } {
@@ -36,7 +28,7 @@ impl Handle {
"failed to open process with needed access: {why}", "failed to open process with needed access: {why}",
)) ))
})?; })?;
if handle == INVALID_HANDLE_VALUE { if handle.is_invalid() {
return Err(Error::ObtainHandleError( return Err(Error::ObtainHandleError(
"failed to get a valid handle".to_string(), "failed to get a valid handle".to_string(),
)); ));
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::{sys::handle::Handle, Error}; use crate::{error::Error, sys::handle::Handle};
use std::{ffi::c_void, ptr}; use std::{ffi::c_void, ptr};
use windows::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory}; use windows::Win32::System::Diagnostics::Debug::{ReadProcessMemory, WriteProcessMemory};
+2 -2
View File
@@ -1,4 +1,4 @@
use crate::Error; use crate::error::Error;
use windows::Win32::System::Diagnostics::ToolHelp::{ use windows::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, MODULEENTRY32W, Module32FirstW, Module32NextW, PROCESSENTRY32W, CreateToolhelp32Snapshot, MODULEENTRY32W, Module32FirstW, Module32NextW, PROCESSENTRY32W,
Process32FirstW, Process32NextW, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, TH32CS_SNAPPROCESS, Process32FirstW, Process32NextW, TH32CS_SNAPMODULE, TH32CS_SNAPMODULE32, TH32CS_SNAPPROCESS,
@@ -41,7 +41,7 @@ impl ProcessSnapshot {
} }
} }
#[derive(Debug)] #[derive(Clone, Debug)]
pub struct ModuleSnapshot { pub struct ModuleSnapshot {
pub name: String, pub name: String,
pub path: String, pub path: String,
+29
View File
@@ -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);
}