Enumerating Session Processes with NtQuerySystemInformation

As you may know, you can enumerate processes of a specific Terminal Server or Citrix session using the NtQuerySystemInformation function.

On x86 system the code below works fine:

While this works fine on Windows XP and 2003 x86, it fails to work correctly on the x64 versions of Windows XP and 2003 (or maybe even higher).

The problem is that RetLength is always SizeOf(SYSTEM_SESSION_PROCESS_INFORMATION) and thus we are in an endless loop!

If you disassemble an a call to NtQuerySystemInformation, for example in the CreateToolhelp32Snapshot API, you will see that it just executes NtQuerySystemInformation and increases the buffer size in a loop.

Ok, let’s do it in the same way 🙂

But this code doesn’t work as well. The reason is that you need to place the whole buffer in a contiguous memory area.

So finally the working code is :