Today just some fun stuff with ASM, probably not the most recommended way to do things but for sure the most geeky way :P

Get the Current Session Id:

function GetCurrentSessionId: DWORD;
asm
  mov     eax,fs:[$00000018];   // Get TEB
  mov     eax,[eax+$30];        // PPEB
  mov     eax,[eax+$1d4];       // PEB.SessionId
end;
 

Get the Current Console Session Id:

function GetConsoleSessionId: DWORD;
asm
  mov eax, [$7ffe02d8];
end;

And… if we can read it we can also write it?

procedure SetCurrentSessionId(const SessionId: DWORD);
asm
  mov     edx,fs:[$00000018];
  mov     edx,[edx+$30];
  mov     [edx+$1d4], SessionId;
end;

and

procedure SetConsoleSessionId(const SessionId: DWORD);
var
  p: PDWORD;
  OldProtect: DWORD;
begin
  p := PDWORD($7ffe02d8);
  Win32Check(VirtualProtect(p, SizeOf(p), PAGE_READWRITE, @OldProtect));
  p^ := SessionId;
  Win32Check(VirtualProtect(p, SizeOf(p), OldProtect, @OldProtect));
end;

You can safely try it since it of course affects the current process only, so don’t worry.

And perhaps more usefull

procedure SetIsDebuggerPresent(const Value: Boolean);
asm
  mov edx,fs:[$00000018];     // TEB
  mov edx, [edx+$30];         // PPEB
  mov byte ptr[edx+2], Value; // +0×002 BeingDebugged    : UChar
end;
 

No related posts.