Run rustfmt
This commit is contained in:
parent
b1c3107c74
commit
a154c71f9b
@ -1,7 +1,7 @@
|
||||
use std::rc::Rc;
|
||||
use std::ops::{Add, AddAssign, Sub, SubAssign};
|
||||
use std::cmp::Ordering;
|
||||
use std::fmt;
|
||||
use std::ops::{Add, AddAssign, Sub, SubAssign};
|
||||
use std::rc::Rc;
|
||||
|
||||
// pub struct Object {
|
||||
// name: String,
|
||||
@ -43,41 +43,40 @@ impl Address {
|
||||
}
|
||||
}
|
||||
fn deref<F>(&self, resolver: &F) -> Address
|
||||
where F: Fn(u64) -> u64 {
|
||||
where
|
||||
F: Fn(u64) -> u64,
|
||||
{
|
||||
match &self.pointer {
|
||||
Some(p) => {
|
||||
let addr = p.deref(resolver);
|
||||
// println!("deref: {} -> {}; resolve: 0x{:x}", self, addr, addr.base + addr.offset);
|
||||
let base =
|
||||
if addr.base != 0 {
|
||||
resolver(addr.base + addr.offset)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let base = if addr.base != 0 {
|
||||
resolver(addr.base + addr.offset)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Address {
|
||||
base: base,
|
||||
pointer: None,
|
||||
offset: self.offset,
|
||||
}
|
||||
},
|
||||
None => {
|
||||
Address {
|
||||
base: self.base,
|
||||
pointer: None,
|
||||
offset: self.offset,
|
||||
}
|
||||
}
|
||||
None => Address {
|
||||
base: self.base,
|
||||
pointer: None,
|
||||
offset: self.offset,
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn get<F>(&self, resolver: &F) -> u64
|
||||
where F: Fn(u64) -> u64 {
|
||||
where
|
||||
F: Fn(u64) -> u64,
|
||||
{
|
||||
if self.pointer.is_some() {
|
||||
self.deref(resolver).get(resolver)
|
||||
}
|
||||
else if self.base == 0 {
|
||||
} else if self.base == 0 {
|
||||
0
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
self.base + self.offset
|
||||
}
|
||||
}
|
||||
@ -136,9 +135,10 @@ impl SubAssign<u64> for Address {
|
||||
|
||||
impl PartialEq for Address {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.pointer.is_none() && other.pointer.is_none()
|
||||
&& self.base == other.base
|
||||
&& self.offset == other.offset
|
||||
self.pointer.is_none()
|
||||
&& other.pointer.is_none()
|
||||
&& self.base == other.base
|
||||
&& self.offset == other.offset
|
||||
}
|
||||
}
|
||||
|
||||
@ -146,8 +146,7 @@ impl PartialOrd for Address {
|
||||
fn partial_cmp(&self, other: &Address) -> Option<Ordering> {
|
||||
if self.pointer.is_some() || other.pointer.is_some() {
|
||||
None
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
let this = self.base + self.offset;
|
||||
let that = other.base + other.offset;
|
||||
Some(this.cmp(&that))
|
||||
@ -159,11 +158,9 @@ impl fmt::Display for Address {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if let Some(p) = &self.pointer {
|
||||
write!(f, "*({}) + 0x{:x}", *p, self.offset)
|
||||
}
|
||||
else if self.offset != 0 {
|
||||
} else if self.offset != 0 {
|
||||
write!(f, "0x{:x} + 0x{:x}", self.base, self.offset)
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
write!(f, "0x{:x}", self.base)
|
||||
}
|
||||
}
|
||||
@ -174,7 +171,7 @@ impl Clone for Address {
|
||||
Address {
|
||||
base: self.base,
|
||||
pointer: self.pointer.clone(),
|
||||
offset: self.offset
|
||||
offset: self.offset,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,14 +1,15 @@
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
scan_driver
|
||||
};
|
||||
use lpus::{driver_state::DriverState, scan_driver};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
@ -21,4 +22,3 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
@ -1,24 +1,30 @@
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
scan_eprocess
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
let result = scan_eprocess(&driver).unwrap_or(Vec::new());
|
||||
|
||||
for r in result.iter() {
|
||||
println!("{:#}", r.to_string());
|
||||
}
|
||||
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::DriverState, scan_eprocess, traverse_activehead, traverse_handletable,
|
||||
traverse_kiprocesslist,
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
let scan = scan_eprocess(&driver).unwrap_or(Vec::new());
|
||||
let activehead = traverse_activehead(&driver).unwrap_or(Vec::new());
|
||||
let kiprocesslist = traverse_kiprocesslist(&driver).unwrap_or(Vec::new());
|
||||
let handletable = traverse_handletable(&driver).unwrap_or(Vec::new());
|
||||
|
||||
for r in scan.iter() {
|
||||
println!("{:#}", r.to_string());
|
||||
}
|
||||
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1,16 +1,17 @@
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
traverse_activehead,
|
||||
traverse_kiprocesslist,
|
||||
traverse_handletable
|
||||
driver_state::DriverState, traverse_activehead, traverse_handletable, traverse_kiprocesslist,
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
@ -33,4 +34,3 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
@ -1,25 +1,24 @@
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
scan_file
|
||||
};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
let result = scan_file(&driver).unwrap_or(Vec::new());
|
||||
|
||||
for r in result.iter() {
|
||||
println!("{:#}", r.to_string());
|
||||
}
|
||||
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{driver_state::DriverState, scan_file};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
let result = scan_file(&driver).unwrap_or(Vec::new());
|
||||
|
||||
for r in result.iter() {
|
||||
println!("{:#}", r.to_string());
|
||||
}
|
||||
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1,14 +1,15 @@
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
scan_kernel_module
|
||||
};
|
||||
use lpus::{driver_state::DriverState, scan_kernel_module};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
@ -21,5 +22,3 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
|
@ -2,16 +2,16 @@ use std::error::Error;
|
||||
|
||||
use parse_int::parse;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
traverse_loadedmodulelist,
|
||||
traverse_unloadeddrivers
|
||||
};
|
||||
use lpus::{driver_state::DriverState, traverse_loadedmodulelist, traverse_unloadeddrivers};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
@ -26,10 +26,11 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
let servicelimit_ptr = ntosbase.clone() + driver.pdb_store.get_offset_r("KiServiceLimit")?;
|
||||
|
||||
let servicelimit = driver.deref_addr_new::<u32>(servicelimit_ptr.address()) as u64;
|
||||
let ssdt: Vec<u64> = driver.deref_array::<u32>(&servicetable, servicelimit)
|
||||
.iter().map(|entry| {
|
||||
servicetable.address() + ((entry >> 4) as u64)
|
||||
}).collect();
|
||||
let ssdt: Vec<u64> = driver
|
||||
.deref_array::<u32>(&servicetable, servicelimit)
|
||||
.iter()
|
||||
.map(|entry| servicetable.address() + ((entry >> 4) as u64))
|
||||
.collect();
|
||||
|
||||
for r in loaded.iter() {
|
||||
println!("{:#}", r.to_string());
|
||||
@ -41,8 +42,14 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("=============================================");
|
||||
for func in ssdt {
|
||||
for r in loaded.iter() {
|
||||
let base = r["dllbase"].as_str().and_then(|b| parse::<u64>(b).ok()).unwrap_or(0);
|
||||
let size = r["size"].as_str().and_then(|s| parse::<u64>(s).ok()).unwrap_or(0);
|
||||
let base = r["dllbase"]
|
||||
.as_str()
|
||||
.and_then(|b| parse::<u64>(b).ok())
|
||||
.unwrap_or(0);
|
||||
let size = r["size"]
|
||||
.as_str()
|
||||
.and_then(|s| parse::<u64>(s).ok())
|
||||
.unwrap_or(0);
|
||||
|
||||
if func > base && func < base + size {
|
||||
let offset = func - ntosbase.address();
|
||||
@ -55,8 +62,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
if n == "" {
|
||||
"(??)".to_string()
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
n
|
||||
}
|
||||
};
|
||||
|
@ -1,63 +1,61 @@
|
||||
use std::error::Error;
|
||||
// use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rustyline::error::ReadlineError;
|
||||
use rustyline::Editor;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
};
|
||||
|
||||
pub fn to_epoch(filetime: u64) -> u64 {
|
||||
// https://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/
|
||||
let windows_epoch_diff = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return 0;
|
||||
}
|
||||
let process_time_epoch = (filetime - windows_epoch_diff) / 10000;
|
||||
// let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards").as_millis() as u64;
|
||||
|
||||
process_time_epoch
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let driver = DriverState::new();
|
||||
driver.windows_ffi.print_version();
|
||||
driver.pdb_store.print_default_information();
|
||||
|
||||
println!("{}", to_epoch(0xfffffa80018cb688));
|
||||
println!("{}", to_epoch(0x01d64ecd8b295318));
|
||||
|
||||
let mut rl = Editor::<()>::new();
|
||||
if rl.load_history("history.lpus").is_err() {
|
||||
println!("No previous history.");
|
||||
}
|
||||
loop {
|
||||
let readline = rl.readline(">> ");
|
||||
match readline {
|
||||
Ok(line) => {
|
||||
rl.add_history_entry(line.as_str());
|
||||
println!("Line: {}", line);
|
||||
// TODO: add parser here
|
||||
if let Err(e) = driver.pdb_store.dt(&line) {
|
||||
println!("{}", e);
|
||||
}
|
||||
},
|
||||
Err(ReadlineError::Interrupted) => {
|
||||
println!("CTRL-C");
|
||||
break
|
||||
},
|
||||
Err(ReadlineError::Eof) => {
|
||||
println!("CTRL-D");
|
||||
break
|
||||
},
|
||||
Err(err) => {
|
||||
println!("Error: {:?}", err);
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
rl.save_history("history.lpus").unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
use std::error::Error;
|
||||
// use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rustyline::error::ReadlineError;
|
||||
use rustyline::Editor;
|
||||
|
||||
use lpus::driver_state::DriverState;
|
||||
|
||||
pub fn to_epoch(filetime: u64) -> u64 {
|
||||
// https://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/
|
||||
let windows_epoch_diff = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return 0;
|
||||
}
|
||||
let process_time_epoch = (filetime - windows_epoch_diff) / 10000;
|
||||
// let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards").as_millis() as u64;
|
||||
|
||||
process_time_epoch
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let driver = DriverState::new();
|
||||
driver.windows_ffi.print_version();
|
||||
driver.pdb_store.print_default_information();
|
||||
|
||||
println!("{}", to_epoch(0xfffffa80018cb688));
|
||||
println!("{}", to_epoch(0x01d64ecd8b295318));
|
||||
|
||||
let mut rl = Editor::<()>::new();
|
||||
if rl.load_history("history.lpus").is_err() {
|
||||
println!("No previous history.");
|
||||
}
|
||||
loop {
|
||||
let readline = rl.readline(">> ");
|
||||
match readline {
|
||||
Ok(line) => {
|
||||
rl.add_history_entry(line.as_str());
|
||||
println!("Line: {}", line);
|
||||
// TODO: add parser here
|
||||
if let Err(e) = driver.pdb_store.dt(&line) {
|
||||
println!("{}", e);
|
||||
}
|
||||
}
|
||||
Err(ReadlineError::Interrupted) => {
|
||||
println!("CTRL-C");
|
||||
break;
|
||||
}
|
||||
Err(ReadlineError::Eof) => {
|
||||
println!("CTRL-D");
|
||||
break;
|
||||
}
|
||||
Err(err) => {
|
||||
println!("Error: {:?}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
rl.save_history("history.lpus").unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1,14 +1,15 @@
|
||||
use std::error::Error;
|
||||
|
||||
use lpus::{
|
||||
driver_state::{DriverState},
|
||||
scan_ethread, /* scan_mutant */
|
||||
};
|
||||
use lpus::{driver_state::DriverState, scan_ethread /* scan_mutant */};
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let mut driver = DriverState::new();
|
||||
if !driver.is_supported() {
|
||||
return Err(format!("Windows version {:?} is not supported", driver.windows_ffi.short_version).into());
|
||||
return Err(format!(
|
||||
"Windows version {:?} is not supported",
|
||||
driver.windows_ffi.short_version
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("NtLoadDriver() -> 0x{:x}", driver.startup());
|
||||
|
||||
@ -25,5 +26,3 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("NtUnloadDriver() -> 0x{:x}", driver.shutdown());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,331 +1,374 @@
|
||||
use std::default::Default;
|
||||
use std::clone::Clone;
|
||||
use std::error::Error;
|
||||
// use std::io::{Error, ErrorKind};
|
||||
use std::ffi::c_void;
|
||||
use std::mem::{size_of_val, size_of};
|
||||
|
||||
use winapi::shared::ntdef::{NTSTATUS};
|
||||
use winapi::shared::minwindef::{DWORD};
|
||||
use winapi::um::winioctl::{
|
||||
CTL_CODE, FILE_ANY_ACCESS,
|
||||
METHOD_IN_DIRECT, METHOD_OUT_DIRECT, /* METHOD_BUFFERED, */ METHOD_NEITHER
|
||||
};
|
||||
|
||||
use crate::address::Address;
|
||||
use crate::pdb_store::{PdbStore, parse_pdb};
|
||||
use crate::windows::{WindowsFFI, WindowsVersion};
|
||||
use crate::ioctl_protocol::{
|
||||
InputData, OffsetData, DerefAddr, ScanPoolData, /* HideProcess, */
|
||||
/* OutputData, */ Nothing
|
||||
};
|
||||
|
||||
type BoxResult<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
const SIOCTL_TYPE: DWORD = 40000;
|
||||
|
||||
pub fn to_epoch(filetime: u64) -> u64 {
|
||||
let windows_epoch_diff: u64 = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return 0;
|
||||
}
|
||||
let process_time_epoch: u64 = (filetime - windows_epoch_diff) / 10000;
|
||||
process_time_epoch
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum DriverAction {
|
||||
SetupOffset,
|
||||
GetKernelBase,
|
||||
ScanPsActiveHead,
|
||||
ScanPool,
|
||||
ScanPoolRemote,
|
||||
DereferenceAddress,
|
||||
HideProcess
|
||||
}
|
||||
|
||||
impl DriverAction {
|
||||
pub fn get_code(&self) -> DWORD {
|
||||
match self {
|
||||
DriverAction::SetupOffset => CTL_CODE(SIOCTL_TYPE, 0x900, METHOD_IN_DIRECT, FILE_ANY_ACCESS),
|
||||
DriverAction::GetKernelBase => CTL_CODE(SIOCTL_TYPE, 0x901, METHOD_OUT_DIRECT, FILE_ANY_ACCESS),
|
||||
DriverAction::ScanPsActiveHead => CTL_CODE(SIOCTL_TYPE, 0x902, METHOD_NEITHER, FILE_ANY_ACCESS),
|
||||
DriverAction::ScanPool => CTL_CODE(SIOCTL_TYPE, 0x903, METHOD_IN_DIRECT, FILE_ANY_ACCESS),
|
||||
DriverAction::ScanPoolRemote => CTL_CODE(SIOCTL_TYPE, 0x904, METHOD_IN_DIRECT, FILE_ANY_ACCESS),
|
||||
DriverAction::DereferenceAddress => CTL_CODE(SIOCTL_TYPE, 0xA00, METHOD_OUT_DIRECT, FILE_ANY_ACCESS),
|
||||
DriverAction::HideProcess => CTL_CODE(SIOCTL_TYPE, 0xA01, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EprocessPoolChunk {
|
||||
pub pool_addr: u64,
|
||||
pub eprocess_addr: u64,
|
||||
pub eprocess_name: String,
|
||||
pub create_time: u64,
|
||||
pub exit_time: u64
|
||||
}
|
||||
|
||||
impl PartialEq for EprocessPoolChunk {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.eprocess_addr == other.eprocess_addr
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct DriverState {
|
||||
// TODO: Make private, only call methods of DriverState
|
||||
pub pdb_store: PdbStore,
|
||||
pub windows_ffi: WindowsFFI,
|
||||
}
|
||||
|
||||
impl DriverState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pdb_store: parse_pdb().expect("Cannot get PDB file"),
|
||||
windows_ffi: WindowsFFI::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn startup(&mut self) -> NTSTATUS {
|
||||
let s = self.windows_ffi.load_driver();
|
||||
let mut input = InputData {
|
||||
offset_value: OffsetData::new(&self.pdb_store, self.windows_ffi.short_version)
|
||||
};
|
||||
self.windows_ffi.device_io(DriverAction::SetupOffset.get_code(),
|
||||
&mut input, &mut Nothing);
|
||||
s
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) -> NTSTATUS {
|
||||
self.windows_ffi.unload_driver()
|
||||
}
|
||||
|
||||
pub fn is_supported(&self) -> bool {
|
||||
self.windows_ffi.short_version.is_supported()
|
||||
}
|
||||
|
||||
pub fn use_old_tag(&self) -> bool {
|
||||
// use old tag to scan, for Window < 8
|
||||
if self.windows_ffi.short_version < WindowsVersion::Windows8 {
|
||||
true
|
||||
}
|
||||
else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_kernel_base(&self) -> Address {
|
||||
let mut ntosbase = 0u64;
|
||||
self.windows_ffi.device_io(DriverAction::GetKernelBase.get_code(),
|
||||
&mut Nothing, &mut ntosbase);
|
||||
Address::from_base(ntosbase)
|
||||
}
|
||||
|
||||
pub fn scan_pool<F>(&self, tag: &[u8; 4], expected_struct: &str, mut handler: F) -> BoxResult<bool>
|
||||
where F: FnMut(Address, &[u8], Address) -> BoxResult<bool>
|
||||
// F(Pool Address, Pool Header Data, Pool Data Address)
|
||||
// TODO: Pool Header as a real struct
|
||||
{
|
||||
// TODO: scan large pool
|
||||
// TODO: make generator, in hold: https://github.com/rust-lang/rust/issues/43122
|
||||
// Making this function a generator will turn the call to a for loop
|
||||
// https://docs.rs/gen-iter/0.2.0/gen_iter/
|
||||
// >> More flexibility in code
|
||||
let pool_header_size = self.pdb_store.get_offset_r("_POOL_HEADER.struct_size")?;
|
||||
let minimum_block_size = self.pdb_store.get_offset_r(&format!("{}.struct_size", expected_struct))?
|
||||
+ pool_header_size;
|
||||
let code = DriverAction::ScanPoolRemote.get_code();
|
||||
let ntosbase = self.get_kernel_base();
|
||||
let [start_address, end_address] = self.get_nonpaged_range(&ntosbase)?;
|
||||
|
||||
println!("kernel base: {}; non-paged pool (start, end): ({}, {}); tag: {:?} {}",
|
||||
ntosbase, start_address, end_address, tag, expected_struct);
|
||||
|
||||
let mut ptr = start_address;
|
||||
while ptr < end_address {
|
||||
let mut next_found = 0u64;
|
||||
let mut input = InputData {
|
||||
scan_range: ScanPoolData::new(&[ptr.address(), end_address.address()], tag)
|
||||
};
|
||||
self.windows_ffi.device_io(code, &mut input, &mut next_found);
|
||||
ptr = Address::from_base(next_found);
|
||||
if ptr >= end_address {
|
||||
break;
|
||||
}
|
||||
|
||||
let pool_addr = Address::from_base(ptr.address());
|
||||
let header: Vec<u8> = self.deref_array(&pool_addr, pool_header_size);
|
||||
let chunk_size = (header[2] as u64) * 16u64;
|
||||
|
||||
if pool_addr.address() + chunk_size > end_address.address() {
|
||||
// the chunk surpasses the non page pool range
|
||||
break;
|
||||
}
|
||||
|
||||
// automatically reject bad chunk
|
||||
if chunk_size < minimum_block_size {
|
||||
ptr += 0x4;
|
||||
continue;
|
||||
}
|
||||
|
||||
let data_addr = Address::from_base(pool_addr.address() + pool_header_size);
|
||||
let success = handler(pool_addr, &header, data_addr).unwrap_or(false);
|
||||
if success {
|
||||
ptr += chunk_size; // skip this chunk
|
||||
}
|
||||
else {
|
||||
ptr += 0x4; // search next
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn address_of(&self, addr: &Address, name: &str) -> BoxResult<u64> {
|
||||
let resolver = |p| { self.deref_addr_new(p) };
|
||||
let r = self.pdb_store.decompose(&addr, &name)?;
|
||||
Ok(r.get(&resolver))
|
||||
}
|
||||
|
||||
pub fn decompose<T: Default>(&self, addr: &Address, name: &str) -> BoxResult<T> {
|
||||
// interface to pdb_store.decompose
|
||||
let resolver = |p| { self.deref_addr_new(p) };
|
||||
let r: T = self.deref_addr_new(self.pdb_store.decompose(&addr, &name)?.get(&resolver));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn decompose_array<T: Default + Clone>(&self, addr: &Address, name: &str, len: u64) -> BoxResult<Vec<T>> {
|
||||
// interface to pdb_store.decompose for array
|
||||
let r: Vec<T> = self.deref_array(&self.pdb_store.decompose(&addr, &name)?, len);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn deref_addr_new<T: Default>(&self, addr: u64) -> T {
|
||||
let mut r: T = Default::default();
|
||||
if addr != 0 {
|
||||
self.deref_addr(addr, &mut r);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
pub fn deref_array<T: Default + Clone>(&self, addr: &Address, len: u64) -> Vec<T> {
|
||||
let resolver = |p| { self.deref_addr_new(p) };
|
||||
let mut r: Vec<T> = vec![Default::default(); len as usize];
|
||||
let size_in_byte = (len as usize) * size_of::<T>();
|
||||
self.deref_addr_ptr(addr.get(&resolver), r.as_mut_ptr(), size_in_byte as u64);
|
||||
r
|
||||
}
|
||||
|
||||
// #[deprecated(note="use deref_addr_new<T>")]
|
||||
pub fn deref_addr<T>(&self, addr: u64, outbuf: &mut T) {
|
||||
let code = DriverAction::DereferenceAddress.get_code();
|
||||
let size: usize = size_of_val(outbuf);
|
||||
let mut input = InputData {
|
||||
deref_addr: DerefAddr {
|
||||
addr,
|
||||
size: size as u64
|
||||
}
|
||||
};
|
||||
self.windows_ffi.device_io(code, &mut input, outbuf);
|
||||
}
|
||||
|
||||
// #[deprecated(note="use deref_array<T>")]
|
||||
pub fn deref_addr_ptr<T>(&self, addr: u64, outptr: *mut T, output_len_as_byte: u64) {
|
||||
let code = DriverAction::DereferenceAddress.get_code();
|
||||
let mut input = InputData {
|
||||
deref_addr: DerefAddr {
|
||||
addr,
|
||||
size: output_len_as_byte
|
||||
}
|
||||
};
|
||||
self.windows_ffi.device_io_raw(code,
|
||||
&mut input as *mut _ as *mut c_void, size_of_val(&input) as DWORD,
|
||||
outptr as *mut c_void, output_len_as_byte as DWORD);
|
||||
}
|
||||
|
||||
pub fn get_unicode_string(&self, unicode_str_addr: u64) -> BoxResult<String> {
|
||||
if unicode_str_addr == 0 {
|
||||
return Err("Not a valid address".into());
|
||||
}
|
||||
|
||||
let mut strlen = 0u16;
|
||||
let mut capacity = 0u16;
|
||||
let mut bufaddr = 0u64;
|
||||
let buffer_ptr = unicode_str_addr + self.pdb_store.get_offset_r("_UNICODE_STRING.Buffer")?;
|
||||
let capacity_addr = unicode_str_addr + self.pdb_store.get_offset_r("_UNICODE_STRING.MaximumLength")?;
|
||||
|
||||
self.deref_addr(unicode_str_addr, &mut strlen);
|
||||
self.deref_addr(capacity_addr, &mut capacity);
|
||||
self.deref_addr(buffer_ptr, &mut bufaddr);
|
||||
|
||||
if bufaddr == 0 || strlen > capacity || strlen == 0 || strlen % 2 != 0 {
|
||||
return Err("Unicode string is empty".into());
|
||||
}
|
||||
|
||||
let mut buf = vec![0u16; (strlen / 2) as usize];
|
||||
self.deref_addr_ptr(bufaddr, buf.as_mut_ptr(), strlen as u64);
|
||||
// TODO: BUG with deref_array, len is wrong,
|
||||
// >> the size of vector is strlen / 2
|
||||
// >> the size to dereference is strlen
|
||||
// XXX: use Vec<u8> and turn to Vec<u16>
|
||||
// let buf: Vec<u16> = self.deref_array(&Address::from_base(bufaddr), (strlen / 2) as u64);
|
||||
|
||||
Ok(String::from_utf16(&buf)?)
|
||||
}
|
||||
|
||||
pub fn get_nonpaged_range(&self, ntosbase: &Address) -> BoxResult<[Address; 2]> {
|
||||
// TODO: Add support for other Windows version here
|
||||
match self.windows_ffi.short_version {
|
||||
WindowsVersion::WindowsFastRing => {
|
||||
let mistate = ntosbase.clone() + self.pdb_store.get_offset_r("MiState")?;
|
||||
let path_first_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeNonPagedPool",
|
||||
"NonPagedPoolFirstVa"
|
||||
].join(".");
|
||||
let path_last_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeNonPagedPool",
|
||||
"NonPagedPoolLastVa"
|
||||
].join(".");
|
||||
let first_va = Address::from_base(self.decompose(&mistate, &path_first_va)?);
|
||||
let last_va = Address::from_base(self.decompose(&mistate, &path_last_va)?);
|
||||
Ok([first_va, last_va])
|
||||
},
|
||||
WindowsVersion::Windows10_2019 |
|
||||
WindowsVersion::Windows10_2018 => {
|
||||
let mistate = ntosbase.clone() + self.pdb_store.get_offset_r("MiState")?;
|
||||
let path_first_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeInformation",
|
||||
"NonPagedPoolFirstVa"
|
||||
].join(".");
|
||||
let path_last_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeInformation",
|
||||
"NonPagedPoolLastVa"
|
||||
].join(".");
|
||||
let first_va = Address::from_base(self.decompose(&mistate, &path_first_va)?);
|
||||
let last_va = Address::from_base(self.decompose(&mistate, &path_last_va)?);
|
||||
Ok([first_va, last_va])
|
||||
},
|
||||
WindowsVersion::Windows7 => {
|
||||
let path_first_va = ntosbase.clone() + self.pdb_store.get_offset_r("MmNonPagedPoolStart")?;
|
||||
let path_last_va = ntosbase.clone() + self.pdb_store.get_offset_r("MiNonPagedPoolEnd")?;
|
||||
let first_va = Address::from_base(self.deref_addr_new(path_first_va.address()));
|
||||
let last_va = Address::from_base(self.deref_addr_new(path_last_va.address()));
|
||||
Ok([first_va, last_va])
|
||||
},
|
||||
_ => {
|
||||
Err("Windows version for nonpaged pool algorithm is not implemented".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
use std::clone::Clone;
|
||||
use std::default::Default;
|
||||
use std::error::Error;
|
||||
// use std::io::{Error, ErrorKind};
|
||||
use std::ffi::c_void;
|
||||
use std::mem::{size_of, size_of_val};
|
||||
|
||||
use winapi::shared::minwindef::DWORD;
|
||||
use winapi::shared::ntdef::NTSTATUS;
|
||||
use winapi::um::winioctl::{
|
||||
CTL_CODE, FILE_ANY_ACCESS, METHOD_IN_DIRECT, /* METHOD_BUFFERED, */ METHOD_NEITHER,
|
||||
METHOD_OUT_DIRECT,
|
||||
};
|
||||
|
||||
use crate::address::Address;
|
||||
use crate::ioctl_protocol::{
|
||||
DerefAddr, InputData, /* OutputData, */ Nothing, OffsetData,
|
||||
ScanPoolData, /* HideProcess, */
|
||||
};
|
||||
use crate::pdb_store::{parse_pdb, PdbStore};
|
||||
use crate::windows::{WindowsFFI, WindowsVersion};
|
||||
|
||||
type BoxResult<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
const SIOCTL_TYPE: DWORD = 40000;
|
||||
|
||||
pub fn to_epoch(filetime: u64) -> u64 {
|
||||
let windows_epoch_diff: u64 = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return 0;
|
||||
}
|
||||
let process_time_epoch: u64 = (filetime - windows_epoch_diff) / 10000;
|
||||
process_time_epoch
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum DriverAction {
|
||||
SetupOffset,
|
||||
GetKernelBase,
|
||||
ScanPsActiveHead,
|
||||
ScanPool,
|
||||
ScanPoolRemote,
|
||||
DereferenceAddress,
|
||||
HideProcess,
|
||||
}
|
||||
|
||||
impl DriverAction {
|
||||
pub fn get_code(&self) -> DWORD {
|
||||
match self {
|
||||
DriverAction::SetupOffset => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0x900, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
DriverAction::GetKernelBase => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0x901, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
DriverAction::ScanPsActiveHead => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0x902, METHOD_NEITHER, FILE_ANY_ACCESS)
|
||||
}
|
||||
DriverAction::ScanPool => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0x903, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
DriverAction::ScanPoolRemote => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0x904, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
DriverAction::DereferenceAddress => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0xA00, METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
DriverAction::HideProcess => {
|
||||
CTL_CODE(SIOCTL_TYPE, 0xA01, METHOD_IN_DIRECT, FILE_ANY_ACCESS)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EprocessPoolChunk {
|
||||
pub pool_addr: u64,
|
||||
pub eprocess_addr: u64,
|
||||
pub eprocess_name: String,
|
||||
pub create_time: u64,
|
||||
pub exit_time: u64,
|
||||
}
|
||||
|
||||
impl PartialEq for EprocessPoolChunk {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.eprocess_addr == other.eprocess_addr
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub struct DriverState {
|
||||
// TODO: Make private, only call methods of DriverState
|
||||
pub pdb_store: PdbStore,
|
||||
pub windows_ffi: WindowsFFI,
|
||||
}
|
||||
|
||||
impl DriverState {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pdb_store: parse_pdb().expect("Cannot get PDB file"),
|
||||
windows_ffi: WindowsFFI::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn startup(&mut self) -> NTSTATUS {
|
||||
let s = self.windows_ffi.load_driver();
|
||||
let mut input = InputData {
|
||||
offset_value: OffsetData::new(&self.pdb_store, self.windows_ffi.short_version),
|
||||
};
|
||||
self.windows_ffi.device_io(
|
||||
DriverAction::SetupOffset.get_code(),
|
||||
&mut input,
|
||||
&mut Nothing,
|
||||
);
|
||||
s
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) -> NTSTATUS {
|
||||
self.windows_ffi.unload_driver()
|
||||
}
|
||||
|
||||
pub fn is_supported(&self) -> bool {
|
||||
self.windows_ffi.short_version.is_supported()
|
||||
}
|
||||
|
||||
pub fn use_old_tag(&self) -> bool {
|
||||
// use old tag to scan, for Window < 8
|
||||
if self.windows_ffi.short_version < WindowsVersion::Windows8 {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_kernel_base(&self) -> Address {
|
||||
let mut ntosbase = 0u64;
|
||||
self.windows_ffi.device_io(
|
||||
DriverAction::GetKernelBase.get_code(),
|
||||
&mut Nothing,
|
||||
&mut ntosbase,
|
||||
);
|
||||
Address::from_base(ntosbase)
|
||||
}
|
||||
|
||||
pub fn scan_pool<F>(
|
||||
&self,
|
||||
tag: &[u8; 4],
|
||||
expected_struct: &str,
|
||||
mut handler: F,
|
||||
) -> BoxResult<bool>
|
||||
where
|
||||
F: FnMut(Address, &[u8], Address) -> BoxResult<bool>, // F(Pool Address, Pool Header Data, Pool Data Address)
|
||||
// TODO: Pool Header as a real struct
|
||||
{
|
||||
// TODO: scan large pool
|
||||
// TODO: make generator, in hold: https://github.com/rust-lang/rust/issues/43122
|
||||
// Making this function a generator will turn the call to a for loop
|
||||
// https://docs.rs/gen-iter/0.2.0/gen_iter/
|
||||
// >> More flexibility in code
|
||||
let pool_header_size = self.pdb_store.get_offset_r("_POOL_HEADER.struct_size")?;
|
||||
let minimum_block_size = self
|
||||
.pdb_store
|
||||
.get_offset_r(&format!("{}.struct_size", expected_struct))?
|
||||
+ pool_header_size;
|
||||
let code = DriverAction::ScanPoolRemote.get_code();
|
||||
let ntosbase = self.get_kernel_base();
|
||||
let [start_address, end_address] = self.get_nonpaged_range(&ntosbase)?;
|
||||
|
||||
println!(
|
||||
"kernel base: {}; non-paged pool (start, end): ({}, {}); tag: {:?} {}",
|
||||
ntosbase, start_address, end_address, tag, expected_struct
|
||||
);
|
||||
|
||||
let mut ptr = start_address;
|
||||
while ptr < end_address {
|
||||
let mut next_found = 0u64;
|
||||
let mut input = InputData {
|
||||
scan_range: ScanPoolData::new(&[ptr.address(), end_address.address()], tag),
|
||||
};
|
||||
self.windows_ffi
|
||||
.device_io(code, &mut input, &mut next_found);
|
||||
ptr = Address::from_base(next_found);
|
||||
if ptr >= end_address {
|
||||
break;
|
||||
}
|
||||
|
||||
let pool_addr = Address::from_base(ptr.address());
|
||||
let header: Vec<u8> = self.deref_array(&pool_addr, pool_header_size);
|
||||
let chunk_size = (header[2] as u64) * 16u64;
|
||||
|
||||
if pool_addr.address() + chunk_size > end_address.address() {
|
||||
// the chunk surpasses the non page pool range
|
||||
break;
|
||||
}
|
||||
|
||||
// automatically reject bad chunk
|
||||
if chunk_size < minimum_block_size {
|
||||
ptr += 0x4;
|
||||
continue;
|
||||
}
|
||||
|
||||
let data_addr = Address::from_base(pool_addr.address() + pool_header_size);
|
||||
let success = handler(pool_addr, &header, data_addr).unwrap_or(false);
|
||||
if success {
|
||||
ptr += chunk_size; // skip this chunk
|
||||
} else {
|
||||
ptr += 0x4; // search next
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn address_of(&self, addr: &Address, name: &str) -> BoxResult<u64> {
|
||||
let resolver = |p| self.deref_addr_new(p);
|
||||
let r = self.pdb_store.decompose(&addr, &name)?;
|
||||
Ok(r.get(&resolver))
|
||||
}
|
||||
|
||||
pub fn decompose<T: Default>(&self, addr: &Address, name: &str) -> BoxResult<T> {
|
||||
// interface to pdb_store.decompose
|
||||
let resolver = |p| self.deref_addr_new(p);
|
||||
let r: T = self.deref_addr_new(self.pdb_store.decompose(&addr, &name)?.get(&resolver));
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn decompose_array<T: Default + Clone>(
|
||||
&self,
|
||||
addr: &Address,
|
||||
name: &str,
|
||||
len: u64,
|
||||
) -> BoxResult<Vec<T>> {
|
||||
// interface to pdb_store.decompose for array
|
||||
let r: Vec<T> = self.deref_array(&self.pdb_store.decompose(&addr, &name)?, len);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn deref_addr_new<T: Default>(&self, addr: u64) -> T {
|
||||
let mut r: T = Default::default();
|
||||
if addr != 0 {
|
||||
self.deref_addr(addr, &mut r);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
pub fn deref_array<T: Default + Clone>(&self, addr: &Address, len: u64) -> Vec<T> {
|
||||
let resolver = |p| self.deref_addr_new(p);
|
||||
let mut r: Vec<T> = vec![Default::default(); len as usize];
|
||||
let size_in_byte = (len as usize) * size_of::<T>();
|
||||
self.deref_addr_ptr(addr.get(&resolver), r.as_mut_ptr(), size_in_byte as u64);
|
||||
r
|
||||
}
|
||||
|
||||
// #[deprecated(note="use deref_addr_new<T>")]
|
||||
pub fn deref_addr<T>(&self, addr: u64, outbuf: &mut T) {
|
||||
let code = DriverAction::DereferenceAddress.get_code();
|
||||
let size: usize = size_of_val(outbuf);
|
||||
let mut input = InputData {
|
||||
deref_addr: DerefAddr {
|
||||
addr,
|
||||
size: size as u64,
|
||||
},
|
||||
};
|
||||
self.windows_ffi.device_io(code, &mut input, outbuf);
|
||||
}
|
||||
|
||||
// #[deprecated(note="use deref_array<T>")]
|
||||
pub fn deref_addr_ptr<T>(&self, addr: u64, outptr: *mut T, output_len_as_byte: u64) {
|
||||
let code = DriverAction::DereferenceAddress.get_code();
|
||||
let mut input = InputData {
|
||||
deref_addr: DerefAddr {
|
||||
addr,
|
||||
size: output_len_as_byte,
|
||||
},
|
||||
};
|
||||
self.windows_ffi.device_io_raw(
|
||||
code,
|
||||
&mut input as *mut _ as *mut c_void,
|
||||
size_of_val(&input) as DWORD,
|
||||
outptr as *mut c_void,
|
||||
output_len_as_byte as DWORD,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn get_unicode_string(&self, unicode_str_addr: u64) -> BoxResult<String> {
|
||||
if unicode_str_addr == 0 {
|
||||
return Err("Not a valid address".into());
|
||||
}
|
||||
|
||||
let mut strlen = 0u16;
|
||||
let mut capacity = 0u16;
|
||||
let mut bufaddr = 0u64;
|
||||
let buffer_ptr =
|
||||
unicode_str_addr + self.pdb_store.get_offset_r("_UNICODE_STRING.Buffer")?;
|
||||
let capacity_addr = unicode_str_addr
|
||||
+ self
|
||||
.pdb_store
|
||||
.get_offset_r("_UNICODE_STRING.MaximumLength")?;
|
||||
|
||||
self.deref_addr(unicode_str_addr, &mut strlen);
|
||||
self.deref_addr(capacity_addr, &mut capacity);
|
||||
self.deref_addr(buffer_ptr, &mut bufaddr);
|
||||
|
||||
if bufaddr == 0 || strlen > capacity || strlen == 0 || strlen % 2 != 0 {
|
||||
return Err("Unicode string is empty".into());
|
||||
}
|
||||
|
||||
let mut buf = vec![0u16; (strlen / 2) as usize];
|
||||
self.deref_addr_ptr(bufaddr, buf.as_mut_ptr(), strlen as u64);
|
||||
// TODO: BUG with deref_array, len is wrong,
|
||||
// >> the size of vector is strlen / 2
|
||||
// >> the size to dereference is strlen
|
||||
// XXX: use Vec<u8> and turn to Vec<u16>
|
||||
// let buf: Vec<u16> = self.deref_array(&Address::from_base(bufaddr), (strlen / 2) as u64);
|
||||
|
||||
Ok(String::from_utf16(&buf)?)
|
||||
}
|
||||
|
||||
pub fn get_nonpaged_range(&self, ntosbase: &Address) -> BoxResult<[Address; 2]> {
|
||||
// TODO: Add support for other Windows version here
|
||||
match self.windows_ffi.short_version {
|
||||
WindowsVersion::WindowsFastRing => {
|
||||
let mistate = ntosbase.clone() + self.pdb_store.get_offset_r("MiState")?;
|
||||
let path_first_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeNonPagedPool",
|
||||
"NonPagedPoolFirstVa",
|
||||
]
|
||||
.join(".");
|
||||
let path_last_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeNonPagedPool",
|
||||
"NonPagedPoolLastVa",
|
||||
]
|
||||
.join(".");
|
||||
let first_va = Address::from_base(self.decompose(&mistate, &path_first_va)?);
|
||||
let last_va = Address::from_base(self.decompose(&mistate, &path_last_va)?);
|
||||
Ok([first_va, last_va])
|
||||
}
|
||||
WindowsVersion::Windows10_2019 | WindowsVersion::Windows10_2018 => {
|
||||
let mistate = ntosbase.clone() + self.pdb_store.get_offset_r("MiState")?;
|
||||
let path_first_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeInformation",
|
||||
"NonPagedPoolFirstVa",
|
||||
]
|
||||
.join(".");
|
||||
let path_last_va: String = vec![
|
||||
"_MI_SYSTEM_INFORMATION",
|
||||
"Hardware",
|
||||
"SystemNodeInformation",
|
||||
"NonPagedPoolLastVa",
|
||||
]
|
||||
.join(".");
|
||||
let first_va = Address::from_base(self.decompose(&mistate, &path_first_va)?);
|
||||
let last_va = Address::from_base(self.decompose(&mistate, &path_last_va)?);
|
||||
Ok([first_va, last_va])
|
||||
}
|
||||
WindowsVersion::Windows7 => {
|
||||
let path_first_va =
|
||||
ntosbase.clone() + self.pdb_store.get_offset_r("MmNonPagedPoolStart")?;
|
||||
let path_last_va =
|
||||
ntosbase.clone() + self.pdb_store.get_offset_r("MiNonPagedPoolEnd")?;
|
||||
let first_va = Address::from_base(self.deref_addr_new(path_first_va.address()));
|
||||
let last_va = Address::from_base(self.deref_addr_new(path_last_va.address()));
|
||||
Ok([first_va, last_va])
|
||||
}
|
||||
_ => Err("Windows version for nonpaged pool algorithm is not implemented".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,137 +1,184 @@
|
||||
use crate::pdb_store::PdbStore;
|
||||
use crate::windows::WindowsVersion;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct OffsetData {
|
||||
eprocess_name_offset: u64,
|
||||
eprocess_link_offset: u64,
|
||||
list_blink_offset: u64,
|
||||
process_head_offset: u64,
|
||||
mistate_offset: u64,
|
||||
hardware_offset: u64,
|
||||
system_node_offset: u64,
|
||||
first_va_offset: u64,
|
||||
last_va_offset: u64,
|
||||
large_page_table_offset: u64,
|
||||
large_page_size_offset: u64,
|
||||
pool_chunk_size: u64,
|
||||
}
|
||||
|
||||
// TODO: Move to WindowsScanStrategy and return the corresponding struct base on Windows version
|
||||
impl OffsetData {
|
||||
pub fn new(pdb_store: &PdbStore, windows_version: WindowsVersion) -> Self {
|
||||
// TODO: Fix the backend so that only neccessary fields are used
|
||||
// This is too much, most of the functionality has been move to the frontend
|
||||
match windows_version {
|
||||
WindowsVersion::WindowsFastRing => Self {
|
||||
eprocess_name_offset: pdb_store.get_offset("_EPROCESS.ImageFileName").unwrap_or(0u64),
|
||||
eprocess_link_offset: pdb_store.get_offset("_EPROCESS.ActiveProcessLinks").unwrap_or(0u64),
|
||||
list_blink_offset: pdb_store.get_offset("_LIST_ENTRY.Blink").unwrap_or(0u64),
|
||||
process_head_offset: pdb_store.get_offset("PsActiveProcessHead").unwrap_or(0u64),
|
||||
mistate_offset: pdb_store.get_offset("MiState").unwrap_or(0u64),
|
||||
hardware_offset: pdb_store.get_offset("_MI_SYSTEM_INFORMATION.Hardware").unwrap_or(0u64),
|
||||
system_node_offset: pdb_store.get_offset("_MI_HARDWARE_STATE.SystemNodeNonPagedPool").unwrap_or(0u64),
|
||||
first_va_offset: pdb_store.get_offset("_MI_SYSTEM_NODE_NONPAGED_POOL.NonPagedPoolFirstVa").unwrap_or(0u64),
|
||||
last_va_offset: pdb_store.get_offset("_MI_SYSTEM_NODE_NONPAGED_POOL.NonPagedPoolLastVa").unwrap_or(0u64),
|
||||
large_page_table_offset: pdb_store.get_offset("PoolBigPageTable").unwrap_or(0u64),
|
||||
large_page_size_offset: pdb_store.get_offset("PoolBigPageTableSize").unwrap_or(0u64),
|
||||
pool_chunk_size: pdb_store.get_offset("_POOL_HEADER.struct_size").unwrap_or(0u64),
|
||||
},
|
||||
WindowsVersion::Windows10_2019 |
|
||||
WindowsVersion::Windows10_2018 => Self {
|
||||
eprocess_name_offset: pdb_store.get_offset("_EPROCESS.ImageFileName").unwrap_or(0u64),
|
||||
eprocess_link_offset: pdb_store.get_offset("_EPROCESS.ActiveProcessLinks").unwrap_or(0u64),
|
||||
list_blink_offset: pdb_store.get_offset("_LIST_ENTRY.Blink").unwrap_or(0u64),
|
||||
process_head_offset: pdb_store.get_offset("PsActiveProcessHead").unwrap_or(0u64),
|
||||
mistate_offset: pdb_store.get_offset("MiState").unwrap_or(0u64),
|
||||
hardware_offset: pdb_store.get_offset("_MI_SYSTEM_INFORMATION.Hardware").unwrap_or(0u64),
|
||||
system_node_offset: pdb_store.get_offset("_MI_HARDWARE_STATE.SystemNodeInformation").unwrap_or(0u64),
|
||||
first_va_offset: pdb_store.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolFirstVa").unwrap_or(0u64),
|
||||
last_va_offset: pdb_store.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolLastVa").unwrap_or(0u64),
|
||||
large_page_table_offset: pdb_store.get_offset("PoolBigPageTable").unwrap_or(0u64),
|
||||
large_page_size_offset: pdb_store.get_offset("PoolBigPageTableSize").unwrap_or(0u64),
|
||||
pool_chunk_size: pdb_store.get_offset("_POOL_HEADER.struct_size").unwrap_or(0u64),
|
||||
},
|
||||
WindowsVersion::Windows7 => Self {
|
||||
eprocess_name_offset: pdb_store.get_offset("_EPROCESS.ImageFileName").unwrap_or(0u64),
|
||||
eprocess_link_offset: pdb_store.get_offset("_EPROCESS.ActiveProcessLinks").unwrap_or(0u64),
|
||||
list_blink_offset: pdb_store.get_offset("_LIST_ENTRY.Blink").unwrap_or(0u64),
|
||||
process_head_offset: pdb_store.get_offset("PsActiveProcessHead").unwrap_or(0u64),
|
||||
mistate_offset: pdb_store.get_offset("MiState").unwrap_or(0u64),
|
||||
hardware_offset: pdb_store.get_offset("_MI_SYSTEM_INFORMATION.Hardware").unwrap_or(0u64),
|
||||
system_node_offset: pdb_store.get_offset("_MI_HARDWARE_STATE.SystemNodeInformation").unwrap_or(0u64),
|
||||
first_va_offset: pdb_store.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolFirstVa").unwrap_or(0u64),
|
||||
last_va_offset: pdb_store.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolLastVa").unwrap_or(0u64),
|
||||
large_page_table_offset: pdb_store.get_offset("PoolBigPageTable").unwrap_or(0u64),
|
||||
large_page_size_offset: pdb_store.get_offset("PoolBigPageTableSize").unwrap_or(0u64),
|
||||
pool_chunk_size: pdb_store.get_offset("_POOL_HEADER.struct_size").unwrap_or(0u64),
|
||||
},
|
||||
// TODO: Add other version of Windows here
|
||||
// TODO: Warn user of unknown windows version, because BSOD will occur
|
||||
_ => Self {
|
||||
eprocess_name_offset: 0u64,
|
||||
eprocess_link_offset: 0u64,
|
||||
list_blink_offset: 0u64,
|
||||
process_head_offset: 0u64,
|
||||
mistate_offset: 0u64,
|
||||
hardware_offset: 0u64,
|
||||
system_node_offset: 0u64,
|
||||
first_va_offset: 0u64,
|
||||
last_va_offset: 0u64,
|
||||
large_page_table_offset: 0u64,
|
||||
large_page_size_offset: 0u64,
|
||||
pool_chunk_size: 0u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct DerefAddr {
|
||||
pub addr: u64,
|
||||
pub size: u64
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct ScanPoolData {
|
||||
pub start: u64,
|
||||
pub end: u64,
|
||||
pub tag: u32
|
||||
}
|
||||
|
||||
impl ScanPoolData{
|
||||
pub fn new(arr: &[u64; 2], tag: &[u8; 4]) -> Self {
|
||||
Self {
|
||||
start: arr[0],
|
||||
end: arr[1],
|
||||
tag: u32::from_le_bytes(*tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct HideProcess {
|
||||
pub name: [u8; 15],
|
||||
pub size: u64
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub union InputData {
|
||||
pub offset_value: OffsetData,
|
||||
pub deref_addr: DerefAddr,
|
||||
pub scan_range: ScanPoolData,
|
||||
pub hide_process: HideProcess,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct Nothing; // for empty data
|
||||
|
||||
#[repr(C)]
|
||||
pub union OutputData {
|
||||
pub nothing: Nothing,
|
||||
}
|
||||
use crate::pdb_store::PdbStore;
|
||||
use crate::windows::WindowsVersion;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct OffsetData {
|
||||
eprocess_name_offset: u64,
|
||||
eprocess_link_offset: u64,
|
||||
list_blink_offset: u64,
|
||||
process_head_offset: u64,
|
||||
mistate_offset: u64,
|
||||
hardware_offset: u64,
|
||||
system_node_offset: u64,
|
||||
first_va_offset: u64,
|
||||
last_va_offset: u64,
|
||||
large_page_table_offset: u64,
|
||||
large_page_size_offset: u64,
|
||||
pool_chunk_size: u64,
|
||||
}
|
||||
|
||||
// TODO: Move to WindowsScanStrategy and return the corresponding struct base on Windows version
|
||||
impl OffsetData {
|
||||
pub fn new(pdb_store: &PdbStore, windows_version: WindowsVersion) -> Self {
|
||||
// TODO: Fix the backend so that only neccessary fields are used
|
||||
// This is too much, most of the functionality has been move to the frontend
|
||||
match windows_version {
|
||||
WindowsVersion::WindowsFastRing => Self {
|
||||
eprocess_name_offset: pdb_store
|
||||
.get_offset("_EPROCESS.ImageFileName")
|
||||
.unwrap_or(0u64),
|
||||
eprocess_link_offset: pdb_store
|
||||
.get_offset("_EPROCESS.ActiveProcessLinks")
|
||||
.unwrap_or(0u64),
|
||||
list_blink_offset: pdb_store.get_offset("_LIST_ENTRY.Blink").unwrap_or(0u64),
|
||||
process_head_offset: pdb_store.get_offset("PsActiveProcessHead").unwrap_or(0u64),
|
||||
mistate_offset: pdb_store.get_offset("MiState").unwrap_or(0u64),
|
||||
hardware_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_INFORMATION.Hardware")
|
||||
.unwrap_or(0u64),
|
||||
system_node_offset: pdb_store
|
||||
.get_offset("_MI_HARDWARE_STATE.SystemNodeNonPagedPool")
|
||||
.unwrap_or(0u64),
|
||||
first_va_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_NODE_NONPAGED_POOL.NonPagedPoolFirstVa")
|
||||
.unwrap_or(0u64),
|
||||
last_va_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_NODE_NONPAGED_POOL.NonPagedPoolLastVa")
|
||||
.unwrap_or(0u64),
|
||||
large_page_table_offset: pdb_store.get_offset("PoolBigPageTable").unwrap_or(0u64),
|
||||
large_page_size_offset: pdb_store
|
||||
.get_offset("PoolBigPageTableSize")
|
||||
.unwrap_or(0u64),
|
||||
pool_chunk_size: pdb_store
|
||||
.get_offset("_POOL_HEADER.struct_size")
|
||||
.unwrap_or(0u64),
|
||||
},
|
||||
WindowsVersion::Windows10_2019 | WindowsVersion::Windows10_2018 => Self {
|
||||
eprocess_name_offset: pdb_store
|
||||
.get_offset("_EPROCESS.ImageFileName")
|
||||
.unwrap_or(0u64),
|
||||
eprocess_link_offset: pdb_store
|
||||
.get_offset("_EPROCESS.ActiveProcessLinks")
|
||||
.unwrap_or(0u64),
|
||||
list_blink_offset: pdb_store.get_offset("_LIST_ENTRY.Blink").unwrap_or(0u64),
|
||||
process_head_offset: pdb_store.get_offset("PsActiveProcessHead").unwrap_or(0u64),
|
||||
mistate_offset: pdb_store.get_offset("MiState").unwrap_or(0u64),
|
||||
hardware_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_INFORMATION.Hardware")
|
||||
.unwrap_or(0u64),
|
||||
system_node_offset: pdb_store
|
||||
.get_offset("_MI_HARDWARE_STATE.SystemNodeInformation")
|
||||
.unwrap_or(0u64),
|
||||
first_va_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolFirstVa")
|
||||
.unwrap_or(0u64),
|
||||
last_va_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolLastVa")
|
||||
.unwrap_or(0u64),
|
||||
large_page_table_offset: pdb_store.get_offset("PoolBigPageTable").unwrap_or(0u64),
|
||||
large_page_size_offset: pdb_store
|
||||
.get_offset("PoolBigPageTableSize")
|
||||
.unwrap_or(0u64),
|
||||
pool_chunk_size: pdb_store
|
||||
.get_offset("_POOL_HEADER.struct_size")
|
||||
.unwrap_or(0u64),
|
||||
},
|
||||
WindowsVersion::Windows7 => Self {
|
||||
eprocess_name_offset: pdb_store
|
||||
.get_offset("_EPROCESS.ImageFileName")
|
||||
.unwrap_or(0u64),
|
||||
eprocess_link_offset: pdb_store
|
||||
.get_offset("_EPROCESS.ActiveProcessLinks")
|
||||
.unwrap_or(0u64),
|
||||
list_blink_offset: pdb_store.get_offset("_LIST_ENTRY.Blink").unwrap_or(0u64),
|
||||
process_head_offset: pdb_store.get_offset("PsActiveProcessHead").unwrap_or(0u64),
|
||||
mistate_offset: pdb_store.get_offset("MiState").unwrap_or(0u64),
|
||||
hardware_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_INFORMATION.Hardware")
|
||||
.unwrap_or(0u64),
|
||||
system_node_offset: pdb_store
|
||||
.get_offset("_MI_HARDWARE_STATE.SystemNodeInformation")
|
||||
.unwrap_or(0u64),
|
||||
first_va_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolFirstVa")
|
||||
.unwrap_or(0u64),
|
||||
last_va_offset: pdb_store
|
||||
.get_offset("_MI_SYSTEM_NODE_INFORMATION.NonPagedPoolLastVa")
|
||||
.unwrap_or(0u64),
|
||||
large_page_table_offset: pdb_store.get_offset("PoolBigPageTable").unwrap_or(0u64),
|
||||
large_page_size_offset: pdb_store
|
||||
.get_offset("PoolBigPageTableSize")
|
||||
.unwrap_or(0u64),
|
||||
pool_chunk_size: pdb_store
|
||||
.get_offset("_POOL_HEADER.struct_size")
|
||||
.unwrap_or(0u64),
|
||||
},
|
||||
// TODO: Add other version of Windows here
|
||||
// TODO: Warn user of unknown windows version, because BSOD will occur
|
||||
_ => Self {
|
||||
eprocess_name_offset: 0u64,
|
||||
eprocess_link_offset: 0u64,
|
||||
list_blink_offset: 0u64,
|
||||
process_head_offset: 0u64,
|
||||
mistate_offset: 0u64,
|
||||
hardware_offset: 0u64,
|
||||
system_node_offset: 0u64,
|
||||
first_va_offset: 0u64,
|
||||
last_va_offset: 0u64,
|
||||
large_page_table_offset: 0u64,
|
||||
large_page_size_offset: 0u64,
|
||||
pool_chunk_size: 0u64,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct DerefAddr {
|
||||
pub addr: u64,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct ScanPoolData {
|
||||
pub start: u64,
|
||||
pub end: u64,
|
||||
pub tag: u32,
|
||||
}
|
||||
|
||||
impl ScanPoolData {
|
||||
pub fn new(arr: &[u64; 2], tag: &[u8; 4]) -> Self {
|
||||
Self {
|
||||
start: arr[0],
|
||||
end: arr[1],
|
||||
tag: u32::from_le_bytes(*tag),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct HideProcess {
|
||||
pub name: [u8; 15],
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
pub union InputData {
|
||||
pub offset_value: OffsetData,
|
||||
pub deref_addr: DerefAddr,
|
||||
pub scan_range: ScanPoolData,
|
||||
pub hide_process: HideProcess,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub struct Nothing; // for empty data
|
||||
|
||||
#[repr(C)]
|
||||
pub union OutputData {
|
||||
pub nothing: Nothing,
|
||||
}
|
||||
|
1100
src/lib.rs
1100
src/lib.rs
File diff suppressed because it is too large
Load Diff
@ -1,9 +1,9 @@
|
||||
use std::error::Error;
|
||||
use std::str::{from_utf8};
|
||||
use serde_json::{json, Value};
|
||||
use crate::driver_state::DriverState;
|
||||
use crate::address::Address;
|
||||
use crate::driver_state::DriverState;
|
||||
use crate::{get_device_type, to_epoch};
|
||||
use serde_json::{json, Value};
|
||||
use std::error::Error;
|
||||
use std::str::from_utf8;
|
||||
|
||||
type BoxResult<T> = Result<T, Box<dyn Error>>;
|
||||
|
||||
@ -29,26 +29,29 @@ pub fn make_eprocess(d: &DriverState, a: &Address) -> BoxResult<Value> {
|
||||
let pid: u64 = d.decompose(a, "_EPROCESS.UniqueProcessId")?;
|
||||
let ppid: u64 = d.decompose(a, "_EPROCESS.InheritedFromUniqueProcessId")?;
|
||||
let image_name: Vec<u8> = d.decompose_array(a, "_EPROCESS.ImageFileName", 15)?;
|
||||
let filename_ptr = d.address_of(a, "_EPROCESS.ImageFilePointer.FileName")
|
||||
.unwrap_or(0); // ImageFilePointer is after Windows 10 Anniversary
|
||||
let filename_ptr = d
|
||||
.address_of(a, "_EPROCESS.ImageFilePointer.FileName")
|
||||
.unwrap_or(0); // ImageFilePointer is after Windows 10 Anniversary
|
||||
|
||||
let eprocess_name =
|
||||
if let Ok(name) = from_utf8(&image_name) {
|
||||
name.to_string().trim_end_matches(char::from(0)).to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
let binary_path = d.get_unicode_string(filename_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let eprocess_name = if let Ok(name) = from_utf8(&image_name) {
|
||||
name.to_string().trim_end_matches(char::from(0)).to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
let binary_path = d.get_unicode_string(filename_ptr).unwrap_or("".to_string());
|
||||
|
||||
let thread_head = d.address_of(a, "_EPROCESS.ThreadListHead")?;
|
||||
let threads: Vec<Value> =
|
||||
make_list_entry(d, Address::from_base(thread_head), "_ETHREAD.ThreadListEntry")
|
||||
.unwrap_or(Vec::new()).iter()
|
||||
.map(|thread_addr| {
|
||||
make_ethread(d, thread_addr)
|
||||
.unwrap_or(json!({})) // unlikely
|
||||
}).collect();
|
||||
let threads: Vec<Value> = make_list_entry(
|
||||
d,
|
||||
Address::from_base(thread_head),
|
||||
"_ETHREAD.ThreadListEntry",
|
||||
)
|
||||
.unwrap_or(Vec::new())
|
||||
.iter()
|
||||
.map(|thread_addr| {
|
||||
make_ethread(d, thread_addr).unwrap_or(json!({})) // unlikely
|
||||
})
|
||||
.collect();
|
||||
|
||||
let c_t = to_epoch(createtime);
|
||||
let e_t = to_epoch(exittime);
|
||||
@ -77,12 +80,13 @@ pub fn make_ethread(d: &DriverState, a: &Address) -> BoxResult<Value> {
|
||||
// let exittime: u64 = d.decompose(a, "_ETHREAD.ExitTime")?;
|
||||
let pid: u64 = d.decompose(a, "_ETHREAD.Cid.UniqueProcess")?;
|
||||
let tid: u64 = d.decompose(a, "_ETHREAD.Cid.UniqueThread")?;
|
||||
let name_ptr: u64 = d.address_of(a, "_ETHREAD.ThreadName")
|
||||
.unwrap_or(0); // ThreadName is after Windows 10 Anniversary
|
||||
let name_ptr: u64 = d.address_of(a, "_ETHREAD.ThreadName").unwrap_or(0); // ThreadName is after Windows 10 Anniversary
|
||||
|
||||
let thread_name =
|
||||
if let Ok(name) = d.get_unicode_string(name_ptr) { name }
|
||||
else { "".to_string() };
|
||||
let thread_name = if let Ok(name) = d.get_unicode_string(name_ptr) {
|
||||
name
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
|
||||
// let c_t = to_epoch(createtime);
|
||||
// let e_t = to_epoch(exittime);
|
||||
@ -114,12 +118,13 @@ pub fn make_driver(d: &DriverState, a: &Address) -> BoxResult<Value> {
|
||||
let unload: u64 = d.decompose(a, "_DRIVER_OBJECT.DriverUnload")?;
|
||||
let size: u64 = d.decompose(a, "_DRIVER_OBJECT.DriverSize")?;
|
||||
|
||||
let devicename = d.get_unicode_string(devicename_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let hardware = d.get_unicode_string(hardware_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let servicekey = d.get_unicode_string(servicekey_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let devicename = d
|
||||
.get_unicode_string(devicename_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let hardware = d.get_unicode_string(hardware_ptr).unwrap_or("".to_string());
|
||||
let servicekey = d
|
||||
.get_unicode_string(servicekey_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
|
||||
// device tree walk
|
||||
let devices = {
|
||||
@ -134,7 +139,8 @@ pub fn make_driver(d: &DriverState, a: &Address) -> BoxResult<Value> {
|
||||
let mut attached_devices: Vec<Value> = Vec::new();
|
||||
while attached_ptr != 0 {
|
||||
let attached = Address::from_base(attached_ptr);
|
||||
let attached_device_type: u32 = d.decompose(&attached, "_DEVICE_OBJECT.DeviceType")?;
|
||||
let attached_device_type: u32 =
|
||||
d.decompose(&attached, "_DEVICE_OBJECT.DeviceType")?;
|
||||
attached_devices.push(json!({
|
||||
"address": format!("0x{:x}", attached_ptr),
|
||||
"type": "_DEVICE_OBJECT",
|
||||
@ -177,20 +183,27 @@ pub fn make_ldr(d: &DriverState, a: &Address) -> BoxResult<Value> {
|
||||
let fullname_ptr = d.address_of(a, "_LDR_DATA_TABLE_ENTRY.FullDllName")?;
|
||||
let basename_ptr = d.address_of(a, "_LDR_DATA_TABLE_ENTRY.BaseDllName")?;
|
||||
|
||||
let fullname = d.get_unicode_string(fullname_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let basename = d.get_unicode_string(basename_ptr)
|
||||
.unwrap_or("".to_string());
|
||||
let fullname = d.get_unicode_string(fullname_ptr).unwrap_or("".to_string());
|
||||
let basename = d.get_unicode_string(basename_ptr).unwrap_or("".to_string());
|
||||
|
||||
let ldr_load: Vec<String> =
|
||||
make_list_entry(d, a.clone(), "_LDR_DATA_TABLE_ENTRY.InLoadOrderLinks")?
|
||||
.iter().map(|x| format!("0x{:x}", x.address())).collect();
|
||||
.iter()
|
||||
.map(|x| format!("0x{:x}", x.address()))
|
||||
.collect();
|
||||
let ldr_mem: Vec<String> =
|
||||
make_list_entry(d, a.clone(), "_LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks")?
|
||||
.iter().map(|x| format!("0x{:x}", x.address())).collect();
|
||||
let ldr_init: Vec<String> =
|
||||
make_list_entry(d, a.clone(), "_LDR_DATA_TABLE_ENTRY.InInitializationOrderLinks")?
|
||||
.iter().map(|x| format!("0x{:x}", x.address())).collect();
|
||||
.iter()
|
||||
.map(|x| format!("0x{:x}", x.address()))
|
||||
.collect();
|
||||
let ldr_init: Vec<String> = make_list_entry(
|
||||
d,
|
||||
a.clone(),
|
||||
"_LDR_DATA_TABLE_ENTRY.InInitializationOrderLinks",
|
||||
)?
|
||||
.iter()
|
||||
.map(|x| format!("0x{:x}", x.address()))
|
||||
.collect();
|
||||
|
||||
Ok(json!({
|
||||
"address": format!("0x{:x}", a.address()),
|
||||
|
1036
src/pdb_store.rs
1036
src/pdb_store.rs
File diff suppressed because it is too large
Load Diff
644
src/windows.rs
644
src/windows.rs
@ -1,295 +1,349 @@
|
||||
use std::ffi::{c_void, CString};
|
||||
use std::mem::{transmute, size_of_val};
|
||||
use std::ptr::null_mut;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use widestring::U16CString;
|
||||
|
||||
use winapi::shared::ntdef::*;
|
||||
use winapi::shared::minwindef::{DWORD, HKEY, HMODULE};
|
||||
use winapi::um::winnt::{
|
||||
SE_PRIVILEGE_ENABLED, TOKEN_PRIVILEGES, TOKEN_ADJUST_PRIVILEGES, LUID_AND_ATTRIBUTES,
|
||||
REG_DWORD, REG_SZ, REG_OPTION_NON_VOLATILE, KEY_WRITE,
|
||||
PRTL_OSVERSIONINFOW, OSVERSIONINFOW,
|
||||
FILE_ATTRIBUTE_NORMAL, GENERIC_READ, GENERIC_WRITE
|
||||
};
|
||||
|
||||
use winapi::um::ioapiset::{DeviceIoControl};
|
||||
use winapi::um::errhandlingapi::{GetLastError};
|
||||
use winapi::um::fileapi::{CreateFileA, CREATE_ALWAYS};
|
||||
use winapi::um::handleapi::{INVALID_HANDLE_VALUE, CloseHandle};
|
||||
use winapi::um::libloaderapi::{LoadLibraryA, GetProcAddress};
|
||||
use winapi::um::processthreadsapi::{GetCurrentProcess, OpenProcessToken};
|
||||
use winapi::um::sysinfoapi::{GetTickCount64};
|
||||
use winapi::um::securitybaseapi::{AdjustTokenPrivileges};
|
||||
use winapi::um::winbase::{LookupPrivilegeValueA};
|
||||
use winapi::um::winreg::{RegCreateKeyExA, RegSetValueExA, RegCloseKey, HKEY_LOCAL_MACHINE};
|
||||
|
||||
const STR_DRIVER_REGISTRY_PATH: &str = "\\Registry\\Machine\\System\\CurrentControlSet\\Services\\lpus";
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
|
||||
pub enum WindowsVersion {
|
||||
Windows7,
|
||||
Windows8,
|
||||
Windows10Legacy,
|
||||
Windows10_2015,
|
||||
Windows10_2016,
|
||||
Windows10_2017,
|
||||
Windows10_2018,
|
||||
Windows10_2019,
|
||||
Windows10_2020,
|
||||
WindowsFastRing,
|
||||
WindowsUnknown
|
||||
}
|
||||
|
||||
impl WindowsVersion {
|
||||
pub fn not_supported(self) -> bool {
|
||||
match self {
|
||||
WindowsVersion::Windows10Legacy |
|
||||
WindowsVersion::Windows10_2015 |
|
||||
WindowsVersion::Windows10_2016 |
|
||||
WindowsVersion::Windows10_2017 |
|
||||
WindowsVersion::Windows8 |
|
||||
WindowsVersion::WindowsUnknown => true,
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
pub fn is_supported(self) -> bool {
|
||||
!self.not_supported()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct WindowsFFI {
|
||||
pub version_info: OSVERSIONINFOW,
|
||||
pub short_version: WindowsVersion,
|
||||
driver_handle: HANDLE,
|
||||
ntdll: HMODULE,
|
||||
nt_load_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS,
|
||||
nt_unload_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS,
|
||||
rtl_init_unicode_str: extern "system" fn(PUNICODE_STRING, PCWSTR),
|
||||
rtl_get_version: extern "system" fn(PRTL_OSVERSIONINFOW) -> NTSTATUS,
|
||||
}
|
||||
|
||||
impl WindowsFFI {
|
||||
pub fn new() -> Self {
|
||||
let str_ntdll = CString::new("ntdll").unwrap();
|
||||
let str_nt_load_driver = CString::new("NtLoadDriver").unwrap();
|
||||
let str_nt_unload_driver = CString::new("NtUnloadDriver").unwrap();
|
||||
let str_rtl_init_unicode_str = CString::new("RtlInitUnicodeString").unwrap();
|
||||
let str_rtl_get_version = CString::new("RtlGetVersion").unwrap();
|
||||
let str_se_load_driver_privilege = CString::new("SeLoadDriverPrivilege").unwrap();
|
||||
|
||||
let str_driver_path = CString::new("\\SystemRoot\\System32\\DRIVERS\\lpus.sys").unwrap();
|
||||
let str_registry_path = CString::new("System\\CurrentControlSet\\Services\\lpus").unwrap();
|
||||
let str_type = CString::new("Type").unwrap();
|
||||
let str_error_control = CString::new("ErrorControl").unwrap();
|
||||
let str_start = CString::new("Start").unwrap();
|
||||
let str_image_path = CString::new("ImagePath").unwrap();
|
||||
|
||||
let mut version_info = OSVERSIONINFOW {
|
||||
dwOSVersionInfoSize: 0u32,
|
||||
dwMajorVersion: 0u32,
|
||||
dwMinorVersion: 0u32,
|
||||
dwBuildNumber: 0u32,
|
||||
dwPlatformId: 0u32,
|
||||
szCSDVersion: [0u16; 128],
|
||||
};
|
||||
|
||||
let ntdll: HMODULE;
|
||||
let nt_load_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS;
|
||||
let nt_unload_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS;
|
||||
let rtl_init_unicode_str: extern "system" fn(PUNICODE_STRING, PCWSTR);
|
||||
let rtl_get_version: extern "system" fn(PRTL_OSVERSIONINFOW) -> NTSTATUS;
|
||||
|
||||
// some pointer unsafe C code
|
||||
unsafe {
|
||||
ntdll = LoadLibraryA(str_ntdll.as_ptr());
|
||||
let nt_load_driver_ = GetProcAddress(ntdll, str_nt_load_driver.as_ptr());
|
||||
let nt_unload_driver_ = GetProcAddress(ntdll, str_nt_unload_driver.as_ptr());
|
||||
let rtl_init_unicode_str_ = GetProcAddress(ntdll, str_rtl_init_unicode_str.as_ptr());
|
||||
let rtl_get_version_ = GetProcAddress(ntdll, str_rtl_get_version.as_ptr());
|
||||
|
||||
nt_load_driver = transmute(nt_load_driver_);
|
||||
nt_unload_driver = transmute(nt_unload_driver_);
|
||||
rtl_init_unicode_str = transmute(rtl_init_unicode_str_);
|
||||
rtl_get_version = transmute(rtl_get_version_);
|
||||
|
||||
// setup registry
|
||||
let mut registry_key: HKEY = null_mut();
|
||||
RegCreateKeyExA(
|
||||
HKEY_LOCAL_MACHINE, str_registry_path.as_ptr(),
|
||||
0, null_mut(),
|
||||
REG_OPTION_NON_VOLATILE, KEY_WRITE,
|
||||
null_mut(), &mut registry_key, null_mut()
|
||||
);
|
||||
let type_value: [u8; 4] = 1u32.to_le_bytes();
|
||||
let error_control_value: [u8; 4] = 1u32.to_le_bytes();
|
||||
let start_value: [u8; 4] = 3u32.to_le_bytes();
|
||||
let registry_values = [
|
||||
(str_type.as_ptr(), REG_DWORD, type_value.as_ptr(), 4),
|
||||
(str_error_control.as_ptr(), REG_DWORD, error_control_value.as_ptr(), 4),
|
||||
(str_start.as_ptr(), REG_DWORD, start_value.as_ptr(), 4),
|
||||
(str_image_path.as_ptr(), REG_SZ,
|
||||
str_driver_path.as_ptr() as *const u8, str_driver_path.to_bytes().len() + 1)
|
||||
];
|
||||
for &(key, keytype, value_ptr, size_in_bytes) in ®istry_values {
|
||||
RegSetValueExA(
|
||||
registry_key, key, 0,
|
||||
keytype, value_ptr, size_in_bytes as u32
|
||||
);
|
||||
}
|
||||
RegCloseKey(registry_key);
|
||||
|
||||
// Setup privilege SeLoadDriverPrivilege
|
||||
let mut token_handle: HANDLE = null_mut();
|
||||
let mut luid = LUID::default();
|
||||
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &mut token_handle);
|
||||
LookupPrivilegeValueA(null_mut(), str_se_load_driver_privilege.as_ptr(), &mut luid);
|
||||
let mut new_token_state = TOKEN_PRIVILEGES {
|
||||
PrivilegeCount: 1,
|
||||
Privileges: [LUID_AND_ATTRIBUTES {
|
||||
Luid: luid,
|
||||
Attributes: SE_PRIVILEGE_ENABLED
|
||||
}]
|
||||
};
|
||||
AdjustTokenPrivileges(
|
||||
token_handle, 0, &mut new_token_state, 16, null_mut(), null_mut());
|
||||
CloseHandle(token_handle);
|
||||
}
|
||||
|
||||
rtl_get_version(&mut version_info);
|
||||
|
||||
let short_version = match version_info.dwBuildNumber {
|
||||
// 2600 => WindowsVersion::WindowsXP,
|
||||
// 6000 | 6001 | 6002 => WindowsVersion::WindowsVista,
|
||||
7600 | 7601 => WindowsVersion::Windows7,
|
||||
9200 | 9600 => WindowsVersion::Windows8,
|
||||
10240 => WindowsVersion::Windows10Legacy,
|
||||
10586 => WindowsVersion::Windows10_2015,
|
||||
14393 => WindowsVersion::Windows10_2016,
|
||||
15063 | 16299 => WindowsVersion::Windows10_2017,
|
||||
17134 | 17763 => WindowsVersion::Windows10_2018,
|
||||
18363 | 18362 => WindowsVersion::Windows10_2019,
|
||||
19041 => WindowsVersion::Windows10_2020,
|
||||
x if x >= 19536 => WindowsVersion::WindowsFastRing,
|
||||
_ => WindowsVersion::WindowsUnknown
|
||||
};
|
||||
|
||||
Self {
|
||||
version_info,
|
||||
short_version,
|
||||
driver_handle: INVALID_HANDLE_VALUE,
|
||||
ntdll,
|
||||
nt_load_driver,
|
||||
nt_unload_driver,
|
||||
rtl_init_unicode_str,
|
||||
rtl_get_version
|
||||
}
|
||||
}
|
||||
|
||||
pub fn driver_loaded(self) -> bool {
|
||||
self.driver_handle != INVALID_HANDLE_VALUE
|
||||
}
|
||||
|
||||
pub fn load_driver(&mut self) -> NTSTATUS {
|
||||
// TODO: Move this to new()
|
||||
// If we move this function to new(), self.driver_handle will be init, and thus no mut here
|
||||
let str_driver_reg = U16CString::from_str(STR_DRIVER_REGISTRY_PATH).unwrap();
|
||||
let mut str_driver_reg_unicode = UNICODE_STRING::default();
|
||||
(self.rtl_init_unicode_str)(&mut str_driver_reg_unicode, str_driver_reg.as_ptr() as *const u16);
|
||||
let status = (self.nt_load_driver)(&mut str_driver_reg_unicode);
|
||||
|
||||
let filename = CString::new("\\\\.\\poolscanner").unwrap();
|
||||
let driver_file_handle: HANDLE = unsafe {
|
||||
CreateFileA(filename.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0, null_mut(), CREATE_ALWAYS,
|
||||
FILE_ATTRIBUTE_NORMAL, null_mut())
|
||||
};
|
||||
|
||||
if driver_file_handle == INVALID_HANDLE_VALUE {
|
||||
println!("Driver CreateFileA failed");
|
||||
}
|
||||
else {
|
||||
self.driver_handle = driver_file_handle;
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub fn unload_driver(&self) -> NTSTATUS {
|
||||
let str_driver_reg = U16CString::from_str(STR_DRIVER_REGISTRY_PATH).unwrap();
|
||||
let mut str_driver_reg_unicode = UNICODE_STRING::default();
|
||||
(self.rtl_init_unicode_str)(&mut str_driver_reg_unicode, str_driver_reg.as_ptr());
|
||||
(self.nt_unload_driver)(&mut str_driver_reg_unicode)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_build_number(&self) -> DWORD {
|
||||
self.version_info.dwBuildNumber
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn print_version(&self) {
|
||||
println!("Windows version: {}.{}.{} {:?}",
|
||||
self.version_info.dwMajorVersion,
|
||||
self.version_info.dwMinorVersion,
|
||||
self.version_info.dwBuildNumber,
|
||||
self.short_version
|
||||
);
|
||||
}
|
||||
|
||||
pub fn to_epoch(&self, filetime: u64) -> u64 {
|
||||
let windows_epoch_diff = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return 0;
|
||||
}
|
||||
let process_time_epoch = (filetime - windows_epoch_diff) / 10000;
|
||||
process_time_epoch
|
||||
}
|
||||
|
||||
pub fn valid_process_time(&self, filetime: u64) -> bool {
|
||||
// https://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/
|
||||
let windows_epoch_diff = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return false;
|
||||
}
|
||||
let system_up_time_ms = unsafe { GetTickCount64() };
|
||||
let process_time_epoch = (filetime - windows_epoch_diff) / 10000; // in milisecond
|
||||
let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).expect("Time went backwards").as_millis() as u64;
|
||||
let system_start_up_time_ms =
|
||||
now_ms - system_up_time_ms - (10 * 3600 * 1000/* 10 minutes penalty */);
|
||||
|
||||
if process_time_epoch < system_start_up_time_ms {
|
||||
false
|
||||
} else if process_time_epoch > now_ms {
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn device_io<T, E>(&self, code: DWORD, inbuf: &mut T, outbuf: &mut E) -> DWORD {
|
||||
self.device_io_raw(code,
|
||||
inbuf as *mut _ as *mut c_void, size_of_val(inbuf) as DWORD,
|
||||
outbuf as *mut _ as *mut c_void, size_of_val(outbuf) as DWORD)
|
||||
}
|
||||
|
||||
pub fn device_io_raw(&self, code: DWORD,
|
||||
input_ptr: *mut c_void, input_len: DWORD,
|
||||
output_ptr: *mut c_void, output_len: DWORD) -> DWORD {
|
||||
// println!("driver loaded: {}; device_io_code: {}", self.driver_loaded(), code);
|
||||
let mut bytes_returned: DWORD = 0;
|
||||
unsafe {
|
||||
let status = DeviceIoControl(self.driver_handle, code,
|
||||
input_ptr, input_len,
|
||||
output_ptr, output_len,
|
||||
&mut bytes_returned, null_mut());
|
||||
if status == 0 {
|
||||
println!("device io failed: last error {}", GetLastError());
|
||||
}
|
||||
};
|
||||
bytes_returned
|
||||
}
|
||||
}
|
||||
use std::ffi::{c_void, CString};
|
||||
use std::mem::{size_of_val, transmute};
|
||||
use std::ptr::null_mut;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use widestring::U16CString;
|
||||
|
||||
use winapi::shared::minwindef::{DWORD, HKEY, HMODULE};
|
||||
use winapi::shared::ntdef::*;
|
||||
use winapi::um::winnt::{
|
||||
FILE_ATTRIBUTE_NORMAL, GENERIC_READ, GENERIC_WRITE, KEY_WRITE, LUID_AND_ATTRIBUTES,
|
||||
OSVERSIONINFOW, PRTL_OSVERSIONINFOW, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ,
|
||||
SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES,
|
||||
};
|
||||
|
||||
use winapi::um::errhandlingapi::GetLastError;
|
||||
use winapi::um::fileapi::{CreateFileA, CREATE_ALWAYS};
|
||||
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
|
||||
use winapi::um::ioapiset::DeviceIoControl;
|
||||
use winapi::um::libloaderapi::{GetProcAddress, LoadLibraryA};
|
||||
use winapi::um::processthreadsapi::{GetCurrentProcess, OpenProcessToken};
|
||||
use winapi::um::securitybaseapi::AdjustTokenPrivileges;
|
||||
use winapi::um::sysinfoapi::GetTickCount64;
|
||||
use winapi::um::winbase::LookupPrivilegeValueA;
|
||||
use winapi::um::winreg::{RegCloseKey, RegCreateKeyExA, RegSetValueExA, HKEY_LOCAL_MACHINE};
|
||||
|
||||
const STR_DRIVER_REGISTRY_PATH: &str =
|
||||
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\lpus";
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
|
||||
pub enum WindowsVersion {
|
||||
Windows7,
|
||||
Windows8,
|
||||
Windows10Legacy,
|
||||
Windows10_2015,
|
||||
Windows10_2016,
|
||||
Windows10_2017,
|
||||
Windows10_2018,
|
||||
Windows10_2019,
|
||||
Windows10_2020,
|
||||
WindowsFastRing,
|
||||
WindowsUnknown,
|
||||
}
|
||||
|
||||
impl WindowsVersion {
|
||||
pub fn not_supported(self) -> bool {
|
||||
match self {
|
||||
WindowsVersion::Windows10Legacy
|
||||
| WindowsVersion::Windows10_2015
|
||||
| WindowsVersion::Windows10_2016
|
||||
| WindowsVersion::Windows10_2017
|
||||
| WindowsVersion::Windows8
|
||||
| WindowsVersion::WindowsUnknown => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
pub fn is_supported(self) -> bool {
|
||||
!self.not_supported()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct WindowsFFI {
|
||||
pub version_info: OSVERSIONINFOW,
|
||||
pub short_version: WindowsVersion,
|
||||
driver_handle: HANDLE,
|
||||
ntdll: HMODULE,
|
||||
nt_load_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS,
|
||||
nt_unload_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS,
|
||||
rtl_init_unicode_str: extern "system" fn(PUNICODE_STRING, PCWSTR),
|
||||
rtl_get_version: extern "system" fn(PRTL_OSVERSIONINFOW) -> NTSTATUS,
|
||||
}
|
||||
|
||||
impl WindowsFFI {
|
||||
pub fn new() -> Self {
|
||||
let str_ntdll = CString::new("ntdll").unwrap();
|
||||
let str_nt_load_driver = CString::new("NtLoadDriver").unwrap();
|
||||
let str_nt_unload_driver = CString::new("NtUnloadDriver").unwrap();
|
||||
let str_rtl_init_unicode_str = CString::new("RtlInitUnicodeString").unwrap();
|
||||
let str_rtl_get_version = CString::new("RtlGetVersion").unwrap();
|
||||
let str_se_load_driver_privilege = CString::new("SeLoadDriverPrivilege").unwrap();
|
||||
|
||||
let str_driver_path = CString::new("\\SystemRoot\\System32\\DRIVERS\\lpus.sys").unwrap();
|
||||
let str_registry_path = CString::new("System\\CurrentControlSet\\Services\\lpus").unwrap();
|
||||
let str_type = CString::new("Type").unwrap();
|
||||
let str_error_control = CString::new("ErrorControl").unwrap();
|
||||
let str_start = CString::new("Start").unwrap();
|
||||
let str_image_path = CString::new("ImagePath").unwrap();
|
||||
|
||||
let mut version_info = OSVERSIONINFOW {
|
||||
dwOSVersionInfoSize: 0u32,
|
||||
dwMajorVersion: 0u32,
|
||||
dwMinorVersion: 0u32,
|
||||
dwBuildNumber: 0u32,
|
||||
dwPlatformId: 0u32,
|
||||
szCSDVersion: [0u16; 128],
|
||||
};
|
||||
|
||||
let ntdll: HMODULE;
|
||||
let nt_load_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS;
|
||||
let nt_unload_driver: extern "system" fn(PUNICODE_STRING) -> NTSTATUS;
|
||||
let rtl_init_unicode_str: extern "system" fn(PUNICODE_STRING, PCWSTR);
|
||||
let rtl_get_version: extern "system" fn(PRTL_OSVERSIONINFOW) -> NTSTATUS;
|
||||
|
||||
// some pointer unsafe C code
|
||||
unsafe {
|
||||
ntdll = LoadLibraryA(str_ntdll.as_ptr());
|
||||
let nt_load_driver_ = GetProcAddress(ntdll, str_nt_load_driver.as_ptr());
|
||||
let nt_unload_driver_ = GetProcAddress(ntdll, str_nt_unload_driver.as_ptr());
|
||||
let rtl_init_unicode_str_ = GetProcAddress(ntdll, str_rtl_init_unicode_str.as_ptr());
|
||||
let rtl_get_version_ = GetProcAddress(ntdll, str_rtl_get_version.as_ptr());
|
||||
|
||||
nt_load_driver = transmute(nt_load_driver_);
|
||||
nt_unload_driver = transmute(nt_unload_driver_);
|
||||
rtl_init_unicode_str = transmute(rtl_init_unicode_str_);
|
||||
rtl_get_version = transmute(rtl_get_version_);
|
||||
|
||||
// setup registry
|
||||
let mut registry_key: HKEY = null_mut();
|
||||
RegCreateKeyExA(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
str_registry_path.as_ptr(),
|
||||
0,
|
||||
null_mut(),
|
||||
REG_OPTION_NON_VOLATILE,
|
||||
KEY_WRITE,
|
||||
null_mut(),
|
||||
&mut registry_key,
|
||||
null_mut(),
|
||||
);
|
||||
let type_value: [u8; 4] = 1u32.to_le_bytes();
|
||||
let error_control_value: [u8; 4] = 1u32.to_le_bytes();
|
||||
let start_value: [u8; 4] = 3u32.to_le_bytes();
|
||||
let registry_values = [
|
||||
(str_type.as_ptr(), REG_DWORD, type_value.as_ptr(), 4),
|
||||
(
|
||||
str_error_control.as_ptr(),
|
||||
REG_DWORD,
|
||||
error_control_value.as_ptr(),
|
||||
4,
|
||||
),
|
||||
(str_start.as_ptr(), REG_DWORD, start_value.as_ptr(), 4),
|
||||
(
|
||||
str_image_path.as_ptr(),
|
||||
REG_SZ,
|
||||
str_driver_path.as_ptr() as *const u8,
|
||||
str_driver_path.to_bytes().len() + 1,
|
||||
),
|
||||
];
|
||||
for &(key, keytype, value_ptr, size_in_bytes) in ®istry_values {
|
||||
RegSetValueExA(
|
||||
registry_key,
|
||||
key,
|
||||
0,
|
||||
keytype,
|
||||
value_ptr,
|
||||
size_in_bytes as u32,
|
||||
);
|
||||
}
|
||||
RegCloseKey(registry_key);
|
||||
|
||||
// Setup privilege SeLoadDriverPrivilege
|
||||
let mut token_handle: HANDLE = null_mut();
|
||||
let mut luid = LUID::default();
|
||||
OpenProcessToken(
|
||||
GetCurrentProcess(),
|
||||
TOKEN_ADJUST_PRIVILEGES,
|
||||
&mut token_handle,
|
||||
);
|
||||
LookupPrivilegeValueA(null_mut(), str_se_load_driver_privilege.as_ptr(), &mut luid);
|
||||
let mut new_token_state = TOKEN_PRIVILEGES {
|
||||
PrivilegeCount: 1,
|
||||
Privileges: [LUID_AND_ATTRIBUTES {
|
||||
Luid: luid,
|
||||
Attributes: SE_PRIVILEGE_ENABLED,
|
||||
}],
|
||||
};
|
||||
AdjustTokenPrivileges(
|
||||
token_handle,
|
||||
0,
|
||||
&mut new_token_state,
|
||||
16,
|
||||
null_mut(),
|
||||
null_mut(),
|
||||
);
|
||||
CloseHandle(token_handle);
|
||||
}
|
||||
|
||||
rtl_get_version(&mut version_info);
|
||||
|
||||
let short_version = match version_info.dwBuildNumber {
|
||||
// 2600 => WindowsVersion::WindowsXP,
|
||||
// 6000 | 6001 | 6002 => WindowsVersion::WindowsVista,
|
||||
7600 | 7601 => WindowsVersion::Windows7,
|
||||
9200 | 9600 => WindowsVersion::Windows8,
|
||||
10240 => WindowsVersion::Windows10Legacy,
|
||||
10586 => WindowsVersion::Windows10_2015,
|
||||
14393 => WindowsVersion::Windows10_2016,
|
||||
15063 | 16299 => WindowsVersion::Windows10_2017,
|
||||
17134 | 17763 => WindowsVersion::Windows10_2018,
|
||||
18363 | 18362 => WindowsVersion::Windows10_2019,
|
||||
19041 => WindowsVersion::Windows10_2020,
|
||||
x if x >= 19536 => WindowsVersion::WindowsFastRing,
|
||||
_ => WindowsVersion::WindowsUnknown,
|
||||
};
|
||||
|
||||
Self {
|
||||
version_info,
|
||||
short_version,
|
||||
driver_handle: INVALID_HANDLE_VALUE,
|
||||
ntdll,
|
||||
nt_load_driver,
|
||||
nt_unload_driver,
|
||||
rtl_init_unicode_str,
|
||||
rtl_get_version,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn driver_loaded(self) -> bool {
|
||||
self.driver_handle != INVALID_HANDLE_VALUE
|
||||
}
|
||||
|
||||
pub fn load_driver(&mut self) -> NTSTATUS {
|
||||
// TODO: Move this to new()
|
||||
// If we move this function to new(), self.driver_handle will be init, and thus no mut here
|
||||
let str_driver_reg = U16CString::from_str(STR_DRIVER_REGISTRY_PATH).unwrap();
|
||||
let mut str_driver_reg_unicode = UNICODE_STRING::default();
|
||||
(self.rtl_init_unicode_str)(
|
||||
&mut str_driver_reg_unicode,
|
||||
str_driver_reg.as_ptr() as *const u16,
|
||||
);
|
||||
let status = (self.nt_load_driver)(&mut str_driver_reg_unicode);
|
||||
|
||||
let filename = CString::new("\\\\.\\poolscanner").unwrap();
|
||||
let driver_file_handle: HANDLE = unsafe {
|
||||
CreateFileA(
|
||||
filename.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0,
|
||||
null_mut(),
|
||||
CREATE_ALWAYS,
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
null_mut(),
|
||||
)
|
||||
};
|
||||
|
||||
if driver_file_handle == INVALID_HANDLE_VALUE {
|
||||
println!("Driver CreateFileA failed");
|
||||
} else {
|
||||
self.driver_handle = driver_file_handle;
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
pub fn unload_driver(&self) -> NTSTATUS {
|
||||
let str_driver_reg = U16CString::from_str(STR_DRIVER_REGISTRY_PATH).unwrap();
|
||||
let mut str_driver_reg_unicode = UNICODE_STRING::default();
|
||||
(self.rtl_init_unicode_str)(&mut str_driver_reg_unicode, str_driver_reg.as_ptr());
|
||||
(self.nt_unload_driver)(&mut str_driver_reg_unicode)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_build_number(&self) -> DWORD {
|
||||
self.version_info.dwBuildNumber
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn print_version(&self) {
|
||||
println!(
|
||||
"Windows version: {}.{}.{} {:?}",
|
||||
self.version_info.dwMajorVersion,
|
||||
self.version_info.dwMinorVersion,
|
||||
self.version_info.dwBuildNumber,
|
||||
self.short_version
|
||||
);
|
||||
}
|
||||
|
||||
pub fn to_epoch(&self, filetime: u64) -> u64 {
|
||||
let windows_epoch_diff = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return 0;
|
||||
}
|
||||
let process_time_epoch = (filetime - windows_epoch_diff) / 10000;
|
||||
process_time_epoch
|
||||
}
|
||||
|
||||
pub fn valid_process_time(&self, filetime: u64) -> bool {
|
||||
// https://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/
|
||||
let windows_epoch_diff = 11644473600000 * 10000;
|
||||
if filetime < windows_epoch_diff {
|
||||
return false;
|
||||
}
|
||||
let system_up_time_ms = unsafe { GetTickCount64() };
|
||||
let process_time_epoch = (filetime - windows_epoch_diff) / 10000; // in milisecond
|
||||
let now_ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("Time went backwards")
|
||||
.as_millis() as u64;
|
||||
let system_start_up_time_ms =
|
||||
now_ms - system_up_time_ms - (10 * 3600 * 1000/* 10 minutes penalty */);
|
||||
|
||||
if process_time_epoch < system_start_up_time_ms {
|
||||
false
|
||||
} else if process_time_epoch > now_ms {
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn device_io<T, E>(&self, code: DWORD, inbuf: &mut T, outbuf: &mut E) -> DWORD {
|
||||
self.device_io_raw(
|
||||
code,
|
||||
inbuf as *mut _ as *mut c_void,
|
||||
size_of_val(inbuf) as DWORD,
|
||||
outbuf as *mut _ as *mut c_void,
|
||||
size_of_val(outbuf) as DWORD,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn device_io_raw(
|
||||
&self,
|
||||
code: DWORD,
|
||||
input_ptr: *mut c_void,
|
||||
input_len: DWORD,
|
||||
output_ptr: *mut c_void,
|
||||
output_len: DWORD,
|
||||
) -> DWORD {
|
||||
// println!("driver loaded: {}; device_io_code: {}", self.driver_loaded(), code);
|
||||
let mut bytes_returned: DWORD = 0;
|
||||
unsafe {
|
||||
let status = DeviceIoControl(
|
||||
self.driver_handle,
|
||||
code,
|
||||
input_ptr,
|
||||
input_len,
|
||||
output_ptr,
|
||||
output_len,
|
||||
&mut bytes_returned,
|
||||
null_mut(),
|
||||
);
|
||||
if status == 0 {
|
||||
println!("device io failed: last error {}", GetLastError());
|
||||
}
|
||||
};
|
||||
bytes_returned
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user