memory_library/
lib.rs

1extern crate nix;
2extern crate libc;
3#[macro_use] extern crate log;
4extern crate env_logger;
5#[cfg(unix)]
6use libc::{open, c_uint, ptrace, waitpid, pid_t, c_int, pwrite};
7use nix::errno;
8
9
10
11#[cfg(target_pointer_width="64")]
12pub struct Transaction{
13    pub adress : u64,
14    pub data : Vec<u8>,
15}
16
17#[cfg(target_pointer_width="32")]
18pub struct Transaction{
19    pub adress : u32,
20    pub data : Vec<u8>,
21}
22#[cfg(unix)]
23#[allow(dead_code)]
24pub struct Transactions{
25    pub transactions : Vec<Transaction>,
26    targetpid : u32,
27}
28
29#[cfg(unix)]
30#[allow(unused_assignments)]
31#[allow(unused_variables)]
32impl Transactions{
33    pub fn make_transactions(&self) -> bool{
34        let mut mem = "/proc/".to_string();
35        mem.push_str(&self.targetpid.to_string());
36        mem.push_str(&"/mem".to_string());
37        let mut handle : Option<i32>;
38        handle = None;
39        unsafe{
40            let ptrace_attach : c_uint =  0x10;
41            let mut status : c_int = 0;
42            let option : c_int = 0;
43            ptrace(ptrace_attach, self.targetpid as pid_t);
44            debug!("Val of ptrace {}", errno::errno());
45            waitpid(self.targetpid as pid_t, &mut status, option);
46            debug!("Val of waitpid {}", errno::errno());
47            handle = Some(open(mem.as_ptr() as *const i8, 0x2));
48            debug!("Val of open {}", errno::errno());
49        }
50        for transaction in &self.transactions{
51                match handle{
52                    Some(val) =>
53                        unsafe{
54                            pwrite(val, transaction.data.as_ptr() as *const libc::c_void,
55                               transaction.data.len(), transaction.adress as i64);
56                            debug!("Val of pwrite {}", errno::errno());
57                            if errno::errno() != 0 {
58                                debug!("Failed to write data");
59                                return false;
60                            }
61                        },
62                    None => {debug!("failed to write data"); return false;},
63                }
64        }
65        debug!("Successfully written all data");
66        return true;
67    }
68}
69
70#[test]
71fn mem_test() {
72    env_logger::init().unwrap();
73    debug!("Testing now");
74    let test = Transaction{
75        adress : 0x0,
76        data : vec![0,0,0],
77    };
78    let test2 = Transactions{
79        targetpid : 11211,
80        transactions : vec![test]
81    };
82    assert!(test2.make_transactions());
83}