using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;
public static class CaptureNative
{
public static void PublishJournal(string temporary, string destination)
{
if (File.Exists(destination)) File.Replace(temporary, destination, null);
else File.Move(temporary, destination);
}
public sealed class Window
{
public string hwnd;
public uint pid;
public string title;
public bool visible;
}
public sealed class Connection
{
public uint pid;
public string local_address;
public ushort local_port;
public string remote_address;
public ushort remote_port;
public uint state;
public ulong created_filetime;
}
[StructLayout(LayoutKind.Sequential)]
struct OwnerModule4
{
public uint state, local, localPort, remote, remotePort, pid;
public long created;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public ulong[] modules;
}
[StructLayout(LayoutKind.Sequential)]
struct OwnerModule6
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] local;
public uint localScope, localPort;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] remote;
public uint remoteScope, remotePort, state, pid;
public long created;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public ulong[] modules;
}
[StructLayout(LayoutKind.Sequential)]
struct ModuleTable4 { public uint count; public OwnerModule4 first; }
[StructLayout(LayoutKind.Sequential)]
struct ModuleTable6 { public uint count; public OwnerModule6 first; }
delegate bool EnumProc(IntPtr hwnd, IntPtr extra);
[DllImport("user32.dll")] static extern bool EnumWindows(EnumProc callback, IntPtr extra);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowText(IntPtr h, StringBuilder b, int n);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetClassName(IntPtr h, StringBuilder b, int n);
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[StructLayout(LayoutKind.Sequential)]
struct InputInfo
{
public uint size;
public uint time;
}
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref InputInfo info);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern IntPtr CommandLineToArgvW(string command, out int count);
[DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr p);
[DllImport("iphlpapi.dll", SetLastError = true)] static extern uint GetExtendedTcpTable(IntPtr p, ref int size, bool order, int family, int table, uint reserved);
public static uint InputTick()
{
var x = new InputInfo();
x.size = (uint)Marshal.SizeOf(x);
if (!GetLastInputInfo(ref x)) throw new InvalidOperationException("input metadata unavailable");
return x.time;
}
public static Window[] Windows()
{
var result = new List<Window>();
EnumWindows((h, x) =>
{
var name = new StringBuilder(256);
GetClassName(h, name, name.Capacity);
if (name.ToString() == "CASCADIA_HOSTING_WINDOW_CLASS")
{
var title = new StringBuilder(32768);
GetWindowText(h, title, title.Capacity);
uint pid;
GetWindowThreadProcessId(h, out pid);
result.Add(new Window
{
hwnd = h.ToInt64().ToString(),
pid = pid,
title = title.ToString(),
visible = IsWindowVisible(h)
});
}
return true;
}, IntPtr.Zero);
return result.ToArray();
}
public static string[] Argv(string command)
{
int n;
IntPtr p = CommandLineToArgvW(command, out n);
if (p == IntPtr.Zero) throw new InvalidOperationException("argv parse failed");
try
{
if (n > 4096) throw new InvalidOperationException("argv count exceeds bound");
var a = new string[n];
for (int i = 0; i < n; i++)
a[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(p, i * IntPtr.Size));
return a;
}
finally
{
LocalFree(p);
}
}
static uint U(IntPtr p, int offset)
{
return unchecked((uint)Marshal.ReadInt32(p, offset));
}
static ushort Port(uint value)
{
return (ushort)(((value & 255) << 8) | ((value >> 8) & 255));
}
public static Connection[] Connections()
{
var rows = new List<Connection>();
foreach (int af in new[] { 2, 23 })
{
int size = 0;
uint rc = GetExtendedTcpTable(IntPtr.Zero, ref size, false, af, 8, 0);
if (rc != 122 && rc != 0) throw new InvalidOperationException("TCP size query failed " + rc);
if (size < 4 || size > 16 * 1024 * 1024) throw new InvalidOperationException("TCP table size invalid");
for (int retry = 0; retry < 3; retry++)
{
IntPtr p = Marshal.AllocHGlobal(size);
try
{
rc = GetExtendedTcpTable(p, ref size, false, af, 8, 0);
if (rc == 122)
{
if (size > 16 * 1024 * 1024) throw new InvalidOperationException("TCP table exceeds bound");
continue;
}
if (rc != 0) throw new InvalidOperationException("TCP query failed " + rc);
int count = Marshal.ReadInt32(p);
int rowSize = Marshal.SizeOf(af == 2 ? typeof(OwnerModule4) : typeof(OwnerModule6));
int offset = Marshal.OffsetOf(af == 2 ? typeof(ModuleTable4) : typeof(ModuleTable6), "first").ToInt32();
int timestampOffset = Marshal.OffsetOf(af == 2 ? typeof(OwnerModule4) : typeof(OwnerModule6), "created").ToInt32();
if (rowSize != (af == 2 ? 160 : 192) || offset != 8 || timestampOffset != (af == 2 ? 24 : 56)) throw new InvalidOperationException("Unsupported owner-module TCP layout");
if (count < 0 || count > (size - offset) / rowSize) throw new InvalidOperationException("TCP table malformed");
for (int i = 0; i < count; i++)
{
IntPtr r = IntPtr.Add(p, offset + i * rowSize);
if (Port(U(r, af == 2 ? 8 : 20)) == 0 || Port(U(r, af == 2 ? 16 : 44)) == 0) continue;
if (af == 2 && (U(r,4) == 0 || U(r,12) == 0)) continue;
long created = Marshal.ReadInt64(r, timestampOffset);
if (af == 2) rows.Add(new Connection
{
pid = U(r, 20),
local_address = new IPAddress(U(r, 4)).ToString(),
local_port = Port(U(r, 8)),
remote_address = new IPAddress(U(r, 12)).ToString(),
remote_port = Port(U(r, 16)),
state = U(r, 0),
created_filetime = created > 0 ? (ulong)created : 0
});
else
{
byte[] a = new byte[16], b = new byte[16];
Marshal.Copy(r, a, 0, 16);
Marshal.Copy(IntPtr.Add(r, 24), b, 0, 16);
bool zeroLocal = true, zeroRemote = true;
for (int j=0; j<16; j++) { zeroLocal &= a[j] == 0; zeroRemote &= b[j] == 0; }
if (zeroLocal || zeroRemote) continue;
rows.Add(new Connection
{
pid = U(r, 52),
local_address = new IPAddress(a, U(r, 16)).ToString(),
local_port = Port(U(r, 20)),
remote_address = new IPAddress(b, U(r, 40)).ToString(),
remote_port = Port(U(r, 44)),
state = U(r, 48),
created_filetime = created > 0 ? (ulong)created : 0
});
}
}
break;
}
finally
{
Marshal.FreeHGlobal(p);
}
}
if (rc != 0) throw new InvalidOperationException("TCP table changed repeatedly");
}
return rows.ToArray();
}
}
public static class ConsoleProbe
{
[DllImport("kernel32.dll", SetLastError = true)] static extern bool AttachConsole(uint pid);
[DllImport("kernel32.dll", SetLastError = true)] static extern uint GetConsoleProcessList([Out] uint[] ids, uint count);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern uint GetConsoleTitle(StringBuilder title, uint size);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool SetConsoleTitle(string title);
[DllImport("kernel32.dll")] static extern bool FreeConsole();
static string Title()
{
var b = new StringBuilder(32768);
GetConsoleTitle(b, (uint)b.Capacity);
return b.ToString();
}
static uint[] Members()
{
var a = new uint[4096];
uint n = GetConsoleProcessList(a, (uint)a.Length);
if (n == 0 || n > a.Length) throw new InvalidOperationException("console members unavailable or exceed bound");
Array.Resize(ref a, (int)n);
return a;
}
static bool Same(int pid, long ticks)
{
try
{
return Process.GetProcessById(pid).StartTime.ToUniversalTime().Ticks == ticks;
}
catch
{
return false;
}
}
static void Write(string path, object value)
{
string tmp = path + ".new";
File.WriteAllText(tmp, new JavaScriptSerializer().Serialize(value), new UTF8Encoding(false));
if (File.Exists(path)) File.Delete(path);
File.Move(tmp, path);
}
public static int Main(string[] args)
{
if (args.Length != 7) return 64;
uint pid = uint.Parse(args[0]);
long ticks = long.Parse(args[1]);
string output = args[2], nonce = args[3], lease = args[4];
int parent = int.Parse(args[5]);
long parentTicks = long.Parse(args[6]);
bool attached = false;
string old = null;
bool changed = false;
var report = new Dictionary<string, object>();
report["pid"] = pid;
report["start_ticks"] = ticks;
report["ready"] = false;
report["done"] = false;
try
{
uint[] initial = new uint[4096];
uint count = GetConsoleProcessList(initial, (uint)initial.Length);
if (count > 0)
{
if (count != 1 || initial[0] != (uint)Process.GetCurrentProcess().Id) throw new InvalidOperationException("helper inherited shared console; refused detach");
if (!FreeConsole()) throw new InvalidOperationException("helper private console detach failed");
}
if (!Same((int)pid, ticks) || !Same(parent, parentTicks)) throw new InvalidOperationException("process identity changed before attach");
if (!AttachConsole(pid)) throw new InvalidOperationException("AttachConsole failed " + Marshal.GetLastWin32Error());
attached = true;
if (!Same((int)pid, ticks)) throw new InvalidOperationException("process identity changed after attach");
var before = Members();
report["members"] = before;
old = Title();
report["title"] = old;
if (nonce.Length > 0)
{
if (!File.Exists(lease)) throw new InvalidOperationException("challenge lease missing");
if (!SetConsoleTitle(nonce)) throw new InvalidOperationException("title challenge unavailable");
changed = true;
report["ready"] = true;
Write(output, report);
var watch = Stopwatch.StartNew();
while (watch.ElapsedMilliseconds < 2500 && File.Exists(lease) && Same(parent, parentTicks)) Thread.Sleep(10);
}
report["members_after"] = Members();
if (!Same((int)pid, ticks)) throw new InvalidOperationException("process identity changed during observation");
report["identity_valid"] = true;
}
catch (Exception e)
{
report["error"] = e.Message;
}
finally
{
if (attached)
{
if (changed)
{
try
{
bool unchanged = Title() == nonce;
report["title_restore"] = unchanged ? (SetConsoleTitle(old) ? "restored" : "failed") : "owner_changed";
}
catch
{
report["title_restore"] = "failed";
}
}
FreeConsole();
}
report["done"] = true;
try
{
Write(output, report);
}
catch
{
}
}
return report.ContainsKey("error") ? 1 : 0;
}
}