title: Hooking Windows Kernel Dispatcher for System Calls
body: <p>I'm trying to hook <code>SYSENTER</code> dispatch function from the kernel and during the past few days I was studying about what happens when a program executes <code>SYSENTER</code> and wants to enter to kernel then I realized <code>IA32_SYSENTER_EIP</code> and <code>IA32_SYSENTER_ESP</code> are responsible to set the kernel <code>RIP</code> and <code>RSP</code> after <code>SYSENTER</code>.</p>
  
  <p>Yesterday I read Intel Software Developer Manuals about <code>SWAPGS</code> :</p>
  
  <blockquote>
    <p>SWAPGS exchanges the current GS base register value with the value contained in MSR address C0000102H (IA32_KERNEL_GS_BASE). The SWAPGS instruction is a privileged instruction intended for use by system software.</p>
    
    <p>When using SYSCALL to implement system calls, there is no kernel stack
    at the OS entry point. Neither is there a straightforward method to
    obtain a pointer to kernel structures from which the kernel stack
    pointer could be read. Thus, the kernel cannot save general purpose
    registers or reference memory.</p>
  </blockquote>
  
  <p>From the second paragraph, <code>there is no kernel stack at the OS entry point</code> seems that OS kernel executes <code>SWAPGS</code> to set the <code>GS</code> and then get the kernel stack pointer but as I read, in a <code>SYSENTER</code> kernel RIP(EIP) and RSP (ESP) should set from <code>IA32_SYSENTER_EIP</code> and <code>IA32_SYSENTER_ESP</code> so the kernel has its stack pointer in <code>IA32_SYSENTER_ESP</code> !</p>
  
  <p>My Questions :</p>
  
  <ol>
  <li>If kernel stack address should come from GS then what's the purpose of <code>IA32_SYSENTER_ESP</code>?</li>
  <li>What are differences between <code>AMD LSTAR (0xC0000082)</code> and <code>IA32_SYSENTER_EIP</code>? I ask it because I saw Windows set 0xc0000082 on my Intel processor.</li>
  <li>Is there any special problem with hooking kernels SYSENTER dispatcher?It's because whenever I put a breakpoint in Windows function which is responsible for dispatching SYSENTER calls (KiSystemCall64Shadow) on a remote debugging machine (Not VM) then it causes BSOD with UNEXPECTED_KERNEL_MODE_TRAP.</li>
  </ol>