using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
public static class PassiveEnvironment
{
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint rights, bool inherit, uint pid);
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll")] static extern bool IsWow64Process(IntPtr handle, out bool wow64);
[DllImport("kernel32.dll")] static extern bool ReadProcessMemory(IntPtr handle, IntPtr address, byte[] buffer, UIntPtr size, out UIntPtr read);
[DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr handle, int kind, IntPtr[] data, int size, out int returned);
static byte[] Read(IntPtr handle, long address, int count)
{
if (address <= 0) throw new InvalidOperationException();
var bytes = new byte[count]; UIntPtr read;
if (!ReadProcessMemory(handle, new IntPtr(address), bytes, (UIntPtr)count, out read) || read.ToUInt64() != (ulong)count) throw new InvalidOperationException();
return bytes;
}
public static string Session(uint pid, long creationTicks)
{
if (IntPtr.Size != 8) throw new InvalidOperationException("Passive process binding requires x64 PowerShell");
var h = OpenProcess(0x410, false, pid);
if (h == IntPtr.Zero) return null;
try
{
if (Process.GetProcessById((int)pid).StartTime.ToUniversalTime().Ticks != creationTicks) return null;
bool wow64;
if (!IsWow64Process(h, out wow64) || wow64) return null;
var basic = new IntPtr[6]; int returned;
if (NtQueryInformationProcess(h, 0, basic, 48, out returned) != 0 || returned != 48) return null;
long parameters = BitConverter.ToInt64(Read(h, basic[1].ToInt64() + 0x20, 8), 0);
long environment = BitConverter.ToInt64(Read(h, parameters + 0x80, 8), 0);
var text = new StringBuilder(); bool ended = false;
for (int offset = 0; offset < 262144 && !ended; offset += 2)
{
int count = Math.Min(4096 - (int)((environment + offset) & 4095), 262144 - offset);
byte[] bytes;
try { bytes = Read(h, environment + offset, count); }
catch { bytes = Read(h, environment + offset, 2); count = 2; }
text.Append(Encoding.Unicode.GetString(bytes));
ended = text.ToString().IndexOf("\0\0", StringComparison.Ordinal) >= 0;
offset += count - 2;
}
if (!ended) return null;
string result = null;
string block = text.ToString();
block = block.Substring(0, block.IndexOf("\0\0", StringComparison.Ordinal));
foreach (var entry in block.Split('\0'))
if (entry.StartsWith("WT_SESSION=", StringComparison.OrdinalIgnoreCase))
{
Guid id;
if (result != null || !Guid.TryParse(entry.Substring(11), out id)) return null;
result = id.ToString("D");
}
if (Process.GetProcessById((int)pid).StartTime.ToUniversalTime().Ticks != creationTicks) return null;
return result;
}
catch { return null; }
finally { CloseHandle(h); }
}
}