tls.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. //! Static TLS of an executable mapped as a DLL.
  2. //!
  3. //! An exe always gets TLS index 0, so title code reaches its thread-local
  4. //! block as `mov r64, gs:[0x58]` (the thread's TLS array) followed by
  5. //! `[r64]`, without reading `_tls_index`. Mapped as a DLL, the image gets
  6. //! another index. Every such load is turned into a call to a thunk that
  7. //! yields `&array[index]` instead, and the image's `_tls_index` (which CRT
  8. //! code does read, and adds to the array pointer) is set to 0.
  9. use std::ffi::c_void;
  10. use anyhow::{Result, bail};
  11. use victory_pe::ImageInfo;
  12. use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
  13. use windows_sys::Win32::System::Memory::{
  14. MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_READWRITE,
  15. VirtualAlloc, VirtualProtect,
  16. };
  17. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  18. const SCN_MEM_EXECUTE: u32 = 0x2000_0000;
  19. const TLS64_ADDRESS_OF_INDEX: usize = 16;
  20. /// `mov r64, gs:[0x58]` is `65 REX 8B ModRM 25 58 00 00 00`.
  21. const LOAD_LEN: usize = 9;
  22. const THUNK_SIZE: usize = 32;
  23. /// Redirects the image's TLS-array loads if the OS gave it an index other
  24. /// than 0. Returns the number of loads patched.
  25. ///
  26. /// # Safety
  27. /// `base` is the image `info` describes, mapped and not yet running.
  28. pub(crate) unsafe fn redirect(base: usize, info: &ImageInfo) -> Result<usize> {
  29. let Some(tls) = &info.tls else { return Ok(0) };
  30. // SAFETY: the TLS directory and the index it points to are in the image;
  31. // the OS relocated the pointer and wrote the index.
  32. let index_at = unsafe {
  33. ((base + tls.directory_rva as usize + TLS64_ADDRESS_OF_INDEX) as *const usize).read()
  34. } as *mut u32;
  35. // SAFETY: as above.
  36. let index = unsafe { index_at.read() };
  37. if index == 0 {
  38. return Ok(0);
  39. }
  40. let thunks = thunks(near(base, info.size_of_image as usize)?, index)?;
  41. let mut patched = 0;
  42. for section in info
  43. .sections
  44. .iter()
  45. .filter(|s| s.characteristics & SCN_MEM_EXECUTE != 0)
  46. {
  47. let start = base + section.rva as usize;
  48. let len = section.virtual_size as usize;
  49. let mut old = 0;
  50. // SAFETY: the section is part of the mapped image.
  51. if unsafe { VirtualProtect(start as _, len, PAGE_EXECUTE_READWRITE, &mut old) } == 0 {
  52. bail!(
  53. "VirtualProtect(code) failed: {}",
  54. std::io::Error::last_os_error()
  55. );
  56. }
  57. // SAFETY: writable now, and no title code runs yet.
  58. let code = unsafe { std::slice::from_raw_parts_mut(start as *mut u8, len) };
  59. patched += patch(code, start, thunks);
  60. // SAFETY: restoring the protection we changed; flushing our own code.
  61. unsafe {
  62. VirtualProtect(start as _, len, old, &mut old);
  63. FlushInstructionCache(GetCurrentProcess(), start as _, len);
  64. }
  65. }
  66. // SAFETY: see `index_at`; `.data` is writable.
  67. unsafe { index_at.write(0) };
  68. tracing::info!(index, patched, "static TLS redirected");
  69. Ok(patched)
  70. }
  71. /// Rewrites each `mov r64, gs:[0x58]` in `code` (at address `at`) as
  72. /// `call thunks[r]; nop4`. `thunks` must be within 2 GiB of `code`.
  73. fn patch(code: &mut [u8], at: usize, thunks: usize) -> usize {
  74. let mut count = 0;
  75. let mut i = 0;
  76. while i + LOAD_LEN <= code.len() {
  77. let c = &code[i..i + LOAD_LEN];
  78. let rex = c[1];
  79. let reg = usize::from((c[3] >> 3) & 7) | if rex & 4 != 0 { 8 } else { 0 };
  80. // shortcut: a byte match, not a decode. In the title all
  81. // 53,246 hits are instruction starts and none is missed (checked
  82. // against a full disassembly); decode .text if a title shows one.
  83. if c[0] == 0x65
  84. && (rex == 0x48 || rex == 0x4C)
  85. && c[2] == 0x8B
  86. && c[3] & 0xC7 == 0x04
  87. && c[4..] == [0x25, 0x58, 0, 0, 0]
  88. && reg != 4
  89. {
  90. let rel = (thunks + reg * THUNK_SIZE) as i64 - (at + i + 5) as i64;
  91. code[i] = 0xE8;
  92. code[i + 1..i + 5].copy_from_slice(&(rel as i32).to_le_bytes());
  93. code[i + 5..i + 9].copy_from_slice(&[0x0F, 0x1F, 0x40, 0x00]);
  94. count += 1;
  95. i += LOAD_LEN;
  96. } else {
  97. i += 1;
  98. }
  99. }
  100. count
  101. }
  102. /// Fills `block` with one thunk per register: `mov r, gs:[0x58];
  103. /// lea r, [r + index * 8]; ret` (flags untouched, like the load it replaces).
  104. fn thunks(block: *mut u8, index: u32) -> Result<usize> {
  105. let disp = (index * 8).to_le_bytes();
  106. for reg in 0..16u8 {
  107. let (r, low) = (reg >> 3, reg & 7);
  108. let mut code = vec![0x65, 0x48 | r << 2, 0x8B, low << 3 | 4, 0x25, 0x58, 0, 0, 0];
  109. code.extend([0x48 | r << 2 | r, 0x8D, 0x80 | low << 3 | low]);
  110. if low == 4 {
  111. code.push(0x24); // SIB: [r12 + disp32]
  112. }
  113. code.extend(disp);
  114. code.push(0xC3);
  115. // SAFETY: `block` holds 16 thunks and is still writable.
  116. unsafe {
  117. std::ptr::copy_nonoverlapping(
  118. code.as_ptr(),
  119. block.add(usize::from(reg) * THUNK_SIZE),
  120. code.len(),
  121. )
  122. };
  123. }
  124. let mut old = 0;
  125. // SAFETY: `block` is our allocation of one page.
  126. if unsafe { VirtualProtect(block as _, 4096, PAGE_EXECUTE_READ, &mut old) } == 0 {
  127. bail!(
  128. "VirtualProtect(TLS thunks) failed: {}",
  129. std::io::Error::last_os_error()
  130. );
  131. }
  132. Ok(block as usize)
  133. }
  134. /// One writable page within `rel32` reach of `[base, base + size)`. Leaked:
  135. /// title code calls into it for the life of the process.
  136. fn near(base: usize, size: usize) -> Result<*mut u8> {
  137. const GRANULE: usize = 0x1_0000;
  138. // The search spans 1 GiB each side, so every call site stays in reach.
  139. if size >= 1 << 30 {
  140. bail!("image too large for TLS thunks within rel32 reach");
  141. }
  142. let above = (base + size).next_multiple_of(GRANULE);
  143. for k in 0..(1usize << 14) {
  144. for hint in [
  145. base.checked_sub((k + 1) * GRANULE),
  146. Some(above + k * GRANULE),
  147. ] {
  148. let Some(hint) = hint else { continue };
  149. // SAFETY: a fresh allocation at a free address, or null.
  150. let p = unsafe {
  151. VirtualAlloc(
  152. hint as *const c_void,
  153. 4096,
  154. MEM_COMMIT | MEM_RESERVE,
  155. PAGE_READWRITE,
  156. )
  157. };
  158. if !p.is_null() {
  159. return Ok(p.cast());
  160. }
  161. }
  162. }
  163. bail!("no free page near the image for TLS thunks")
  164. }
  165. #[cfg(test)]
  166. mod tests {
  167. use super::*;
  168. /// Reads the thread's TLS array pointer the way title code does.
  169. fn tls_array() -> usize {
  170. let array: usize;
  171. // SAFETY: reads TEB.ThreadLocalStoragePointer.
  172. unsafe { std::arch::asm!("mov {}, gs:[0x58]", out(reg) array) };
  173. array
  174. }
  175. #[test]
  176. fn loads_become_calls_that_yield_the_title_slot() {
  177. let page = near(tls_array as *const () as usize, 0).unwrap();
  178. let thunks = thunks(near(page as usize, 4096).unwrap(), 3).unwrap();
  179. // (before the load, REX, ModRM, after the load): each case returns
  180. // the loaded register in rax; r12 is saved, being callee-saved.
  181. let cases: [(&[u8], u8, u8, &[u8]); 3] = [
  182. (&[], 0x48, 0x04, &[0xC3]), // rax
  183. (&[], 0x4C, 0x04, &[0x4C, 0x89, 0xC0, 0xC3]), // r8
  184. (
  185. &[0x41, 0x54],
  186. 0x4C,
  187. 0x24,
  188. &[0x4C, 0x89, 0xE0, 0x41, 0x5C, 0xC3],
  189. ), // r12
  190. ];
  191. for (before, rex, modrm, after) in cases {
  192. let mut code = before.to_vec();
  193. code.extend([0x65, rex, 0x8B, modrm, 0x25, 0x58, 0, 0, 0]);
  194. code.extend(after);
  195. // SAFETY: the page is ours and writable.
  196. let bytes = unsafe { std::slice::from_raw_parts_mut(page, code.len()) };
  197. bytes.copy_from_slice(&code);
  198. assert_eq!(patch(bytes, page as usize, thunks), 1);
  199. let mut old = 0;
  200. // SAFETY: our page, made executable to run the patched code.
  201. unsafe { VirtualProtect(page as _, 4096, PAGE_EXECUTE_READ, &mut old) };
  202. // SAFETY: the page holds the patched load and a return.
  203. let f: extern "system" fn() -> usize = unsafe { std::mem::transmute(page) };
  204. assert_eq!(f(), tls_array() + 3 * 8, "REX {rex:#x} ModRM {modrm:#x}");
  205. // SAFETY: our page again.
  206. unsafe { VirtualProtect(page as _, 4096, PAGE_READWRITE, &mut old) };
  207. }
  208. }
  209. }