fibers icon indicating copy to clipboard operation
fibers copied to clipboard

Missing shadow stack and other fiber state on Windows

Open avakar opened this issue 3 years ago • 3 comments

This is what's currently (Windows 10.0.22000) part of the fiber state on Windows:

  • non-volatile CPU registers (rbx, rbp, rsi, rdi, r12 through r15, xmm6 through xmm15, x87 state),
  • shadow stack pointer, for which you also need to allocate special stack (malloc memory won't do, it has to be allocated/freed via NtSetInformationProcess, but is reusable),
  • stack limits in TEB (these are actually relevant in other places than RTC, like stack-walking in SEH, guard-page handling, stack overflow handling... and it's unwise to not switch them)
TEB+0x0008 StackBase
TEB+0x0010 StackLimit
TEB+0x1478 DeallocationStack
TEB+0x1748 GuaranteedStackBytes
  • ActivationContextStackPointer at TEB+0x02c8, which needs to be allocated and freed for each fiber via RtlAllocateActivationContextStack and RtlFreeActivationContextStack, otherwise random parts of Windows API that touch it will malfunction; reusable,

  • FlsData at TEB+0x17c8 (these are allocated lazily, so can be initialized to 0, but need to be freed when deleting the fiber via RtlProcessFlsData(FlsData, /*Flags=*/3); you may clear it via RtlProcessFlsData(FlsData, 1) when reusing, though it's probably not strictly necessary), FLS is used internally by Microsoft's awful exception handling code and will get used whenever an exception is thrown.

The noteworthy part of the above sentence is the word currently. Shadow stack, for example, wasn't a thing a year ago. I would recommend using SwitchToFiber instead. You can reuse the fiber state fairly easily by switching out of the fiber instead of deleting it.

avakar avatar Nov 29 '21 09:11 avakar