all repos — gemini-redirect @ a75139baf23dc35e3d766db94cef7ff094525f49

content/blog/woce-1.md (view raw)

  1+++
  2title = "Writing our own Cheat Engine: Introduction"
  3date = 2021-02-07
  4[taxonomies]
  5category = ["sw"]
  6tags = ["windows", "rust", "hacking"]
  7+++
  8
  9This is part 1 on the *Writing our own Cheat Engine* series.
 10
 11[Cheat Engine][ce] is a tool designed to modify single player games and contains other useful tools within itself that enable its users to debug games or other applications. It comes with a memory scanner, (dis)assembler, inspection tools and a handful other things. In this series, we will be writing our own tiny Cheat Engine capable of solving all steps of the tutorial, and diving into how it all works underneath.
 12
 13Needless to say, we're doing this for private and educational purposes only. One has to make sure to not violate the EULA or ToS of the specific application we're attaching to. This series, much like cheatengine.org, does not condone the illegal use of the code shared.
 14
 15Cheat Engine is a tool for Windows, so we will be developing for Windows as well. However, you can also [read memory from Linux-like systems][linux-readmem]. [GameConqueror][game-conqueror] is a popular alternative to Cheat Engine on Linux systems, so if you feel adventurous, you could definitely follow along too! The techniques shown in this series apply regardless of how we read memory from a process. You will learn a fair bit about doing FFI in Rust too.
 16
 17We will be developing the application in Rust, because it enables us to interface with the Windows API easily, is memory safe (as long as we're careful with `unsafe`!), and is speedy (we will need this for later steps in the Cheat Engine tutorial). You could use any language of your choice though. For example, [Python also makes it relatively easy to use the Windows API][python-ctypes].
 18
 19[Cheat Engine's source code][ce-code] is mostly written in Pascal and C. And it's *a lot* of code, with a very flat project structure, and files ranging in the thousand lines of code each. It's daunting. It's a mature project, with a lot of knowledge encoded in the code base, and a lot of features like distributed scanning or an entire disassembler. Unfortunately, there's not a lot of comments. For these reasons, I'll do some guesswork when possible as to how it's working underneath, rather than actually digging into what Cheat Engine is actually doing.
 20
 21With that out of the way, let's get started!
 22
 23## Welcome to the Cheat Engine Tutorial
 24
 25<details open><summary>Cheat Engine Tutorial: Step 1</summary>
 26
 27> This tutorial will teach you the basics of cheating in video games. It will also show you foundational aspects of using Cheat Engine (or CE for short). Follow the steps below to get started.
 28>
 29> 1. Open Cheat Engine if it currently isn't running.
 30> 2. Click on the "Open Process" icon (it's the top-left icon with the computer on it, below "File".).
 31> 3. With the Process List window now open, look for this tutorial's process in the list. It will look something like > "00001F98-Tutorial-x86_64.exe" or "0000047C-Tutorial-i386.exe". (The first 8 numbers/letters will probably be different.)
 32> 4. Once you've found the process, click on it to select it, then click the "Open" button. (Don't worry about all the > other buttons right now. You can learn about them later if you're interested.)
 33>
 34> Congratulations! If you did everything correctly, the process window should be gone with Cheat Engine now attached to the > tutorial (you will see the process name towards the top-center of CE).
 35>
 36> Click the "Next" button below to continue, or fill in the password and click the "OK" button to proceed to that step.)
 37>
 38> If you're having problems, simply head over to forum.cheatengine.org, then click on "Tutorials" to view beginner-friendly > guides!
 39
 40</details>
 41
 42## Enumerating processes
 43
 44Our first step is attaching to the process we want to work with. But we need a way to find that process in the first place! Having to open the task manager, look for the process we care about, noting down the process ID (PID), and slapping it in the source code is not satisfying at all. Instead, let's enumerate all the processes from within the program, and let the user select one by typing its name.
 45
 46From a quick [DuckDuckGo search][ddg-enumproc], we find an official tutorial for [Enumerating All Processes][tut-enumproc], which leads to the [`EnumProcesses`][api-enumproc] call. Cool! Let's slap in the [`winapi`][winapi-crate] crate on `Cargo.toml`, because I don't want to write all the definitions by myself:
 47
 48```toml
 49[dependencies]
 50winapi = { version = "0.3.9", features = ["psapi"] }
 51```
 52
 53Because [`EnumProcesses`][api-enumproc] is in `Psapi.h` (you can see this in the online page of its documentation), we know we'll need the `psapi` crate feature. Another option is to search for it in the [`winapi` documentation][winapi-doc] and noting down the parent module where its stored.
 54
 55The documentation for the method has the following remark:
 56
 57> It is a good idea to use a large array, because it is hard to predict how many processes there will be at the time you call **EnumProcesses**.
 58
 59*Sidenote: reading the documentation for the methods we'll use from the Windows API is extremely important. There's a lot of gotchas involved, so we need to make sure we're extra careful.*
 60
 611024 is a pretty big number, so let's go with that:
 62
 63```rust
 64use std::io;
 65use std::mem;
 66use winapi::shared::minwindef::{DWORD, FALSE};
 67
 68pub fn enum_proc() -> io::Result<Vec<u32>> {
 69    let mut pids = Vec::<DWORD>::with_capacity(1024);
 70    let mut size = 0;
 71    // SAFETY: the pointer is valid and the size matches the capacity.
 72    if unsafe {
 73        winapi::um::psapi::EnumProcesses(
 74            pids.as_mut_ptr(),
 75            (pids.capacity() * mem::size_of::<DWORD>()) as u32,
 76            &mut size,
 77        )
 78    } == FALSE
 79    {
 80        return Err(io::Error::last_os_error());
 81    }
 82
 83    todo!()
 84}
 85```
 86
 87We allocate enough space for 1024 `pids` in a vector, and pass a mutable pointer to the contents to `EnumProcesses`. Note that the size of the array is in *bytes*, not items, so we need to multiply the capacity by the size of `DWORD`. The API likes to use `u32` for sizes, unlike Rust which uses `usize`, so we need a cast.
 88
 89Last, we need another mutable variable where the amount of bytes written is stored, `size`.
 90
 91> If the function fails, the return value is zero. To get extended error information, call [`GetLastError`][getlasterr].
 92
 93That's precisely what we do. If it returns false (zero), we return the last OS error. Rust provides us with [`std::io::Error::last_os_error`][lasterr], which essentially makes that same call but returns a proper `io::Error` instance. Cool!
 94
 95> To determine how many processes were enumerated, divide the *lpcbNeeded* value by `sizeof(DWORD)`.
 96
 97Easy enough:
 98
 99```rust
100let count = size as usize / mem::size_of::<DWORD>();
101// SAFETY: the call succeeded and count equals the right amount of items.
102unsafe { pids.set_len(count) };
103Ok(pids)
104```
105
106Rust doesn't know that the memory for `count` items were initialized by the call, but we do, so we make use of the [`Vec::set_len`][vecsetlen] call to indicate this. The Rust documentation even includes a FFI similar to our code!
107
108Let's give it a ride:
109
110```rust
111fn main() {
112    dbg!(enum_proc().unwrap().len());
113}
114```
115
116```
117>cargo run
118   Compiling memo v0.1.0
119    Finished dev [unoptimized + debuginfo] target(s) in 0.20s
120     Running `target\debug\memo.exe`
121[src\main.rs:27] enum_proc().unwrap().len() = 178
122```
123
124It works! But currently we only have a bunch of process identifiers, with no way of knowing which process they refer to.
125
126> To obtain process handles for the processes whose identifiers you have just obtained, call the [`OpenProcess`][openproc] function.
127
128Oh!
129
130## Opening a process
131
132The documentation for `OpenProcess` also contains the following:
133
134> When you are finished with the handle, be sure to close it using the [`CloseHandle`](closehandle) function.
135
136This sounds to me like the perfect time to introduce a custom `struct Process` with an `impl Drop`! We're using `Drop` to cleanup resources, not behaviour, so it's fine. [Using `Drop` to cleanup behaviour is a bad idea][drop-behaviour]. But anyway, let's get back to the code:
137
138```rust
139use std::ptr::NonNull;
140use winapi::ctypes::c_void;
141
142pub struct Process {
143    pid: u32,
144    handle: NonNull<c_void>,
145}
146
147impl Process {
148    pub fn open(pid: u32) -> io::Result<Self> {
149        todo!()
150    }
151}
152
153impl Drop for Process {
154    fn drop(&mut self) {
155        todo!()
156    }
157}
158```
159
160For `open`, we'll want to use `OpenProcess` (and we also need to add the `processthreadsapi` feature to the `winapi` dependency in `Cargo.toml`). It returns a `HANDLE`, which is a nullable mutable pointer to `c_void`. If it's null, the call failed, and if it's non-null, it succeeded and we have a valid handle. This is why we use Rust's [`NonNull`][nonnull]:
161
162```rust
163// SAFETY: the call doesn't have dangerous side-effects.
164NonNull::new(unsafe { winapi::um::processthreadsapi::OpenProcess(0, FALSE, pid) })
165    .map(|handle| Self { pid, handle })
166    .ok_or_else(io::Error::last_os_error)
167```
168
169`NonNull` will return `Some` if the pointer is non-null. We map the non-null pointer to a `Process` instance with `Self { .. }`. `ok_or_else` converts the `Option` to a `Result` with the error builder function we provide if it was `None`.
170
171The first parameter is a bitflag of permissions we want to have. For now, we can leave it as zero (all bits unset, no specific permissions granted). The second one is whether we want to inherit the handle, which we don't, and the third one is the process identifier. Let's close the resource handle on `Drop` (after adding `handleapi` to the crate features):
172
173```rust
174// SAFETY: the handle is valid and non-null.
175unsafe { winapi::um::handleapi::CloseHandle(self.handle.as_mut()) };
176```
177
178`CloseHandle` can actually fail (for example, on double-close), but given our invariants, it won't. You could add an `assert!` to panic if this is not the case.
179
180We can now open processes, and they will be automatically closed on `Drop`. Does any of this work though?
181
182```rust
183fn main() {
184    let mut success = 0;
185    let mut failed = 0;
186    enum_proc().unwrap().into_iter().for_each(|pid| match Process::open(pid) {
187        Ok(_) => success += 1,
188        Err(_) => failed += 1,
189    });
190
191    eprintln!("Successfully opened {}/{} processes", success, success + failed);
192}
193```
194
195```
196>cargo run
197   Compiling memo v0.1.0
198    Finished dev [unoptimized + debuginfo] target(s) in 0.36s
199     Running `target\debug\memo.exe`
200Successfully opened 0/191 processes
201```
202
203…nope. Maybe the documentation for `OpenProcess` says something?
204
205> `dwDesiredAccess`
206>
207> The access to the process object. This access right is checked against the security descriptor for the process. This parameter can be **one or more** of the process access rights.
208
209One or more, but we're setting zero permissions. I told you, reading the documentation is important! The [Process Security and Access Rights][proc-rights] page lists all possible values we could use. `PROCESS_QUERY_INFORMATION` seems to be appropriated:
210
211> Required to retrieve certain information about a process, such as its token, exit code, and priority class
212
213```rust
214OpenProcess(winapi::um::winnt::PROCESS_QUERY_INFORMATION, ...)
215```
216
217Does this fix it?
218
219```rust
220>cargo run
221   Compiling memo v0.1.0
222    Finished dev [unoptimized + debuginfo] target(s) in 0.36s
223     Running `target\debug\memo.exe`
224Successfully opened 69/188 processes
225```
226
227*Nice*. It does solve it. But why did we only open 69 processes out of 188? Does it help if we run our code as administrator? Let's search for `cmd` in the Windows menu and right click to Run as administrator, then `cd` into our project and try again:
228
229```
230>cargo run
231    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
232     Running `target\debug\memo.exe`
233Successfully opened 77/190 processes
234```
235
236We're able to open a few more, so it does help. In general, we'll want to run as administrator, so normal programs can't sniff on what we're doing, and so that we have permission to do more things.
237
238## Getting the name of a process
239
240We're not done enumerating things just yet. To get the "name" of a process, we need to enumerate the modules that it has loaded, and only then can we get the module base name. The first module is the program itself, so we don't need to enumerate *all* modules, just the one is enough.
241
242For this we want [`EnumProcessModules`][mod-enumproc] and [`GetModuleBaseNameA`][mod-name]. I'm using the ASCII variant of `GetModuleBaseName` because I'm too lazy to deal with UTF-16 of the `W` (wide, unicode) variants.
243
244```rust
245use std::mem::MaybeUninit;
246use winapi::shared::minwindef::HMODULE;
247
248pub fn name(&self) -> io::Result<String> {
249    let mut module = MaybeUninit::<HMODULE>::uninit();
250    let mut size = 0;
251    // SAFETY: the pointer is valid and the size is correct.
252    if unsafe {
253        winapi::um::psapi::EnumProcessModules(
254            self.handle.as_ptr(),
255            module.as_mut_ptr(),
256            mem::size_of::<HMODULE>() as u32,
257            &mut size,
258        )
259    } == FALSE
260    {
261        return Err(io::Error::last_os_error());
262    }
263
264    // SAFETY: the call succeeded, so module is initialized.
265    let module = unsafe { module.assume_init() };
266    todo!()
267}
268```
269
270`EnumProcessModules` takes a pointer to an array of `HMODULE`. We could use a `Vec` of capacity one to hold the single module, but in memory, a pointer a single item can be seen as a pointer to an array of items. `MaybeUninit` helps us reserve enough memory for the one item we need.
271
272With the module handle, we can retrieve its base name:
273
274```rust
275let mut buffer = Vec::<u8>::with_capacity(64);
276// SAFETY: the handle, module and buffer are all valid.
277let length = unsafe {
278    winapi::um::psapi::GetModuleBaseNameA(
279        self.handle.as_ptr(),
280        module,
281        buffer.as_mut_ptr().cast(),
282        buffer.capacity() as u32,
283    )
284};
285if length == 0 {
286    return Err(io::Error::last_os_error());
287}
288
289// SAFETY: the call succeeded and length represents bytes.
290unsafe { buffer.set_len(length as usize) };
291Ok(String::from_utf8(buffer).unwrap())
292```
293
294Similar to how we did with `EnumProcesses`, we create a buffer that will hold the ASCII string of the module's base name. The call wants us to pass a pointer to a mutable buffer of `i8`, but Rust's `String::from_utf8` wants a `Vec<u8>`, so instead we declare a buffer of `u8` and `.cast()` the pointer in the call. You could also do this with `as _`, and Rust would infer the right type, but `cast` is neat.
295
296We `unwrap` the creation of the UTF-8 string because the buffer should contain only ASCII characters (which are also valid UTF-8). We could use the `unsafe` variant to create the string, but what if somehow it contains non-ASCII characters? The less `unsafe`, the better.
297
298Let's see it in action:
299
300```rust
301fn main() {
302    enum_proc()
303        .unwrap()
304        .into_iter()
305        .for_each(|pid| match Process::open(pid) {
306            Ok(proc) => match proc.name() {
307                Ok(name) => println!("{}: {}", pid, name),
308                Err(e) => println!("{}: (failed to get name: {})", pid, e),
309            },
310            Err(e) => eprintln!("failed to open {}: {}", pid, e),
311        });
312}
313```
314
315```
316>cargo run
317   Compiling memo v0.1.0
318    Finished dev [unoptimized + debuginfo] target(s) in 0.32s
319     Running `target\debug\memo.exe`
320failed to open 0: The parameter is incorrect. (os error 87)
321failed to open 4: Access is denied. (os error 5)
322...
323failed to open 5940: Access is denied. (os error 5)
3245608: (failed to get name: Access is denied. (os error 5))
325...
3261704: (failed to get name: Access is denied. (os error 5))
327failed to open 868: Access is denied. (os error 5)
328...
329```
330
331That's not good. What's up with that? Maybe…
332
333> The handle must have the `PROCESS_QUERY_INFORMATION` and `PROCESS_VM_READ` access rights.
334
335…I should've read the documentation. Okay, fine:
336
337```rust
338use winapi::um::winnt;
339OpenProcess(winnt::PROCESS_QUERY_INFORMATION | winnt::PROCESS_VM_READ, ...)
340```
341
342```
343>cargo run
344   Compiling memo v0.1.0 (C:\Users\L\Desktop\memo)
345    Finished dev [unoptimized + debuginfo] target(s) in 0.35s
346     Running `target\debug\memo.exe`
347failed to open 0: The parameter is incorrect. (os error 87)
348failed to open 4: Access is denied. (os error 5)
349...
3509348: cheatengine-x86_64.exe
3513288: Tutorial-x86_64.exe
3528396: cmd.exe
3534620: firefox.exe
3547964: cargo.exe
35510052: cargo.exe
3565756: memo.exe
357```
358
359Hooray 🎉! There's some processes we can't open, but that's because they're system processes. Security works!
360
361## Finale
362
363That was a fairly long post when all we did was print a bunch of pids and their corresponding name. But in all fairness, we also laid out a good foundation for what's coming next.
364
365You can [obtain the code for this post][code] over at my GitHub. At the end of every post, the last commit will be tagged, so you can `git checkout step1` to see the final code for any blog post.
366
367In the next post, we'll tackle the second step of the tutorial: Exact Value scanning.
368
369[ce]: https://cheatengine.org/
370[python-ctypes]: https://lonami.dev/blog/ctypes-and-windows/
371[ce-code]: https://github.com/cheat-engine/cheat-engine/
372[linux-readmem]: https://stackoverflow.com/q/12977179/4759433
373[game-conqueror]: https://github.com/scanmem/scanmem
374[ddg-enumproc]: https://ddg.gg/winapi%20enumerate%20all%20processes
375[tut-enumproc]: https://docs.microsoft.com/en-us/windows/win32/psapi/enumerating-all-processes
376[api-enumproc]: https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocesses
377[winapi-crate]: https://crates.io/crates/winapi
378[winapi-doc]: https://docs.rs/winapi/
379[getlasterr]: https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
380[lasterr]: https://doc.rust-lang.org/stable/std/io/struct.Error.html#method.last_os_error
381[vecsetlen]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.set_len
382[openproc]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
383[closehandle]: https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle
384[drop-behaviour]: https://internals.rust-lang.org/t/pre-rfc-leave-auto-trait-for-reliable-destruction/13825
385[nonnull]: https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html
386[proc-rights]: https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights
387[mod-enumproc]: https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocessmodules
388[mod-name]: https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmodulebasenamea
389[code]: https://github.com/lonami/memo