rust-ptrace 0.1 released

The Codius team is excited to announce the release of rust-ptrace 0.1. rust-ptrace is a rust crate that provides an API to the linux ptrace() syscall, which is used for inspecting the execution state of other processes. This is the first public release of rust-ptrace that was alluded to in a previous writeup describing how we use Rust as a layer of security in our sandbox.

It is available through the usual channel, crates.io, by adding the following to your Cargo.toml:

[dependencies]
ptrace = "0.1"  

Using rust-ptrace

Rust-ptrace provides a fairly straightforward set of primitives for inspecting another process' execution state which includes CPU registers, contents of memory, and watching any syscalls. Documentation on using ptrace to accomplish these things can be found in copious quantity elsewhere on the 'net, but let's go over the rust specifics.

Attaching to a process

Attaching to a process is just the same as in C. Calling ptrace::attach(pid) ends up calling ptrace(PTRACE_ATTACH, pid, 0, 0);, just as one would expect:

match ptrace::attach(some_pid) {  
    Ok(_) => println!("Attached!"),
    Err(e) => panic!("Could not attach: {}", e)
}

For all ptrace functions in rust-ptrace, the error value is the value of errno after the call. The Ok value is whatever is returned by ptrace().

Reading and writing data from a process

rust-ptrace provides two helpful types for reading/writing blocks of data to and from another process' memory:

ptrace::attach(some_pid).ok().expect("Could not attach");  
let r = Reader::new(some_pid);  
match r.peek_data(some_address) {  
    Ok(v) => println!("Read word: {}", v),
    Err(e) => panic!("Could not read word. Errno: {}", e)
}
match r.read_string(some_other_address) {  
    Ok(s) => println!("Read a null terminated string: {}", s),
    Err(e) => panic!("Could not read a full string. Errno: {}", e)
}

The above code:

  • Attaches to a process
  • Reads a word from an address
  • Reads a null-terminated string from an address

More example usage can be found within the read/write tests.

Happy hacking!