content/blog/woce-5.md (view raw)
1+++
2title = "Writing our own Cheat Engine: Code finder"
3date = 2021-03-06
4updated = 2021-03-06
5[taxonomies]
6category = ["sw"]
7tags = ["windows", "rust", "hacking"]
8+++
9
10This is part 5 on the *Writing our own Cheat Engine* series:
11
12* [Part 1: Introduction](/blog/woce-1) (start here if you're new to the series!)
13* [Part 2: Exact Value scanning](/blog/woce-2)
14* [Part 3: Unknown initial value](/blog/woce-3)
15* [Part 4: Floating points](/blog/woce-4)
16* Part 5: Code finder
17* [Part 6: Pointers](/blog/woce-6)
18
19In part 4 we spent a good deal of time trying to make our scans generic, and now we have something that works[^1]! Now that the scanning is fairly powerful and all covered, the Cheat Engine tutorial shifts focus into slightly more advanced techniques that you will most certainly need in anything bigger than a toy program.
20
21It's time to write our very own **debugger** in Rust!
22
23## Code finder
24
25<details open><summary>Cheat Engine Tutorial: Step 5</summary>
26
27> Sometimes the location something is stored at changes when you restart the game, or even while you're playing… In that case you can use 2 things to still make a table that works. In this step I'll try to describe how to use the Code Finder function.
28>
29> The value down here will be at a different location each time you start the tutorial, so a normal entry in the address list wouldn't work. First try to find the address. (You've got to this point so I assume you know how to.)
30>
31> When you've found the address, right-click the address in Cheat Engine and choose "Find out what writes to this address". A window will pop up with an empty list.
32>
33> Then click on the Change value button in this tutorial, and go back to Cheat Engine. If everything went right there should be an address with assembler code there now.
34>
35> Click it and choose the replace option to replace it with code that does nothing. That will also add the code address to the code list in the advanced options window. (Which gets saved if you save your table.)
36>
37> Click on stop, so the game will start running normal again, and close to close the window. Now, click on Change value, and if everything went right the Next button should become enabled.
38>
39> Note: When you're freezing the address with a high enough speed it may happen that next becomes visible anyhow
40
41</details>
42
43## Baby steps to debugging
44
45Although I have used debuggers before, I have never had a need to write one myself so it's time for some research.
46
47Searching on DuckDuckGo, I can find entire series to [Writing a Debugger][debug-series]. We would be done by now if only that series wasn't written for Linux. The Windows documentation contains a section called [Creating a Basic Debugger][win-basic-dbg], but as far as I can tell, it only teaches you the [functions][dbg-func] needed to configure the debugging loop. Which mind you, we will need, but in due time.
48
49According to [Writing your own windows debugger in C][dbg-c], the steps needed to write a debugger are:
50
51* [`SuspendThread(proc)`][suspend-thread]. It makes sense that we need to pause all the threads[^2] before messing around with the code the program is executing, or things are very prone to go wrong.
52* [`GetThreadContext(proc)`][thread-ctx]. This function retrieves the appropriate context of the specified thread and is highly processor specific. It basically takes a snapshot of all the registers. Think of registers like extremely fast, but also extremely limited, memory the processor uses.
53* [`DebugBreakProcess`][dbg-break]. Essentially [writes out the 0xCC opcode][0xcc], `int 3` in assembly, also known as software breakpoint. It's written wherever the Register Instruction Pointer (RIP[^3]) currently points to, so in essence, when the thread resumes, it will immediately [trigger the breakpoint][how-c-brk].
54* [`ContinueDebugEvent`][cont-dbg]. Presumably continues debugging.
55
56There are pages documenting [all of the debug events][dbg-events] that our debugger will be able to handle.
57
58Okay, nice! Software breakpoints seem to be done by writing out memory to the region where the program is reading instructions from. We know how to write memory, as that's what all the previous posts have been doing to complete the corresponding tutorial steps. After the breakpoint is executed, all we need to do is [restore the original memory back][how-int3] so that the next time the program executes the code it sees no difference.
59
60But a software breakpoint will halt execution when the code executes the interrupt instruction. This step of the tutorial wants us to find *what writes to a memory location*. Where should we place the breakpoint to detect such location? Writing out the instruction to the memory we want to break in won't do; it's not an instruction, it's just data.
61
62The name may have given it away. If we're talking about software breakpoints, it makes sense that there would exist such a thing as [*hardware* breakpoints][hw-brk]. Because they're tied to the hardware, they're highly processor-specific, but luckily for us, the processor on your usual desktop computer probably has them! Even the [cortex-m] does. The wikipedia page also tells us the name of the thing we're looking for, watchpoints:
63
64> Other kinds of conditions can also be used, such as the reading, writing, or modification of a specific location in an area of memory. This is often referred to as a conditional breakpoint, a data breakpoint, or a watchpoint.
65
66A breakpoint that triggers when a specific memory location is written to is exactly what we need, and [x86 has debug registers D0 to D3 to track memory addresses][x86-dbg-reg]. As far as I can tell, there is no API in specific to mess with the registers. But we don't need any of that! We can just go ahead and [write some assembly by hand][asm-macro] to access these registers. At the time of writing, inline assembly is unstable, so we need a nightly compiler. Run `rustup toolchain install nightly` if you haven't yet, and execute the following code with `cargo +nightly run`:
67
68```rust
69#![feature(asm)] // top of the file
70
71fn main() {
72 let x: u64 = 123;
73 unsafe {
74 asm!("mov dr7, {}", in(reg) x);
75 }
76}
77
78```
79
80`dr7` stands is the [debug control register][dbg-reg], and running this we get…
81
82```
83>cargo +nightly run
84 Compiling memo v0.1.0
85 Finished dev [unoptimized + debuginfo] target(s) in 0.74s
86 Running `target\debug\memo.exe`
87error: process didn't exit successfully: `target\debug\memo.exe` (exit code: 0xc0000096, STATUS_PRIVILEGED_INSTRUCTION)
88```
89
90…an exception! In all fairness, I have no idea what that code would have done. So maybe the `STATUS_PRIVILEGED_INSTRUCTION` is just trying to protect us. Can we read from the register instead, and see it's default value?
91
92```rust
93let x: u64;
94unsafe {
95 asm!("mov {}, dr7", out(reg) x);
96}
97assert_eq!(x, 5);
98```
99
100```
101>cargo +nightly run
102...
103error: process didn't exit successfully: `target\debug\memo.exe` (exit code: 0xc0000096, STATUS_PRIVILEGED_INSTRUCTION)
104```
105
106Nope. Okay, it seems directly reading from or writing to the debug register is a ring-0 thing. Surely there's a way around this. But first we should figure out how to enumerate and pause all the threads.
107
108## Pausing all the threads
109
110It seems there is no straightforward way to enumerate the threads. One has to [create a "toolhelp"][toolhelp] and poll the entries. I won't bore you with the details. Let's add `tlhelp32` to the crate features of `winapi` and try it out:
111
112```rust
113
114#[derive(Debug)]
115pub struct Toolhelp {
116 handle: winapi::um::winnt::HANDLE,
117}
118
119impl Drop for Toolhelp {
120 fn drop(&mut self) {
121 unsafe { winapi::um::handleapi::CloseHandle(self.handle) };
122 }
123}
124
125pub fn enum_threads(pid: u32) -> io::Result<Vec<u32>> {
126 const ENTRY_SIZE: u32 = mem::size_of::<winapi::um::tlhelp32::THREADENTRY32>() as u32;
127
128 // size_of(dwSize + cntUsage + th32ThreadID + th32OwnerProcessID)
129 const NEEDED_ENTRY_SIZE: u32 = 4 * mem::size_of::<DWORD>() as u32;
130
131 // SAFETY: it is always safe to attempt to call this function.
132 let handle = unsafe {
133 winapi::um::tlhelp32::CreateToolhelp32Snapshot(winapi::um::tlhelp32::TH32CS_SNAPTHREAD, 0)
134 };
135 if handle == winapi::um::handleapi::INVALID_HANDLE_VALUE {
136 return Err(io::Error::last_os_error());
137 }
138 let toolhelp = Toolhelp { handle };
139
140 let mut result = Vec::new();
141 let mut entry = winapi::um::tlhelp32::THREADENTRY32 {
142 dwSize: ENTRY_SIZE,
143 cntUsage: 0,
144 th32ThreadID: 0,
145 th32OwnerProcessID: 0,
146 tpBasePri: 0,
147 tpDeltaPri: 0,
148 dwFlags: 0,
149 };
150
151 // SAFETY: we have a valid handle, and point to memory we own with the right size.
152 if unsafe { winapi::um::tlhelp32::Thread32First(toolhelp.handle, &mut entry) } != FALSE {
153 loop {
154 if entry.dwSize >= NEEDED_ENTRY_SIZE && entry.th32OwnerProcessID == pid {
155 result.push(entry.th32ThreadID);
156 }
157
158 entry.dwSize = ENTRY_SIZE;
159 // SAFETY: we have a valid handle, and point to memory we own with the right size.
160 if unsafe { winapi::um::tlhelp32::Thread32Next(toolhelp.handle, &mut entry) } == FALSE {
161 break;
162 }
163 }
164 }
165
166 Ok(result)
167}
168```
169
170Annoyingly, invalid handles returned by [`CreateToolhelp32Snapshot`][create-snapshot], are `INVALID_HANDLE_VALUE` (which is -1), not null. But that's not a big deal, we simply can't use `NonNull` here. The function ignores the process identifier when using `TH32CS_SNAPTHREAD`, used to include all threads, and we need to compare the process identifier ourselves.
171
172In summary, we create a "toolhelp" (wrapped in a helper `struct` so that whatever happens, `Drop` will clean it up), initialize a thread enntry (with everything but the structure size to zero) and call `Thread32First` the first time, `Thread32Next` subsequent times. It seems to work all fine!
173
174```rust
175dbg!(process::enum_threads(pid));
176```
177
178```
179[src\main.rs:46] process::enum_threads(pid) = Ok(
180 [
181 10560,
182 ],
183)
184```
185
186According to this, the Cheat Engine tutorial is only using one thread. Good to know. Much like processes, threads need to be opened before we can use them, with [`OpenThread`][open-thread]:
187
188```rust
189pub struct Thread {
190 tid: u32,
191 handle: NonNull<c_void>,
192}
193
194impl Thread {
195 pub fn open(tid: u32) -> io::Result<Self> {
196 // SAFETY: the call doesn't have dangerous side-effects
197 NonNull::new(unsafe {
198 winapi::um::processthreadsapi::OpenThread(
199 winapi::um::winnt::THREAD_SUSPEND_RESUME,
200 FALSE,
201 tid,
202 )
203 })
204 .map(|handle| Self { tid, handle })
205 .ok_or_else(io::Error::last_os_error)
206 }
207
208 pub fn tid(&self) -> u32 {
209 self.tid
210 }
211}
212
213impl Drop for Thread {
214 fn drop(&mut self) {
215 unsafe { winapi::um::handleapi::CloseHandle(self.handle.as_mut()) };
216 }
217}
218```
219
220Just your usual RAII pattern. The thread is opened with permission to suspend and resume it. Let's try to pause the handles with [`SuspendThread`][suspend-thread] to make sure that this thread is actually the one we're looking for:
221
222```rust
223pub fn suspend(&mut self) -> io::Result<usize> {
224 // SAFETY: the handle is valid.
225 let ret = unsafe {
226 winapi::um::processthreadsapi::SuspendThread(self.handle.as_ptr())
227 };
228 if ret == -1i32 as u32 {
229 Err(io::Error::last_os_error())
230 } else {
231 Ok(ret as usize)
232 }
233}
234
235pub fn resume(&mut self) -> io::Result<usize> {
236 // SAFETY: the handle is valid.
237 let ret = unsafe {
238 winapi::um::processthreadsapi::ResumeThread(self.handle.as_ptr())
239 };
240 if ret == -1i32 as u32 {
241 Err(io::Error::last_os_error())
242 } else {
243 Ok(ret as usize)
244 }
245}
246```
247
248Both suspend and resume return the previous "suspend count". It's kind of like a barrier or semaphore where the thread only runs if the suspend count is zero. Trying it out:
249
250```rust
251let mut threads = thread::enum_threads(pid)
252 .unwrap()
253 .into_iter()
254 .map(Thread::open)
255 .collect::<Result<Vec<_>, _>>()
256 .unwrap();
257
258threads
259 .iter_mut()
260 .for_each(|thread| {
261 println!("Pausing thread {} for 10 seconds…", thread.tid());
262 thread.suspend().unwrap();
263
264 std::thread::sleep(std::time::Duration::from_secs(10));
265
266 println!("Wake up, {}!", thread.tid());
267 thread.resume().unwrap();
268 });
269```
270
271If you run this code with the process ID of the Cheat Engine tutorial, you will see that the tutorial window freezes for ten seconds! Because the main and only thread is paused, it cannot process any window events, so it becomes unresponsive. It is now "safe" to mess around with the thread context.
272
273## Setting hardware breakpoints
274
275I'm definitely not the first person to wonder [How to set a hardware breakpoint?][howto-hw-brk]. This is great, because it means I don't need to ask that question myself. It appears we need to change the debug register *via the thread context*.
276
277One has to be careful to use the right context structure. Confusingly enough, [`WOW64_CONTEXT`][wow64-ctx] is 32 bits, not 64. `CONTEXT` alone seems to be the right one:
278
279```rust
280pub fn get_context(&self) -> io::Result<winapi::um::winnt::CONTEXT> {
281 let context = MaybeUninit::<winapi::um::winnt::CONTEXT>::zeroed();
282 // SAFETY: it's a C struct, and all-zero is a valid bit-pattern for the type.
283 let mut context = unsafe { context.assume_init() };
284 context.ContextFlags = winapi::um::winnt::CONTEXT_ALL;
285
286 // SAFETY: the handle is valid and structure points to valid memory.
287 if unsafe {
288 winapi::um::processthreadsapi::GetThreadContext(self.handle.as_ptr(), &mut context)
289 } == FALSE
290 {
291 Err(io::Error::last_os_error())
292 } else {
293 Ok(context)
294 }
295}
296```
297
298Trying it out:
299
300```rust
301thread.suspend().unwrap();
302
303let context = thread.get_context().unwrap();
304println!("Dr0: {:016x}", context.Dr0);
305println!("Dr7: {:016x}", context.Dr7);
306println!("Dr6: {:016x}", context.Dr6);
307println!("Rax: {:016x}", context.Rax);
308println!("Rbx: {:016x}", context.Rbx);
309println!("Rcx: {:016x}", context.Rcx);
310println!("Rip: {:016x}", context.Rip);
311```
312
313```
314Dr0: 0000000000000000
315Dr7: 0000000000000000
316Dr6: 0000000000000000
317Rax: 0000000000001446
318Rbx: 0000000000000000
319Rcx: 0000000000000000
320Rip: 00007ffda4259904
321```
322
323Looks about right! Hm, I wonder what happens if I use Cheat Engine to add the watchpoint on the memory location we care about?
324
325```
326Dr0: 000000000157e650
327Dr7: 00000000000d0001
328```
329
330Look at that! The debug registers changed! DR0 contains the location we want to watch for writes, and the debug control register DR7 changed. Cheat Engine sets the same values on all threads (for some reason I now see more than one thread printed for the tutorial, not sure what's up with that; maybe the single-thread is the weird one out).
331
332Hmm, what happens if I watch for access instead of write?
333
334```
335Dr0: 000000000157e650
336Dr7: 00000000000f0001
337```
338
339What if I set both?
340
341```
342Dr0: 000000000157e650
343Dr7: 0000000000fd0005
344```
345
346Most intriguing! This was done by telling Cheat Engine to find "what writes" to the address, then "what accesses" the address. I wonder if the order matters?
347
348```
349Dr0: 000000000157e650
350Dr7: 0000000000df0005
351```
352
353"What accesses" and then "what writes" does change it. Very well! We're only concerned in a single breakpoint, so we won't worry about this, but it's good to know that we can inspect what Cheat Engine is doing. It's also interesting to see how Cheat Engine is using hardware breakpoints and not software breakpoints.
354
355For simplicity, our code is going to assume that we're the only ones messing around with the debug registers, and that there will only be a single debug register in use. Make sure to add `THREAD_SET_CONTEXT` to the permissions when opening the thread handle:
356
357```rust
358pub fn set_context(&self, context: &winapi::um::winnt::CONTEXT) -> io::Result<()> {
359 // SAFETY: the handle is valid and structure points to valid memory.
360 if unsafe {
361 winapi::um::processthreadsapi::SetThreadContext(self.handle.as_ptr(), context)
362 } == FALSE
363 {
364 Err(io::Error::last_os_error())
365 } else {
366 Ok(())
367 }
368}
369
370pub fn watch_memory_write(&self, addr: usize) -> io::Result<()> {
371 let mut context = self.get_context()?;
372 context.Dr0 = addr as u64;
373 context.Dr7 = 0x00000000000d0001;
374 self.set_context(&context)?;
375 todo!()
376}
377```
378
379If we do this (and temporarily get rid of the `todo!()`), trying to change the value in the Cheat Engine tutorial will greet us with a warm message:
380
381> **Tutorial-x86_64**
382>
383> External exception 80000004.
384>
385> Press OK to ignore and risk data corruption.\
386> Press Abort to kill the program.
387>
388> <kbd>OK</kbd> <kbd>Abort</kbd>
389
390There is no debugger attached yet that could possibly handle this exception, so the exception just propagates. Let's fix that.
391
392## Handling debug events
393
394Now that we've succeeded on setting breakpoints, we can actually follow the steps described in [Creating a Basic Debugger][win-basic-dbg]. It starts by saying that we should use [`DebugActiveProcess`][dbg-active] to attach our processor, the debugger, to the process we want to debug, the debuggee. This function lives under the `debugapi` header, so add it to `winapi` features:
395
396```rust
397pub struct DebugToken {
398 pid: u32,
399}
400
401pub fn debug(pid: u32) -> io::Result<DebugToken> {
402 if unsafe { winapi::um::debugapi::DebugActiveProcess(pid) } == FALSE {
403 return Err(io::Error::last_os_error());
404 };
405 let token = DebugToken { pid };
406 if unsafe { winapi::um::winbase::DebugSetProcessKillOnExit(FALSE) } == FALSE {
407 return Err(io::Error::last_os_error());
408 };
409 Ok(token)
410}
411
412impl Drop for DebugToken {
413 fn drop(&mut self) {
414 unsafe { winapi::um::debugapi::DebugActiveProcessStop(self.pid) };
415 }
416}
417```
418
419Once again, we create a wrapper `struct` with `Drop` to stop debugging the process once the token is dropped. The call to `DebugSetProcessKillOnExit` in our `debug` method ensures that, if our process (the debugger) dies, the process we're debugging (the debuggee) stays alive. We don't want to be restarting the entire Cheat Engine tutorial every time our Rust code crashes!
420
421With the debugger attached, we can wait for debug events. We will put this method inside of `impl DebugToken`, so that the only way you can call it is if you successfully attached to another process:
422
423```rust
424impl DebugToken {
425 pub fn wait_event(
426 &self,
427 timeout: Option<Duration>,
428 ) -> io::Result<winapi::um::minwinbase::DEBUG_EVENT> {
429 let mut result = MaybeUninit::uninit();
430 let timeout = timeout
431 .map(|d| d.as_millis().try_into().ok())
432 .flatten()
433 .unwrap_or(winapi::um::winbase::INFINITE);
434
435 // SAFETY: can only wait for events with a token, so the debugger is active.
436 if unsafe { winapi::um::debugapi::WaitForDebugEvent(result.as_mut_ptr(), timeout) } == FALSE
437 {
438 Err(io::Error::last_os_error())
439 } else {
440 // SAFETY: the call returned non-zero, so the structure is initialized.
441 Ok(unsafe { result.assume_init() })
442 }
443 }
444}
445```
446
447`WaitForDebugEvent` wants a timeout in milliseconds, so our function lets the user pass the more Rusty `Duration` type. `None` will indicate "there is no timeout", i.e., it's infinite. If the duration is too large to fit in the `u32` (`try_into` fails), it will also be infinite.
448
449If we attach the debugger, set the hardware watchpoint, and modify the memory location from the tutorial, an event with `dwDebugEventCode = 3` will be returned! Now, back to the page with the [Debugging Events][dbg-events]… Gah! It only has the name of the constants, not the values. Well, good thing [docs.rs] has a source view! We can just check the values in the [source code for `winapi`][winapi-dbg-event-src]:
450
451```rust
452pub const EXCEPTION_DEBUG_EVENT: DWORD = 1;
453pub const CREATE_THREAD_DEBUG_EVENT: DWORD = 2;
454pub const CREATE_PROCESS_DEBUG_EVENT: DWORD = 3;
455pub const EXIT_THREAD_DEBUG_EVENT: DWORD = 4;
456pub const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
457pub const LOAD_DLL_DEBUG_EVENT: DWORD = 6;
458pub const UNLOAD_DLL_DEBUG_EVENT: DWORD = 7;
459pub const OUTPUT_DEBUG_STRING_EVENT: DWORD = 8;
460pub const RIP_EVENT: DWORD = 9;
461```
462
463So, we've got a `CREATE_PROCESS_DEBUG_EVENT`:
464
465> Generated whenever a new process is created in a process being debugged or whenever the debugger begins debugging an already active process. The system generates this debugging event before the process begins to execute in user mode and before the system generates any other debugging events for the new process.
466
467It makes sense that this is our first event. By the way, if you were trying this out with a `sleep` lying around in your code, you may have noticed that the window froze until the debugger terminated. That's because:
468
469> When the system notifies the debugger of a debugging event, it also suspends all threads in the affected process. The threads do not resume execution until the debugger continues the debugging event by using [`ContinueDebugEvent`][cont-dbg].
470
471Let's call `ContinueDebugMethod` but also wait on more than one event and see what happens:
472
473```rust
474for _ in 0..10 {
475 let event = debugger.wait_event(None).unwrap();
476 println!("Got {}", event.dwDebugEventCode);
477 debugger.cont(event, true).unwrap();
478}
479```
480
481```
482Got 3
483Got 6
484Got 6
485Got 6
486Got 6
487Got 6
488Got 6
489Got 6
490Got 6
491Got 6
492```
493
494That's a lot of `LOAD_DLL_DEBUG_EVENT`. Pumping it up to one hundred and also showing the index we get the following:
495
496```
4970. Got 3
4981. Got 6
499...
50040. Got 6
50141. Got 2
50242. Got 1
50343. Got 4
504```
505
506In order, we got:
507
508* One `CREATE_PROCESS_DEBUG_EVENT`.
509* Forty `LOAD_DLL_DEBUG_EVENT`.
510* One `CREATE_THREAD_DEBUG_EVENT`.
511* One `EXCEPTION_DEBUG_EVENT`.
512* One `EXIT_THREAD_DEBUG_EVENT`.
513
514And, if after all this, you change the value in the Cheat Engine tutorial (thus triggering our watch point), we get `EXCEPTION_DEBUG_EVENT`!
515
516> Generated whenever an exception occurs in the process being debugged. Possible exceptions include attempting to access inaccessible memory, executing breakpoint instructions, attempting to divide by zero, or any other exception noted in Structured Exception Handling.
517
518If we print out all the fields in the [`EXCEPTION_DEBUG_INFO`][exc-dbg-info] structure:
519
520```
521Watching writes to 10e3a0 for 10s
522First chance: 1
523ExceptionCode: 2147483652
524ExceptionFlags: 0
525ExceptionRecord: 0x0
526ExceptionAddress: 0x10002c5ba
527NumberParameters: 0
528ExceptionInformation: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
529```
530
531The `ExceptionCode`, which is `0x80000004`, corresponds with `EXCEPTION_SINGLE_STEP`:
532
533> A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
534
535The `ExceptionAddress` is supposed to be "the address where the exception occurred". Very well! I have already completed this step of the tutorial, and I know the instruction is `mov [rax],edx` (or, as Cheat Engine shows, the bytes `89 10` in hexadecimal). The opcode for the `nop` instruction is `90` in hexadecimal, so if we replace two bytes at this address, we should be able to complete the tutorial.
536
537Note that we also need to flush the instruction cache, as noted in the Windows documentation:
538
539> Debuggers frequently read the memory of the process being debugged and write the memory that contains instructions to the instruction cache. After the instructions are written, the debugger calls the [`FlushInstructionCache`][flush-ins] function to execute the cached instructions.
540
541So we add a new method to `impl Process`:
542
543```rust
544/// Flushes the instruction cache.
545///
546/// Should be called when writing to memory regions that contain code.
547pub fn flush_instruction_cache(&self) -> io::Result<()> {
548 // SAFETY: the call doesn't have dangerous side-effects.
549 if unsafe {
550 winapi::um::processthreadsapi::FlushInstructionCache(
551 self.handle.as_ptr(),
552 ptr::null(),
553 0,
554 )
555 } == FALSE
556 {
557 Err(io::Error::last_os_error())
558 } else {
559 Ok(())
560 }
561}
562```
563
564And write some quick and dirty code to get this done:
565
566```rust
567let addr = ...;
568println!("Watching writes to {:x} for 10s", addr);
569threads.iter_mut().for_each(|thread| {
570 thread.watch_memory_write(addr).unwrap();
571});
572loop {
573 let event = debugger.wait_event(None).unwrap();
574 if event.dwDebugEventCode == 1 {
575 let exc = unsafe { event.u.Exception() };
576 if exc.ExceptionRecord.ExceptionCode == 2147483652 {
577 let addr = exc.ExceptionRecord.ExceptionAddress as usize;
578 match process.write_memory(addr, &[0x90, 0x90]) {
579 Ok(_) => eprintln!("Patched [{:x}] with NOP", addr),
580 Err(e) => eprintln!("Failed to patch [{:x}] with NOP: {}", addr, e),
581 };
582 process.flush_instruction_cache().unwrap();
583 debugger.cont(event, true).unwrap();
584 break;
585 }
586 }
587 debugger.cont(event, true).unwrap();
588}
589```
590
591Although it seems to work:
592
593```
594Watching writes to 15103f0 for 10s
595Patched [10002c5ba] with NOP
596```
597
598It really doesn't:
599
600> **Tutorial-x86_64**
601>
602> Access violation.
603>
604> Press OK to ignore and risk data corruption.\
605> Press Abort to kill the program.
606>
607> <kbd>OK</kbd> <kbd>Abort</kbd>
608
609Did we write memory somewhere we shouldn't? The documentation does mention "segment-relative" and "linear virtual addresses":
610
611> `GetThreadSelectorEntry` returns the descriptor table entry for a specified selector and thread. Debuggers use the descriptor table entry to convert a segment-relative address to a linear virtual address. The `ReadProcessMemory` and `WriteProcessMemory` functions require linear virtual addresses.
612
613But nope! This isn't the problem. The problem is that the `ExceptionRecord.ExceptionAddress` is *after* the execution happened, so it's already 2 bytes beyond where it should be. We were accidentally writing out the first half of the next instruction, which, yeah, could not end good.
614
615So does it work if I do this instead?:
616
617```rust
618process.write_memory(addr - 2, &[0x90, 0x90])
619// ^^^ new
620```
621
622This totally does work. Step 5: complete 🎉
623
624## Properly patching instructions
625
626You may not be satisfied at all with our solution. Not only are we hardcoding some magic constants to set hardware watchpoints, we're also relying on knowledge specific to the Cheat Engine tutorial (insofar that we're replacing two bytes worth of instruction with NOPs).
627
628Properly supporting more than one hardware breakpoint, along with supporting different types of breakpoints, is definitely doable. The meaning of the bits for the debug registers is well defined, and you can definitely study that to come up with [something more sophisticated][cpp-many-brk] and support multiple different breakpoints. But for now, that's out of the scope of this series. The tutorial only wants us to use an on-write watchpoint, and our solution is fine and portable for that use case.
629
630However, relying on the size of the instructions is pretty bad. The instructions x86 executes are of variable length, so we can't possibly just look back until we find the previous instruction, or even naively determine its length. A lot of unrelated sequences of bytes are very likely instructions themselves. We need a disassembler. No, we're not writing our own[^4].
631
632Searching on [crates.io] for "disassembler" yields a few results, and the first one I've found is [iced-x86]. I like the name, it has a decent amount of GitHub stars, and it was last updated less than a month ago. I don't know about you, but I think we've just hit a jackpot!
633
634It's quite heavy though, so I will add it behind a feature gate, and users that want it may opt into it:
635
636```toml
637[features]
638patch-nops = ["iced-x86"]
639
640[dependencies]
641iced-x86 = { version = "1.10.3", optional = true }
642```
643
644You can make use of it with `cargo run --features=patch-nops`. I don't want to turn this blog post into a tutorial for `iced-x86`, but in essence, we need to make use of its `Decoder`. Here's the plan:
645
6461. Find the memory region corresponding to the address we want to patch.
6472. Read the entire region.
6483. Decode the read bytes until the instruction pointer reaches our address.
6494. Because we just parsed the previous instruction, we know its length, and can be replaced with NOPs.
650
651```rust
652#[cfg(feature = "patch-nops")]
653pub fn nop_last_instruction(&self, addr: usize) -> io::Result<()> {
654 use iced_x86::{Decoder, DecoderOptions, Formatter, Instruction, NasmFormatter};
655
656 let region = self
657 .memory_regions()
658 .into_iter()
659 .find(|region| {
660 let base = region.BaseAddress as usize;
661 base <= addr && addr < base + region.RegionSize
662 })
663 .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "no matching region found"))?;
664
665 let bytes = self.read_memory(region.BaseAddress as usize, region.RegionSize)?;
666
667 let mut decoder = Decoder::new(64, &bytes, DecoderOptions::NONE);
668 decoder.set_ip(region.BaseAddress as _);
669
670 let mut instruction = Instruction::default();
671 while decoder.can_decode() {
672 decoder.decode_out(&mut instruction);
673 if instruction.next_ip() as usize == addr {
674 return self
675 .write_memory(instruction.ip() as usize, &vec![0x90; instruction.len()])
676 .map(drop);
677 }
678 }
679
680 Err(io::Error::new(
681 io::ErrorKind::Other,
682 "no matching instruction found",
683 ))
684}
685```
686
687Pretty straightforward! We can set the "instruction pointer" of the decoder so that it matches with the address we're reading from. The `next_ip` method comes in really handy. Overall, it's a bit inefficient, because we could reuse the regions retrieved previously, but other than that, there is not much room for improvement.
688
689With this, we are no longer hardcoding the instruction size or guessing which instruction is doing what. You may wonder, what if the region does not start with valid executable code? It could be possible that the instructions are in some memory region with garbage except for a very specific location with real code. I don't know how Cheat Engine handles this, but I think it's reasonable to assume that the region starts with valid code.
690
691As far as I can tell (after having asked a bit around), the encoding is usually self synchronizing (similar to UTF-8), so eventually we should end up with correct instructions. But someone can still intentionally write real code between garbage data which we would then disassemble incorrectly. This is a problem on all variable-length ISAs. Half a solution is to [start at the entry point][howto-disasm], decode all instructions, and follow the jumps. The other half would be correctly identifying jumps created just to trip a disassembler up, and jumps pointing to dynamically-calculated addresses!
692
693## Finale
694
695That was quite a deep dive! We have learnt about the existence of the various breakpoint types (software, hardware, and even behaviour, such as watchpoints), how to debug a separate process, and how to correctly update the code other process is running on-the-fly. The [code for this post][code] is available over at my GitHub. You can run `git checkout step5` after cloning the repository to get the right version of the code.
696
697Although we've only talked about *setting* breakpoints, there are of course [ways of detecting them][detect-brk]. There's [entire guides about it][detect-brk-guide]. Again, we currently hardcode the fact we want to add a single watchpoint using the first debug register. A proper solution here would be to actually calculate the needs that need to be set, as well as keeping track of how many breakpoints have been added so far.
698
699Hardware breakpoints are also limited, since they're simply a bunch of registers, and our machine does not have infinite registers. How are other debuggers like `gdb` able to create a seemingly unlimited amount of breakpoints? Well, the GDB wiki actually has a page on [Internals Watchpoints][gdb-watchpoints], and it's really interesting! `gdb` essentially single-steps through the entire program and tests the expressions after every instruction:
700
701> Software watchpoints are very slow, since GDB needs to single-step the program being debugged and test the value of the watched expression(s) after each instruction.
702
703However, that's not the only way. One could [change the protection level][change-prot] of the region of interest (for example, remove the write permission), and when the program tries to write there, it will fail! In any case, the GDB wiki is actually a pretty nice resource. It also has a section on [Breakpoint Handling][gdb-breakpoints], which contains some additional insight.
704
705With regards to code improvements, `DebugToken::wait_event` could definitely be both nicer and safer to use, with a custom `enum`, so the user does not need to rely on magic constants or having to resort to `unsafe` access to get the right `union` variant.
706
707In the [next post](/blog/woce-6), we'll tackle the sixth step of the tutorial: Pointers. It reuses the debugging techniques presented here to backtrack where the pointer for our desired value is coming from, so here we will need to actually *understand* what the instructions are doing, not just patching them out!
708
709### Footnotes
710
711[^1]: I'm not super happy about the design of it all, but we won't actually need anything beyond scanning for integers for the rest of the steps so it doesn't really matter.
712
713[^2]: There seems to be a way to pause the entire process in one go, with the [undocumented `NtSuspendProcess`][suspend-proc] function!
714
715[^3]: It really is called that. The naming went from "IP" (instruction pointer, 16 bits), to "EIP" (extended instruction pointer, 32 bits) and currently "RIP" (64 bits). The naming convention for upgraded registers is the same (RAX, RBX, RCX, and so on). The [OS Dev wiki][osdev-wiki] is a great resource for this kind of stuff.
716
717[^4]: Well, we don't need an entire disassembler. Knowing the length of each instruction is enough, but that on its own is also a lot of work.
718
719[debug-series]: http://system.joekain.com/debugger/
720[win-basic-dbg]: https://docs.microsoft.com/en-us/windows/win32/debug/creating-a-basic-debugger
721[dbg-func]: https://docs.microsoft.com/en-us/windows/win32/debug/debugging-functions
722[dbg-c]: https://www.gironsec.com/blog/2013/12/writing-your-own-debugger-windows-in-c/
723[suspend-thread]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread
724[thread-ctx]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext
725[dbg-break]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-debugbreakprocess
726[0xcc]: https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/x86-instructions#miscellaneous
727[how-c-brk]: https://stackoverflow.com/q/3915511/
728[cont-dbg]: https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-continuedebugevent
729[dbg-events]: https://docs.microsoft.com/en-us/windows/win32/debug/debugging-events
730[how-int3]: https://stackoverflow.com/q/3747852/
731[hw-brk]: https://en.wikipedia.org/wiki/Breakpoint#Hardware
732[cortex-m]: https://interrupt.memfault.com/blog/cortex-m-breakpoints
733[x86-dbg-reg]: https://stackoverflow.com/a/19109153/
734[asm-macro]: https://doc.rust-lang.org/stable/unstable-book/library-features/asm.html
735[dbg-reg]: https://en.wikipedia.org/wiki/X86_debug_register
736[toolhelp]: https://stackoverflow.com/a/1206915/
737[create-snapshot]: https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot
738[open-thread]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthread
739[howto-hw-brk]: https://social.msdn.microsoft.com/Forums/en-US/0cb3360d-3747-42a7-bc0e-668c5d9ee1ee/how-to-set-a-hardware-breakpoint
740[wow64-ctx]: https://stackoverflow.com/q/17504174/
741[dbg-active]: https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-debugactiveprocess
742[docs.rs]: https://docs.rs/
743[winapi-dbg-event-src]: https://docs.rs/winapi/0.3.9/src/winapi/um/minwinbase.rs.html#203-211
744[cont-dbg]: https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-continuedebugevent
745[exc-dbg-info]: https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-exception_debug_info
746[flush-ins]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-flushinstructioncache
747[crates.io]: https://crates.io
748[iced-x86]: https://crates.io/crates/iced-x86
749[detect-brk]: https://reverseengineering.stackexchange.com/a/16547
750[detect-brk-guide]: https://www.codeproject.com/Articles/30815/An-Anti-Reverse-Engineering-Guide
751[gdb-watchpoints]: https://sourceware.org/gdb/wiki/Internals%20Watchpoints
752[gdb-breakpoints]: https://sourceware.org/gdb/wiki/Internals/Breakpoint%20Handling
753[howto-disasm]: https://stackoverflow.com/q/3983735/
754[cpp-many-brk]: https://github.com/mmorearty/hardware-breakpoints
755[change-prot]: https://stackoverflow.com/a/7805842/
756[suspend-proc]: https://stackoverflow.com/a/4062698/
757[osdev-wiki]: https://wiki.osdev.org/CPU_Registers_x86_64
758[code]: https://github.com/lonami/memo