49 lines
2.5 KiB
C#
49 lines
2.5 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.IO.Pipes;
|
|
using System.Reflection;
|
|
using System.Runtime.InteropServices;
|
|
using System.Security.Cryptography;
|
|
using System.Security.Principal;
|
|
using System.Text;
|
|
|
|
namespace PlotDirector.WordAddIn
|
|
{
|
|
internal static class AgentProcess
|
|
{
|
|
internal static string PipeName()
|
|
{
|
|
var value = WindowsIdentity.GetCurrent().User.Value + ":" + Process.GetCurrentProcess().SessionId;
|
|
using (var hash = SHA256.Create()) return "PlotDirector.Companion.v1." + BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(value))).Replace("-", "").Substring(0,24);
|
|
}
|
|
// Called only on the IPC worker. No Word objects, UI calls or shell search paths.
|
|
internal static void Start()
|
|
{
|
|
var root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
|
var executable = Path.Combine(root,"Agent","PlotDirector.Companion.Agent.exe");
|
|
if (!File.Exists(executable)) return;
|
|
using (Process.Start(new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(executable) })) { }
|
|
}
|
|
internal static bool VerifyOwner(NamedPipeClientStream pipe)
|
|
{
|
|
uint processId;
|
|
if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle.DangerousGetHandle(),out processId)) return false;
|
|
var process = OpenProcess(0x1000,false,processId);
|
|
if (process == IntPtr.Zero) return false;
|
|
IntPtr token = IntPtr.Zero;
|
|
try
|
|
{
|
|
if (!OpenProcessToken(process,8,out token)) return false;
|
|
using (var identity = new WindowsIdentity(token))
|
|
using (var current = WindowsIdentity.GetCurrent()) return identity.User == current.User;
|
|
}
|
|
finally { if(token != IntPtr.Zero)CloseHandle(token); CloseHandle(process); }
|
|
}
|
|
[DllImport("kernel32.dll",SetLastError=true)] private static extern bool GetNamedPipeServerProcessId(IntPtr pipe,out uint processId);
|
|
[DllImport("kernel32.dll",SetLastError=true)] private static extern IntPtr OpenProcess(uint access,bool inherit,uint processId);
|
|
[DllImport("advapi32.dll",SetLastError=true)] private static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token);
|
|
[DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr handle);
|
|
}
|
|
}
|