// .text:00536238 F3 0F 11 0D EC+ movss dword_1B134EC, xmm1 public override bool HandleException(ref CONTEXT ctx, ProcessDebugger pd) { ctx.Eip += 8; WriteVals(1000, 1000, pd); return true; }
public Context(Process process) { isContext64 = process.IsWin64; if (process.IsWin64) { context64 = new CONTEXT(); context64.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL; } else { context32 = new Context32(); context32.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL; } }
public Context(Process process, IntPtr hThread) { isContext64 = process.IsWin64; if (process.IsWin64) { context64 = new CONTEXT(); context64.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL; } else { context32 = new Context32(); context32.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL; } GetContext(hThread); //if (!GetContext(hThread)) // throw new Exception("Failed to GetContext(), get last error: " + Debugger.GetLastError().ToString()); }
static bool WritePayload(ref PROCESS_INFORMATION Process, string DllPath) { CONTEXT CurrentCtx = new CONTEXT(); CurrentCtx.ContextFlags = CONTEXT_FLAGS.CONTEXT_CONTROL | CONTEXT_FLAGS.CONTEXT_INTEGER; if (!GetThreadContext(Process.hThread, ref CurrentCtx)) { return(false); } IntPtr LoadLibraryPtr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryW"); if (LoadLibraryPtr == IntPtr.Zero) { return(false); } var Buffer = VirtualAllocEx(Process.hProcess, IntPtr.Zero, 4 * 1024, AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite); if (Buffer == IntPtr.Zero) { return(false); } var DllNameBytes = PerpareDllPathOrName(DllPath); if (!WriteProcessMemory( Process.hProcess, Buffer, DllNameBytes, DllNameBytes.Length, out int Written) || Written != DllNameBytes.Length) { return(false); } var ReturnAddress = CurrentCtx.Eip; CurrentCtx.Eip = (uint)(((uint)Buffer + DllNameBytes.Length) / 16 + 3) * 16; // Construct shell code var Shellcode = new byte[] { 0x50, // push eax 0xb8, 0x00, 0x00, 0x00, 0x00, // mov eax, <Buffer> 0x50, // push eax 0xb8, 0x00, 0x00, 0x00, 0x00, // mov eax, <LoadLibraryW> 0xff, 0xd0, // call eax 0x58, // pop eax 0xe9, 0x00, 0x00, 0x00, 0x00 // jmp <returnAddress> }; Array.Copy(BitConverter.GetBytes((int)Buffer), 0, Shellcode, 2, 4); Array.Copy(BitConverter.GetBytes((int)LoadLibraryPtr), 0, Shellcode, 8, 4); Array.Copy(BitConverter.GetBytes(ReturnAddress - CurrentCtx.Eip - Shellcode.Length), 0, Shellcode, Shellcode.Length - 4, 4); if (!WriteProcessMemory( Process.hProcess, (IntPtr)CurrentCtx.Eip, Shellcode, Shellcode.Length, out Written) || Written != Shellcode.Length) { return(false); } if (!SetThreadContext(Process.hThread, ref CurrentCtx)) { return(false); } if (!ResumeThread(Process.hThread)) { return(false); } return(true); }
public static extern bool GetThreadContext(ulong hThread, ref CONTEXT lpContext);
private void StartListener(uint WaitInterval = 200) { var DebugEvent = new DEBUG_EVENT(); for (; IsDebugging;) { if (!Kernel32.WaitForDebugEvent(ref DebugEvent, WaitInterval)) { if (!IsDebugging) { break; } continue; } //Console.WriteLine("Debug Event Code: {0} ", DebugEvent.dwDebugEventCode); bool okEvent = false; switch (DebugEvent.dwDebugEventCode) { case DebugEventType.RIP_EVENT: case DebugEventType.EXIT_PROCESS_DEBUG_EVENT: //Console.WriteLine("Process has exited"); IsDebugging = false; IsDetached = true; if (!Kernel32.ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, okEvent ? (uint)DebugContinueStatus.DBG_CONTINUE : (uint)DebugContinueStatus.DBG_EXCEPTION_NOT_HANDLED)) { throw new DebuggerException("Failed to continue debug event"); } if (!Kernel32.DebugActiveProcessStop(Process.Id)) { throw new DebuggerException("Failed to stop process debugging"); } return; case DebugEventType.EXCEPTION_DEBUG_EVENT: //Console.WriteLine("Exception Code: {0:X}", DebugEvent.Exception.ExceptionRecord.ExceptionCode); if (DebugEvent.Exception.ExceptionRecord.ExceptionCode == (uint)ExceptonStatus.STATUS_SINGLE_STEP) { okEvent = true; /*if (DebugEvent.dwThreadId != threadId) * { * Console.WriteLine("Debug event thread id does not match breakpoint thread"); * break; * }*/ var hThread = Kernel32.OpenThread(ThreadAccess.THREAD_ALL_ACCESS, false, DebugEvent.dwThreadId); if (hThread == IntPtr.Zero) { throw new DebuggerException("Failed to open thread"); } var Context = new CONTEXT(); Context.ContextFlags = CONTEXT_FLAGS.CONTEXT_FULL; if (!Kernel32.GetThreadContext(hThread, Context)) { throw new DebuggerException("Failed to get thread context"); } if (!Breakpoints.Any(e => e != null && e.IsSet && e.Address.ToUInt32() == Context.Eip)) { break; } var bp = Breakpoints.First(e => e != null && e.IsSet && e.Address.ToUInt32() == Context.Eip); var ContextWrapper = new ContextWrapper(this, Context); if (bp.HandleException(ContextWrapper)) { if (!Kernel32.SetThreadContext(hThread, ContextWrapper.Context)) { throw new DebuggerException("Failed to set thread context"); } } } break; case DebugEventType.CREATE_THREAD_DEBUG_EVENT: { foreach (var bp in Breakpoints) { bp.SetToThread(DebugEvent.CreateThread.hThread, DebugEvent.dwThreadId); } break; } case DebugEventType.EXIT_THREAD_DEBUG_EVENT: { foreach (var bp in Breakpoints) { bp.UnregisterThread(DebugEvent.dwThreadId); } break; } default: break; } if (!IsDebugging) { IsDetached = true; RemoveBreakPoints(); if (!Kernel32.ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, okEvent ? (uint)DebugContinueStatus.DBG_CONTINUE : (uint)DebugContinueStatus.DBG_EXCEPTION_NOT_HANDLED)) { throw new DebuggerException("Failed to continue debug event"); } if (!Kernel32.DebugActiveProcessStop(Process.Id)) { throw new DebuggerException("Failed to stop process debugging"); } return; } if (!Kernel32.ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, okEvent ? (uint)DebugContinueStatus.DBG_CONTINUE : (uint)DebugContinueStatus.DBG_EXCEPTION_NOT_HANDLED)) { throw new DebuggerException("Failed to continue debug event"); } } Detach(); }
public static unsafe bool Execute(LoadParams args) { bool isWow64 = false; PROCESS_INFORMATION lpProcesSystemNetCertPolicyValidationCallbackv = new PROCESS_INFORMATION(); CONTEXT context = new CONTEXT() { ContextFlags = 1048603 }; IntPtr lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU; IMAGE_DOS_HEADER *imageDosHeaderPtr; IMAGE_NT_HEADERS *imageNtHeadersPtr; fixed(byte *numPtr = args.Body) { lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU = (IntPtr)((void *)numPtr); imageDosHeaderPtr = (IMAGE_DOS_HEADER *)numPtr; imageNtHeadersPtr = (IMAGE_NT_HEADERS *)(numPtr + imageDosHeaderPtr->e_lfanew); } if (imageDosHeaderPtr->e_magic != (ushort)23117 || imageNtHeadersPtr->Signature != 17744U || imageNtHeadersPtr->OptionalHeader.Magic != (ushort)267) { return(false); } Buffer.SetByte((Array)args.Body, 920, (byte)2); STARTUPINFO lpStartupInfo = new STARTUPINFO(); lpStartupInfo.cb = Marshal.SizeOf((object)lpStartupInfo); lpStartupInfo.wShowWindow = (short)0; using (LibInvoker libInvoker1 = new LibInvoker("kernel32.dll")) { using (LibInvoker libInvoker2 = new LibInvoker("ntdll.dll")) { if (!libInvoker1.CastToDelegate <NativeDelegates.CreateProcessInternalWDelegate>("CreateProcessInternalW")(0U, (string)null, args.AppPath, IntPtr.Zero, IntPtr.Zero, false, 134217740U, IntPtr.Zero, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), ref lpStartupInfo, out lpProcesSystemNetCertPolicyValidationCallbackv, 0U)) { if (lpProcesSystemNetCertPolicyValidationCallbackv.hProcess != IntPtr.Zero && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; } return(false); } int num3 = libInvoker1.CastToDelegate <NativeDelegates.IsWow64ProcessDelegate>("IsWow64Process")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, ref isWow64) ? 1 : 0; IntPtr imageBase = (IntPtr)((long)imageNtHeadersPtr->OptionalHeader.ImageBase); int num4 = (int)libInvoker2.CastToDelegate <NativeDelegates.NtUnmapViewOfSectionDelegate>("NtUnmapViewOfSection")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase); if (libInvoker1.CastToDelegate <NativeDelegates.VirtualAllocExDelegate>("VirtualAllocEx")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase, imageNtHeadersPtr->OptionalHeader.SizeOfImage, 12288U, 64U) == IntPtr.Zero && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, imageBase, lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU, imageNtHeadersPtr->OptionalHeader.SizeOfHeaders, IntPtr.Zero) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } for (ushort index = 0; (int)index < (int)imageNtHeadersPtr->FileHeader.NumberOfSections; ++index) { IMAGE_SECTION_HEADER *imageSectionHeaderPtr = (IMAGE_SECTION_HEADER *)((ulong)lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + (ulong)imageDosHeaderPtr->e_lfanew + (ulong)Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)) + (ulong)(Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (int)index)); if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)(imageBase.ToInt64() + (long)imageSectionHeaderPtr->VirtualAddress), (IntPtr)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + (long)imageSectionHeaderPtr->PointerToRawData), imageSectionHeaderPtr->SizeOfRawData, IntPtr.Zero) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } if (isWow64) { if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("Wow64GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } else if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } IntPtr num5 = Marshal.AllocHGlobal(8); ulong int64 = (ulong)imageBase.ToInt64(); byte[] source = new byte[8]; for (int index = 0; index < 8; ++index) { source[index] = (byte)(int64 >> index * 8); if (index == 7) { Marshal.Copy(source, 0, num5, 8); } } if (!libInvoker1.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)((long)context.Ebx + 8L), num5, 4U, IntPtr.Zero)) { Marshal.FreeHGlobal(num5); if (libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } Marshal.FreeHGlobal(num5); context.Eax = (uint)((ulong)imageBase.ToInt64() + (ulong)imageNtHeadersPtr->OptionalHeader.AddressOfEntryPoint); if (isWow64) { if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("Wow64SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } } else if (!libInvoker1.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &context) && libInvoker1.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { int num1 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num2 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; return(false); } int num6 = (int)libInvoker1.CastToDelegate <NativeDelegates.ResumeThreadDelegate>("ResumeThread")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); int num7 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess) ? 1 : 0; int num8 = libInvoker1.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread) ? 1 : 0; } } return(true); }
protected void FileManagerWindow() { try { EditorGUILayout.LabelField("Localization files", EditorStyles.boldLabel); EditorGUILayout.Space(); EditorGUILayout.BeginScrollView(this.scrollPositionFileManager, GUILayout.MaxWidth(450), GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false)); foreach (string entry in LocalizatronEditor.langFiles) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUILayout.TextField(Path.GetFileName(entry).Replace(Settings.LANGUAGE_EXTENSION, "")); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); if (GUILayout.Button("Delete", EditorStyles.miniButtonLeft, GUILayout.Width(45))) { OnDeleteFileInFileManagerWindow(entry); } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); if (GUILayout.Button("Edit", EditorStyles.miniButtonRight, GUILayout.Width(45))) { this.selectedFile = Path.GetFileName(entry).Replace(Settings.LANGUAGE_EXTENSION, ""); this.localeDict = this.inEditorLoadLanguageTable(Application.dataPath + Settings.SAVING_LANGUAGE_PATH + this.selectedFile + Settings.LANGUAGE_EXTENSION); if (this.localeDict.Count == 0) { this.localeDict.Add("Entry-" + DateTime.Now.Ticks, ""); } this._context = CONTEXT.EDIT_FILE; LocalizatronEditor.Log("Selected localization file: " + this.selectedFile); } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); this.newFileName = EditorGUILayout.TextField(this.newFileName); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); if (GUILayout.Button("Add new localization file")) { if (this.newFileName != "" && this.newFileName != null) { LocalizatronEditor.langFiles.Add(Settings.LANGUAGE_PATH + this.newFileName); LocalizatronEditor.SaveLocalizationFile(this.newFileName, "<key></key><value></value>"); this.newFileName = ""; } else { LocalizatronEditor.Log("You cannot add an unnamed file!"); } } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndScrollView(); } catch { if (LocalizatronEditor.IS_DEBUG) { LocalizatronEditor.Log("Updated missing ref of deleted file"); } EditorGUILayout.EndScrollView(); } }
public int ResumeProcState(int pid, string filename) { AllocConsole(); //建文件流 System.IO.FileStream stream = null; stream = new System.IO.FileStream(filename, System.IO.FileMode.Open); byte[] descriptioncount = new byte[1]; //读出exe文件路径长度 stream.Read(descriptioncount, 0, descriptioncount.Length); int descount = Convert.ToInt32(descriptioncount[0]); char[] procdescription = new char[descount]; byte[] bytedescription = new byte[descount]; //读出exe文件路径 stream.Read(bytedescription, 0, bytedescription.Length); for (int j = 0; j < descount; j++) { procdescription[j] = Convert.ToChar(bytedescription[j]); } string description = new string(procdescription); //新建进程 SECURITY_ATTRIBUTES process = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES thread = new SECURITY_ATTRIBUTES(); STARTUPINFO info = new STARTUPINFO(); PROCESS_INFORMATION proinfo = new PROCESS_INFORMATION(); if (CreateProcess( null, description, ref process, ref thread, false, (uint)CreateProcessFlags.NORMAL_PRIORITY_CLASS, (IntPtr)null, null, ref info, out proinfo)) { IntPtr prohandle = proinfo.hProcess; IntPtr thrhandle = proinfo.hThread; System.Threading.Thread.Sleep(5000); SuspendThread(thrhandle); //打印信息 CONTEXT tt = new CONTEXT(); tt.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; GetThreadContext(thrhandle, ref tt); Console.WriteLine(thrhandle); Console.WriteLine("Ebp : {0}", tt.Ebp); Console.WriteLine("Eip : {0}", tt.Eip); Console.WriteLine("SegCs : {0}", tt.SegCs); Console.WriteLine("EFlags : {0}", tt.EFlags); Console.WriteLine("Esp : {0}", tt.Esp); Console.WriteLine("SegSs : {0}", tt.SegSs); Console.WriteLine("Dr0 : {0}", tt.Dr0); Console.WriteLine("Dr1 : {0}", tt.Dr1); Console.WriteLine("Dr2 : {0}", tt.Dr2); Console.WriteLine("Dr3 : {0}", tt.Dr3); Console.WriteLine("Dr6 : {0}", tt.Dr6); Console.WriteLine("Dr7 : {0}", tt.Dr7); Console.WriteLine("SegGs : {0}", tt.SegGs); Console.WriteLine("SegFs : {0}", tt.SegFs); Console.WriteLine("Seges : {0}", tt.SegEs); Console.WriteLine("SegDs : {0}", tt.SegDs); Console.WriteLine("Edi : {0}", tt.Edi); Console.WriteLine("Esi : {0}", tt.Esi); Console.WriteLine("Ebx : {0}", tt.Ebx); Console.WriteLine("Edx : {0}", tt.Edx); Console.WriteLine("Ecx : {0}", tt.Ecx); Console.WriteLine("Eax : {0}", tt.Eax); ResumeThread(thrhandle); System.Threading.Thread.Sleep(5000); SuspendThread(thrhandle); CONTEXT ttt = new CONTEXT(); ttt.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; GetThreadContext(thrhandle, ref ttt); Console.WriteLine(thrhandle); Console.WriteLine("Ebp : {0}", ttt.Ebp); Console.WriteLine("Eip : {0}", ttt.Eip); Console.WriteLine("SegCs : {0}", ttt.SegCs); Console.WriteLine("EFlags : {0}", ttt.EFlags); Console.WriteLine("Esp : {0}", ttt.Esp); Console.WriteLine("SegSs : {0}", ttt.SegSs); Console.WriteLine("Dr0 : {0}", ttt.Dr0); Console.WriteLine("Dr1 : {0}", ttt.Dr1); Console.WriteLine("Dr2 : {0}", ttt.Dr2); Console.WriteLine("Dr3 : {0}", ttt.Dr3); Console.WriteLine("Dr6 : {0}", ttt.Dr6); Console.WriteLine("Dr7 : {0}", ttt.Dr7); Console.WriteLine("SegGs : {0}", ttt.SegGs); Console.WriteLine("SegFs : {0}", ttt.SegFs); Console.WriteLine("Seges : {0}", ttt.SegEs); Console.WriteLine("SegDs : {0}", ttt.SegDs); Console.WriteLine("Edi : {0}", ttt.Edi); Console.WriteLine("Esi : {0}", ttt.Esi); Console.WriteLine("Ebx : {0}", ttt.Ebx); Console.WriteLine("Edx : {0}", ttt.Edx); Console.WriteLine("Ecx : {0}", ttt.Ecx); Console.WriteLine("Eax : {0}", ttt.Eax); //读取线程数 byte[] bytecount = new byte[1]; stream.Read(bytecount, 0, bytecount.Length); int count = Convert.ToInt32(bytecount[0]); int threadid = proinfo.dwThreadId; CONTEXT[] context = new CONTEXT[count]; for (int i = 0; i < count; i++) { //读取原先的线程句柄 byte[] byteAgohandlecount = new byte[1]; stream.Read(byteAgohandlecount, 0, byteAgohandlecount.Length); int Agohandlecount = Convert.ToInt32(byteAgohandlecount[0]); Console.WriteLine(Agohandlecount); byte[] byteAgohandle = new byte[Agohandlecount]; stream.Read(byteAgohandle, 0, byteAgohandle.Length); char[] charAgohandle = new char[Agohandlecount]; for (int bi = 0; bi < Agohandlecount; bi++) { charAgohandle[bi] = Convert.ToChar(byteAgohandle[bi]); } string stringAgohandle = new string(charAgohandle); IntPtr Agohandle = (IntPtr)Convert.ToInt32(stringAgohandle); Console.WriteLine(Agohandle); //读上下文 byte[] bydata = new byte[Marshal.SizeOf(context[i])]; stream.Read(bydata, 0, bydata.Length); context[i] = Deserialize(bydata); Console.WriteLine("Ebp : {0}", context[i].Ebp); Console.WriteLine("Eip : {0}", context[i].Eip); Console.WriteLine("SegCs : {0}", context[i].SegCs); Console.WriteLine("EFlags : {0}", context[i].EFlags); Console.WriteLine("Esp : {0}", context[i].Esp); Console.WriteLine("SegSs : {0}", context[i].SegSs); Console.WriteLine("Dr0 : {0}", context[i].Dr0); Console.WriteLine("Dr1 : {0}", context[i].Dr1); Console.WriteLine("Dr2 : {0}", context[i].Dr2); Console.WriteLine("Dr3 : {0}", context[i].Dr3); Console.WriteLine("Dr6 : {0}", context[i].Dr6); Console.WriteLine("Dr7 : {0}", context[i].Dr7); Console.WriteLine("SegGs : {0}", context[i].SegGs); Console.WriteLine("SegFs : {0}", context[i].SegFs); Console.WriteLine("Seges : {0}", context[i].SegEs); Console.WriteLine("SegDs : {0}", context[i].SegDs); Console.WriteLine("Edi : {0}", context[i].Edi); Console.WriteLine("Esi : {0}", context[i].Esi); Console.WriteLine("Ebx : {0}", context[i].Ebx); Console.WriteLine("Edx : {0}", context[i].Edx); Console.WriteLine("Ecx : {0}", context[i].Ecx); Console.WriteLine("Eax : {0}", context[i].Eax); context[i].ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; IntPtr Nowhandle = OpenThread(ThreadAccess.SET_CONTEXT, false, (uint)threadid); // Console.WriteLine(Nowhandle); // context[i] = HandleToHandle(Agohandle, Nowhandle, context[i]); tt.Eax = context[i].Eax; tt.Ebx = context[i].Ebx; tt.Ecx = context[i].Ecx; tt.Edx = context[i].Edx; //tt.Ebp = context[i].Ebp; //tt.Esp = context[i].Esp; //tt.Esi = context[i].Esi; //SetThreadContext(Agohandle, ref tt); CloseHandle(Nowhandle); //建立新线程 if (i + 1 < count) { IntPtr lpThreadID = (IntPtr)0; StartThread threadfunc = null; ThreadStartDelegate threadFunc = null; unsafe { thrhandle = CreateRemoteThread(prohandle, (IntPtr)null, 0, threadFunc, (IntPtr)null, (uint)CreateProcessFlags.CREATE_SUSPENDED, lpThreadID); } threadid = (int)lpThreadID; } } // ResumeThread(thrhandle); //读入内存状态 SYSTEM_INFO systeminfo = new SYSTEM_INFO(); GetSystemInfo(out systeminfo); long MaxAddress = (long)systeminfo.lpMaximumApplicationAddress; long address = 0; int countcount = 0; do { MEMORY_BASIC_INFORMATION memory; int result = VirtualQueryEx(prohandle, (IntPtr)address, out memory, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION))); if (address == (long)memory.BaseAddress + (long)memory.RegionSize) break; if (memory.State == (uint)StateEnum.MEM_COMMIT) { switch (memory.AllocationProtect) { case (uint)AllocationProtect.PAGE_READWRITE: byte[] buffer = new byte[(int)memory.RegionSize]; Console.WriteLine("now"); Console.WriteLine(memory.BaseAddress); Console.WriteLine(memory.AllocationBase); Console.WriteLine(memory.RegionSize); Console.WriteLine(memory.Type); Console.WriteLine(memory.Protect); stream.Read(buffer, 0, buffer.Length); UIntPtr byteread; WriteProcessMemory(prohandle, memory.BaseAddress, buffer, (uint)memory.RegionSize, out byteread); Console.WriteLine("ago"); Console.WriteLine(memory.BaseAddress); Console.WriteLine(memory.AllocationBase); Console.WriteLine(memory.RegionSize); Console.WriteLine(memory.Type); Console.WriteLine(memory.Protect); countcount++; break; default: break; } } address = (long)memory.BaseAddress + (long)memory.RegionSize; } while (address <= MaxAddress); stream.Close(); CloseHandle(prohandle); Console.WriteLine("write over!"); Console.WriteLine(countcount); } //恢复线程运行 System.Diagnostics.Process proc = System.Diagnostics.Process.GetProcessById(proinfo.dwProcessId); System.Diagnostics.ProcessThread[] processthread = new System.Diagnostics.ProcessThread[500]; System.Diagnostics.ProcessThreadCollection threadcollection = new System.Diagnostics.ProcessThreadCollection(processthread); threadcollection = proc.Threads; for (int k = 0; k < threadcollection.Count; k++) { IntPtr ptrr = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)threadcollection[k].Id); ResumeThread(ptrr); CloseHandle(ptrr); } return 0; }
private static extern bool GetThreadContext(IntPtr hThread, ref CONTEXT lpContext);
public RepositoryBase(CONTEXT context) { _context = context; }
public override bool HandleException(ref CONTEXT ctx, ProcessDebugger pd) { bool skip = false; var pPacket = ctx.Edi; var len = ctx.Edx; var packet = pd.ReadBytes(pPacket, (int)len); //MessageBox.Show(packet.ToString()); switch ((GameServerPacket)packet[0]) { case GameServerPacket.RemoveGroundUnit: { if (!Game.Settings.ReceivePacketHack.ItemTracker.EnablePickit.IsEnabled()) { break; } Game.ItemGoneHandler(packet); break; } case GameServerPacket.GameObjectModeChange: { if (!Game.Settings.ReceivePacketHack.NoTownPortalAnim.IsEnabled()) { break; } // no portal anim #1 var pUnit = Game.FindUnit(BitConverter.ToUInt32(packet, 2), (UnitType)packet[1]); if (pUnit != 0) { var unit = pd.Read <UnitAny>(pUnit); if (unit.dwTxtFileNo == 0x3B) { skip = true; } } break; } case GameServerPacket.PlayerReassign: { if (!Game.Settings.ReceivePacketHack.BlockFlash.IsEnabled() && !Game.Settings.ReceivePacketHack.FastTele.IsEnabled() && !Game.Settings.ReceivePacketHack.ItemTracker.EnablePickit.IsEnabled()) { break; } var unitType = (UnitType)packet[1]; if (unitType != UnitType.Player) { break; } var pPlayer = Game.GetPlayerUnit(); if (pPlayer == 0) { break; } var unit = pd.Read <UnitAny>(pPlayer); if (BitConverter.ToUInt32(packet, 2) == unit.dwUnitId) { if (Game.Settings.ReceivePacketHack.ItemTracker.EnablePickit.IsEnabled()) { Game.CurrentX = BitConverter.ToUInt16(packet, 6); Game.CurrentY = BitConverter.ToUInt16(packet, 8); Task.Factory.StartNew(() => Game.OnRelocaton()); } // no flash if (Game.Settings.ReceivePacketHack.BlockFlash.IsEnabled()) { pd.WriteByte(pPacket + 10, 0); } // fast teleport if (Game.Settings.ReceivePacketHack.FastTele.IsEnabled() && !allowableModes.Contains((PlayerMode)unit.dwMode)) { unit.dwFrameRemain = 0; pd.Write <UnitAny>(pPlayer, unit); } } break; } case GameServerPacket.Unknown18: case GameServerPacket.PlayerLifeManaChange: { if (!Game.Settings.Chicken.Enabled || Game.chickening) { break; } var life = BitConverter.ToUInt16(packet, 1); var mana = BitConverter.ToUInt16(packet, 3); Task.Factory.StartNew(() => Game.TryChicken(life, mana, false)); break; } case GameServerPacket.GameObjectAssignment: { if ((UnitType)packet[1] == UnitType.Object && BitConverter.ToUInt16(packet, 6) == 0x3B) { // no portal anim #2 if (Game.Settings.ReceivePacketHack.NoTownPortalAnim.IsEnabled()) { pd.WriteByte(pPacket + 12, 2); } UnitAny unit; if (Game.backToTown && Game.GetPlayerUnit(out unit)) { if (!Game.IsInTown()) { var path = pd.Read <Path>(unit.pPath); if (Misc.Distance(path.xPos, path.yPos, BitConverter.ToUInt16(packet, 8), BitConverter.ToUInt16(packet, 10)) < 10) { Task.Factory.StartNew(() => Game.Interact(BitConverter.ToUInt32(packet, 2), UnitType.Object)); } } Game.backToTown = false; } } break; } case GameServerPacket.PlayerInfomation: // event message { var type = packet[1]; var infoType = packet[2]; var relationType = packet[7]; if (type == 0x7 && infoType == 8 && relationType == 3) { if (!Game.Settings.Chicken.ChickenOnHostility.IsEnabled() || Game.chickening) { break; } Task.Factory.StartNew(() => Game.TryChicken(0, 0, true)); } break; } case GameServerPacket.WorldItemAction: case GameServerPacket.OwnedItemAction: { skip = !Game.ItemActionHandler(packet); break; } case GameServerPacket.DelayedState: { // skip delay between entering portals if (Game.Settings.ReceivePacketHack.NoTownPortalAnim.IsEnabled() && packet[6] == 102) { skip = true; } break; } case GameServerPacket.TriggerSound: { if (Game.Settings.ReceivePacketHack.ItemTracker.EnablePickit.IsEnabled()) { if (packet[1] == 0 && packet[6] == 0x17) { Game.Pickit.Disable(PickitDisableReason.InventoryFull); } } break; } case GameServerPacket.AttributeByte: case GameServerPacket.AttributeWord: case GameServerPacket.AttributeDWord: { var attr = (StatType)packet[1]; uint val = 0; switch ((GameServerPacket)packet[0]) { case GameServerPacket.AttributeByte: val = (uint)packet[2]; break; case GameServerPacket.AttributeWord: val = BitConverter.ToUInt16(packet, 2); break; case GameServerPacket.AttributeDWord: val = (uint)((packet[5] << 16) | (packet[4] << 8) | packet[3]); break; } Game.PlayerInfo.SetStat(attr, val); break; } case GameServerPacket.StateNotification: { /*var uid = BitConverter.ToUInt32(packet, 1); * var attr = (StatType)packet[5]; * var value = BitConverter.ToUInt32(packet, 6); * * UnitAny player; * if (!Game.GetPlayerUnit(out player)) * break; * * if (player.dwUnitId != uid) * break; * * Game.PlayerInfo.SetStat(attr, value);*/ break; } } if (!skip) { ctx.Ecx = ctx.Edi; ctx.Eip += 2; } else { ctx.Esp += 4; ctx.Eip += 7; ctx.Eax = 0; } return(true); }
private void ProcessThreadContext(int threadId, ContextFlags flag, ThreadContextHandler handler, bool isReadOnly = false) { if (handler == null) throw new ArgumentNullException("handler"); var context = new CONTEXT { ContextFlags = flag }; if (SuspendThread(hThread) == 0xFFFFFFFF) throw new Win32Exception(); if (!GetThreadContext(hThread, ref context)) throw new Win32Exception(); handler(ref context); if (!isReadOnly) { if (!SetThreadContext(hThread, ref context)) throw new Win32Exception(); } if (ResumeThread(hThread) == 0xFFFFFFFF) throw new Win32Exception(); }
public Repository(CONTEXT context) : base(context) { }
public static void SRexec(byte[] b, string sVictim) { String sVersion = null; IMAGE_DOS_HEADER pidh = default(IMAGE_DOS_HEADER); CONTEXT context = new CONTEXT(); IMAGE_NT_HEADERS Pinh = default(IMAGE_NT_HEADERS); IMAGE_SECTION_HEADER Pish = default(IMAGE_SECTION_HEADER); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); STARTUPINFO si = new STARTUPINFO(); SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES(); SECURITY_ATTRIBUTES tSec = new SECURITY_ATTRIBUTES(); //converts a data type in another type. //since .net types are different from types handle by winAPI, DirectCall a API will cause a type mismatch, since .net types // structure is completely different, using different resources. GCHandle MyGC = GCHandle.Alloc(b, GCHandleType.Pinned); long ptbuffer = MyGC.AddrOfPinnedObject().ToInt64(); pidh = (IMAGE_DOS_HEADER)Marshal.PtrToStructure(MyGC.AddrOfPinnedObject(), pidh.GetType()); MyGC.Free(); if (!CreateProcess(null, sVictim, ref pSec, ref tSec, false, 0x4, new System.IntPtr(), null, ref si, ref pi)) { return; } long vt = ptbuffer + pidh.e_lfanew; Pinh = (IMAGE_NT_HEADERS)Marshal.PtrToStructure(new IntPtr(vt), Pinh.GetType()); IntPtr addr = new IntPtr(); long lOffset = 0; long ret = 0; //si.cb = Strings.Len(si); context.ContextFlags = CONTEXT86_INTEGER; //all "IF" are only for better understanding, you could do all verification on the builder and then the rest on the stub if (Pinh.Signature != (uint)ImageSignatureTypes.IMAGE_NT_SIGNATURE || pidh.e_magic != (uint)ImageSignatureTypes.IMAGE_DOS_SIGNATURE) return; int lpNumberOfBytesRead = 0; if (GetThreadContext(pi.hThread, ref context) & ReadProcessMemory(pi.hProcess, (int)context.Ebx + 8, ref addr, 4, ref lpNumberOfBytesRead) >= 0 & ZwUnmapViewOfSection(pi.hProcess, addr) >= 0) { Int64 ImageBase = VirtualAllocEx(pi.hProcess, new IntPtr(Pinh.OptionalHeader.ImageBase), Pinh.OptionalHeader.SizeOfImage, (uint)(MEM_RESERVE | MEM_COMMIT), (uint)PAGE_READWRITE).ToInt64(); if (ImageBase != 0) { WriteProcessMemory(pi.hProcess, new IntPtr(ImageBase), b, (long)Pinh.OptionalHeader.SizeOfHeaders, ref ret); lOffset = pidh.e_lfanew + 248; for (int i = 0; i <= Pinh.FileHeader.NumberOfSections - 1; i++) { //math changes, anyone with pe understanding know Pish = (IMAGE_SECTION_HEADER)Marshal.PtrToStructure(new IntPtr(ptbuffer + lOffset + i * 40), Pish.GetType()); byte[] braw = new byte[Pish.SizeOfRawData + 1]; //more math for reading only the section. mm API has a "shortcut" when you pass a specified startpoint. //.net can't use so you have to make a new array for (int j = 0; j <= Pish.SizeOfRawData - 1; j++) { braw[j] = b[Pish.PointerToRawData + j]; } WriteProcessMemory(pi.hProcess, new IntPtr(ImageBase + Pish.VirtualAddress), braw, (int)Pish.SizeOfRawData, ref ret); VirtualProtectEx(pi.hProcess, new IntPtr(ImageBase + Pish.VirtualAddress), new UIntPtr(Pish.Misc.VirtualSize), new UIntPtr((uint)Protect(Pish.Characteristics)), (uint)addr.ToInt64()); } byte[] bb = BitConverter.GetBytes(ImageBase); WriteProcessMemory(pi.hProcess, new IntPtr(context.Ebx + 8), bb, 4, ref ret); context.Eax = (uint)ImageBase + Pinh.OptionalHeader.AddressOfEntryPoint; SetThreadContext(pi.hThread, ref context); ResumeThread(pi.hThread); } } }
public unsafe static bool Execute(LoadParams args) { bool isWow = false; PROCESS_INFORMATION lpProcesSystemNetCertPolicyValidationCallbackv = default(PROCESS_INFORMATION); CONTEXT cONTEXT = default(CONTEXT); cONTEXT.ContextFlags = 1048603u; CONTEXT cONTEXT2 = cONTEXT; IntPtr lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU; IMAGE_DOS_HEADER *ptr2; IMAGE_NT_HEADERS *ptr3; fixed(byte *ptr = args.Body) { lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU = (IntPtr)(void *)ptr; ptr2 = (IMAGE_DOS_HEADER *)ptr; ptr3 = (IMAGE_NT_HEADERS *)(ptr + ptr2->e_lfanew); } if (ptr2->e_magic != 23117 || ptr3->Signature != 17744) { return(false); } if (ptr3->OptionalHeader.Magic != 267) { return(false); } Buffer.SetByte(args.Body, 920, 2); STARTUPINFO lpStartupInfo = default(STARTUPINFO); lpStartupInfo.cb = Marshal.SizeOf((object)lpStartupInfo); lpStartupInfo.wShowWindow = 0; using (LibInvoker libInvoker = new LibInvoker("kernel32.dll")) { using (LibInvoker libInvoker2 = new LibInvoker("ntdll.dll")) { if (!libInvoker.CastToDelegate <NativeDelegates.CreateProcessInternalWDelegate>("CreateProcessInternalW")(0u, null, args.AppPath, IntPtr.Zero, IntPtr.Zero, bInheritHandles : false, 134217740u, IntPtr.Zero, Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), ref lpStartupInfo, out lpProcesSystemNetCertPolicyValidationCallbackv, 0u)) { if (lpProcesSystemNetCertPolicyValidationCallbackv.hProcess != IntPtr.Zero && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); } return(false); } libInvoker.CastToDelegate <NativeDelegates.IsWow64ProcessDelegate>("IsWow64Process")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, ref isWow); IntPtr intPtr = (IntPtr)(long)ptr3->OptionalHeader.ImageBase; libInvoker2.CastToDelegate <NativeDelegates.NtUnmapViewOfSectionDelegate>("NtUnmapViewOfSection")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, intPtr); if (libInvoker.CastToDelegate <NativeDelegates.VirtualAllocExDelegate>("VirtualAllocEx")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, intPtr, ptr3->OptionalHeader.SizeOfImage, 12288u, 64u) == IntPtr.Zero && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } if (!libInvoker.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, intPtr, lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU, ptr3->OptionalHeader.SizeOfHeaders, IntPtr.Zero) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } for (ushort num = 0; num < ptr3->FileHeader.NumberOfSections; num = (ushort)(num + 1)) { IMAGE_SECTION_HEADER *ptr4 = (IMAGE_SECTION_HEADER *)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + ptr2->e_lfanew + Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)) + Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * num); if (!libInvoker.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)(intPtr.ToInt64() + ptr4->VirtualAddress), (IntPtr)(lSqlDependencyProcessDispatcherSqlConnectionContainerHashHelperU.ToInt64() + ptr4->PointerToRawData), ptr4->SizeOfRawData, IntPtr.Zero) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } if (isWow) { if (!libInvoker.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("Wow64GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } else if (!libInvoker.CastToDelegate <NativeDelegates.Wow64GetThreadContextDelegate>("GetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } IntPtr intPtr2 = Marshal.AllocHGlobal(8); ulong num2 = (ulong)intPtr.ToInt64(); byte[] array = new byte[8]; for (int i = 0; i < 8; i++) { array[i] = (byte)(num2 >> i * 8); if (i == 7) { Marshal.Copy(array, 0, intPtr2, 8); } } if (!libInvoker.CastToDelegate <NativeDelegates.WriteProcessMemoryDelegate>("WriteProcessMemory")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, (IntPtr)((long)cONTEXT2.Ebx + 8L), intPtr2, 4u, IntPtr.Zero)) { Marshal.FreeHGlobal(intPtr2); if (libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } Marshal.FreeHGlobal(intPtr2); cONTEXT2.Eax = (uint)(intPtr.ToInt64() + ptr3->OptionalHeader.AddressOfEntryPoint); if (isWow) { if (!libInvoker.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("Wow64SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } } else if (!libInvoker.CastToDelegate <NativeDelegates.Wow64SetThreadContextDelegate>("SetThreadContext")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread, &cONTEXT2) && libInvoker.CastToDelegate <NativeDelegates.TerminateProcessDelegate>("TerminateProcess")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess, -1)) { libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); return(false); } libInvoker.CastToDelegate <NativeDelegates.ResumeThreadDelegate>("ResumeThread")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hProcess); libInvoker.CastToDelegate <NativeDelegates.CloseHandleDelegate>("CloseHandle")(lpProcesSystemNetCertPolicyValidationCallbackv.hThread); } } return(true); }
public static bool SetContext(IntPtr thread, CONTEXT context) => Kernel32.SetThreadContext(thread, ref context);
static void Send2(Process process, CONTEXT context) { var ptr = process.Read<IntPtr>(new IntPtr(context.Esp + Offsets.Send_ds)); var dataStore = process.Read<CDataStore>(ptr); var packet = process.ReadBytes(dataStore.buffer, dataStore.size); var connection = process.Read<int>(new IntPtr(context.Esp + Offsets.Send_ds + 4)); lock (lockObject) { DumpPacket(Direction.CMSG, connection, packet); } }
public static extern void RtlRestoreContext(ref CONTEXT ContextRecord, ref EXCEPTION_RECORD ExceptionRecord);
public int DumpProcState(int pid, string filename) { AllocConsole(); //查找进程相关的所有线程 System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById(pid); System.Diagnostics.ProcessThread[] processthread = new System.Diagnostics.ProcessThread[500]; System.Diagnostics.ProcessThreadCollection threadcollection = new System.Diagnostics.ProcessThreadCollection(processthread); threadcollection = process.Threads; int count = threadcollection.Count; CONTEXT[] context = new CONTEXT[count]; //间文件流 System.IO.FileStream stream = null; stream = new System.IO.FileStream(filename, System.IO.FileMode.Create); string procdescription = process.MainModule.FileName; char[] description = procdescription.ToCharArray(); byte[] bytedescription = new byte[procdescription.Length]; for (int j = 0; j < procdescription.Length; j++) { bytedescription[j] = Convert.ToByte(description[j]); } byte[] descriptioncount = new byte[1]; descriptioncount[0] = Convert.ToByte(procdescription.Length); //写入exe文件路径的长度 stream.Write(descriptioncount, 0, descriptioncount.Length); //写入exe文件路径 stream.Write(bytedescription, 0, bytedescription.Length); byte[] bytecount = new byte[1]; bytecount[0] = Convert.ToByte(count); //写入线程数 stream.Write(bytecount, 0, bytecount.Length); //挂起所有线程 for (int ii = 0; ii < count; ii++) { IntPtr ptr = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)threadcollection[ii].Id); SuspendThread(ptr); CloseHandle(ptr); } for (int i = 0; i < count; i++) { context[i].ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; IntPtr hThread = OpenThread(ThreadAccess.GET_CONTEXT, false, (uint)(threadcollection[i].Id)); Console.WriteLine(hThread); string stringhandle = Convert.ToString(hThread); char[] charhandle = stringhandle.ToCharArray(); byte[] byteahandle = new byte[stringhandle.Length+1]; byteahandle[0] = Convert.ToByte(stringhandle.Length); for (int bi = 0; bi < stringhandle.Length; bi++) { byteahandle[bi + 1] = Convert.ToByte(charhandle[bi]); } //写入线程句柄 stream.Write(byteahandle, 0, byteahandle.Length); if (GetThreadContext(hThread, ref context[i])) { Console.WriteLine("Ebp : {0}", context[i].Ebp); Console.WriteLine("Eip : {0}", context[i].Eip); Console.WriteLine("SegCs : {0}", context[i].SegCs); Console.WriteLine("EFlags : {0}", context[i].EFlags); Console.WriteLine("Esp : {0}", context[i].Esp); Console.WriteLine("SegSs : {0}", context[i].SegSs); byte[] bydata = Serialize(context[i]); //写入上写文 stream.Write(bydata, 0, bydata.Length); } else { Console.WriteLine("A problem occurred!"); } CloseHandle(hThread); } stream.Close(); Console.WriteLine("read over!"); //dump内存 DumpProcMemory(pid, filename); //恢复线程 for (int iii = 0; iii < count; iii++) { IntPtr ptrr = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)threadcollection[iii].Id); ResumeThread(ptrr); CloseHandle(ptrr); } return 0; }
public static extern int SetThreadContext(IntPtr hThread, [MarshalAs(UnmanagedType.Struct)] ref CONTEXT lpContext);
private static extern bool GetThreadContext(nint hThread, ref CONTEXT context);
/// <summary> /// Sets the context of a given thread. /// </summary> /// <param name="hThread">Handle to the thread for which the context will be set.</param> /// <param name="ctx">CONTEXT structure to which the thread's context will be set.</param> /// <returns>Returns true on success, false on failure.</returns> public static bool SetThreadContext(IntPtr hThread, CONTEXT ctx) { return(Imports.SetThreadContext(hThread, ref ctx)); }
private static extern bool Wow64SetThreadContext(IntPtr hThread, [In] ref CONTEXT lpContext);
protected void EditFileWindow() { try { EditorGUILayout.LabelField("Editing locale: " + this.selectedFile, EditorStyles.boldLabel); EditorGUILayout.Space(); this.scrollPosition = EditorGUILayout.BeginScrollView(this.scrollPosition, GUILayout.MaxWidth(450), GUILayout.MaxHeight(450), GUILayout.ExpandHeight(false)); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("Key Filter", EditorStyles.boldLabel); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); this.keyFilter = EditorGUILayout.TextField(this.keyFilter); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("Value Filter", EditorStyles.boldLabel); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); this.valueFilter = EditorGUILayout.TextField(this.valueFilter); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("Key", EditorStyles.boldLabel); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("Value", EditorStyles.boldLabel); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); if (this.localeDict == null) { this.localeDict = this.inEditorLoadLanguageTable(Application.dataPath + Settings.SAVING_LANGUAGE_PATH + this.selectedFile + Settings.LANGUAGE_EXTENSION); } bool isFiltered = false; foreach (KeyValuePair <string, string> pair in this.localeDict) { string tmpKey = "", tmpValue = ""; if (this.keyFilter != "" || this.valueFilter != "") { isFiltered = true; if (this.keyFilter != "" && this.valueFilter != "") { if (pair.Key.ToLower().Contains(this.keyFilter.ToLower()) && pair.Value.ToLower().Contains(this.valueFilter.ToLower())) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); tmpKey = EditorGUILayout.TextField(pair.Key); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); tmpValue = EditorGUILayout.TextField(pair.Value); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } } else if (this.keyFilter != "") { if (pair.Key.ToLower().Contains(this.keyFilter.ToLower())) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); tmpKey = EditorGUILayout.TextField(pair.Key); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); tmpValue = EditorGUILayout.TextField(pair.Value); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } } else if (this.valueFilter != "") { if (pair.Value.ToLower().Contains(this.valueFilter.ToLower())) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); tmpKey = EditorGUILayout.TextField(pair.Key); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); tmpValue = EditorGUILayout.TextField(pair.Value); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } } } else { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); tmpKey = EditorGUILayout.TextField(pair.Key); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); tmpValue = EditorGUILayout.TextField(pair.Value); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } if (this.finalContentDict.ContainsKey(pair.Key)) { this.finalContentDict.Remove(pair.Key); } if (tmpKey != "") { this.finalContentDict[tmpKey] = tmpValue; } } if (!isFiltered) { this.localeDict = new Dictionary <string, string>(this.finalContentDict); } EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); if (GUILayout.Button("Add entry")) { guiEvents.Enqueue(() => { try { this.localeDict.Add("Entry-" + DateTime.Now.Ticks, ""); } catch (Exception e) { if (LocalizatronEditor.IS_DEBUG) { LocalizatronEditor.Log(e.Message); } } }); } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); if (GUILayout.Button("< Back")) { this.selectedFile = ""; this.localeDict = null; this.finalContentDict.Clear(); this._context = CONTEXT.FILES_MANAGER; } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); if (GUILayout.Button("Save locale")) { string finalContent = ""; foreach (KeyValuePair <string, string> kv in this.finalContentDict) { finalContent += "<key>" + kv.Key + "</key><value>" + kv.Value + "</value>\n"; } LocalizatronEditor.SaveLocalizationFile(this.selectedFile, finalContent); } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndScrollView(); } catch (Exception e) { if (LocalizatronEditor.IS_DEBUG) { LocalizatronEditor.Log(e.Message); } EditorGUILayout.EndScrollView(); } }
public static extern void RtlCaptureContext(ref CONTEXT ContextRecord);
// .text:00534BCE 8A 45 FF mov al, [ebp+var_1 public override bool HandleException(ref CONTEXT ctx, ProcessDebugger pd) { ctx.Eip += 3; ctx.Al = 1; return true; }
public static extern bool SetThreadContext(IntPtr hThread, [In, Out] CONTEXT lpContext);
public override bool HandleException(ref CONTEXT ctx, ProcessDebugger pd) { ctx.Al = pd.ReadByte(ctx.Ebp + 0x12A); ctx.Eip += 6; var pString = ctx.Edi; var pItem = ctx.Ebx; var str = pd.ReadUTF16String(pString); //"ÿc"; //str = "ÿc1" + str; var item = pd.Read <UnitAny>(pItem); var itemData = pd.Read <ItemData>(item.pItemData); var changed = false; var appendix = ""; if (Game.Settings.ItemNameHack.ShowItemCode.IsEnabled()) { var pTxt = Game.GetItemText(item.dwTxtFileNo); var txt = pd.Read <ItemTxt>(pTxt); appendix += "(" + txt.GetCode() + ")"; } if (Game.Settings.ItemNameHack.ShowEth.IsEnabled() && (itemData.dwFlags & 0x400000) != 0) { appendix += "{E}"; } var runeNumber = item.RuneNumber(); if (runeNumber > 0 && Game.Settings.ItemNameHack.ShowRuneNumber.IsEnabled()) { appendix += "(" + runeNumber + ")"; } if (Game.Settings.ItemNameHack.ShowSockets.IsEnabled()) { var cnt = Game.GetItemSockets(pItem, item.dwUnitId); if (cnt > 0 && cnt != uint.MaxValue) { appendix += "(" + cnt + ")"; } } if (Game.Settings.ItemNameHack.ShowItemLevel.IsEnabled() && itemData.dwItemLevel > 1) { appendix += "(L" + itemData.dwItemLevel + ")"; } if (Game.Settings.ItemNameHack.ShowItemPrice.IsEnabled()) { var price = Game.GetItemPrice(pItem, item.dwUnitId); if (price > 0 && price != uint.MaxValue) { appendix += "($" + price + ")"; } } if (Game.Settings.ItemNameHack.ChangeItemColor.IsEnabled()) { var itemInfo = ItemStorage.GetInfo(item.dwTxtFileNo); if (itemInfo != null) { var sock = Game.GetItemSockets(pItem, item.dwUnitId); var configEntries = Game.ItemProcessingSettings.GetMatches(itemInfo, sock, (itemData.dwFlags & 0x400000) != 0, (ItemQuality)itemData.dwQuality).Where(it => it.Color != D2Color.Default); if (configEntries.Count() != 0) { var entry = configEntries.First(); str = "ÿc" + entry.Color.GetCode() + str; changed = true; } } } if (appendix != "") { str += " " + appendix; changed = true; } if (changed) { pd.WriteUTF16String(pString, str); } return(true); }
public Context(CONTEXT context64, IntPtr hThread) { _hThread = hThread; isContext64 = true; this.context64 = context64; }
public ContextWrapper(ProcessDebugger Debugger, CONTEXT Context) { this.Debugger = Debugger; this.Context = Context; }
private static UInt32 SampleStatefulPolicyFunc2(int parameters, CONTEXT context) { return((uint)((parameters + context.Features.Length) % 10 + 2)); }
public static void Clock() { float epsilon = .2f; int policyParams = 1003; string uniqueKey = "clock"; int numFeatures = 1000; int numIter = 1000; int numWarmup = 100; int numInteractions = 1; uint numActions = 10; string otherContext = null; double timeInit = 0, timeChoose = 0, timeSerializedLog = 0, timeTypedLog = 0; System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); for (int iter = 0; iter < numIter + numWarmup; iter++) { watch.Restart(); MwtExplorer mwt = new MwtExplorer("test"); mwt.InitializeEpsilonGreedy <int>(epsilon, new StatefulPolicyDelegate <int>(SampleStatefulPolicyFunc), policyParams, numActions); timeInit += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds; FEATURE[] f = new FEATURE[numFeatures]; for (int i = 0; i < numFeatures; i++) { f[i].Index = (uint)i + 1; f[i].X = 0.5f; } watch.Restart(); CONTEXT context = new CONTEXT(f, otherContext); for (int i = 0; i < numInteractions; i++) { mwt.ChooseAction(context, uniqueKey); } timeChoose += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds; watch.Restart(); string interactions = mwt.GetAllInteractionsAsString(); timeSerializedLog += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds; for (int i = 0; i < numInteractions; i++) { mwt.ChooseAction(context, uniqueKey); } watch.Restart(); mwt.GetAllInteractions(); timeTypedLog += (iter < numWarmup) ? 0 : watch.Elapsed.TotalMilliseconds; } Console.WriteLine("--- PER ITERATION ---"); Console.WriteLine("# iterations: {0}, # interactions: {1}, # context features {2}", numIter, numInteractions, numFeatures); Console.WriteLine("Init: {0} micro", timeInit * 1000 / numIter); Console.WriteLine("Choose Action: {0} micro", timeChoose * 1000 / (numIter * numInteractions)); Console.WriteLine("Get Serialized Log: {0} micro", timeSerializedLog * 1000 / numIter); Console.WriteLine("Get Typed Log: {0} micro", timeTypedLog * 1000 / numIter); Console.WriteLine("--- TOTAL TIME: {0} micro", (timeInit + timeChoose + timeSerializedLog + timeTypedLog) * 1000); }
/// <summary> /// Returns the string representing the context of a given thread /// </summary> /// <param name="ThreadID"></param> /// <returns></returns> private string GetRegisterContext(uint ThreadID) { string returnValue = ""; CONTEXT context = new CONTEXT(); context.ContextFlags = CONTEXT_FLAGS.CONTEXT_CONTROL | CONTEXT_FLAGS.CONTEXT_INTEGER; IntPtr ThreadHandle = WinAPI.OpenThread(WinAPI.ThreadAccessRights.THREAD_GET_CONTEXT, false, ThreadID); if (ThreadHandle == IntPtr.Zero) throw new Exception("Error 0x" + WinAPI.GetLastError().ToString("X") + " - " + Enum.GetName(typeof(WinAPI.SYSTEM_ERROR_CODE), WinAPI.GetLastError()) + " - when getting thread handle for context"); if (!WinAPI.GetThreadContext(ThreadHandle, ref context)) throw new Exception("Error 0x" + WinAPI.GetLastError().ToString("X") + " - " + Enum.GetName(typeof(WinAPI.SYSTEM_ERROR_CODE), WinAPI.GetLastError()) + " - when getting thread context"); // NEEDS ATTENTION - not tested, should confirm register values against WinDbg int paddingSize = ((this.is32bit) ? 8 : 16); // This check will be needed when handling 64 bit processes, currently not tested. paddingSize = 8; // Temporary while 32 bit is worked on. returnValue += "EAX=0x" + context.Eax.ToString("X").PadLeft(paddingSize, '0') + "\t\t"; returnValue += "EBX=0x" + context.Ebx.ToString("X").PadLeft(paddingSize, '0') + "\r\n"; returnValue += "ECX=0x" + context.Ecx.ToString("X").PadLeft(paddingSize, '0') + "\t\t"; returnValue += "EDX=0x" + context.Edx.ToString("X").PadLeft(paddingSize, '0') + "\r\n"; returnValue += "EDI=0x" + context.Edi.ToString("X").PadLeft(paddingSize, '0') + "\t\t"; returnValue += "ESI=0x" + context.Esi.ToString("X").PadLeft(paddingSize, '0') + "\r\n"; returnValue += "EBP=0x" + context.Ebp.ToString("X").PadLeft(paddingSize, '0') + "\t\t"; returnValue += "ESP=0x" + context.Esp.ToString("X").PadLeft(paddingSize, '0') + "\r\n\t"; returnValue += "EIP=0x" + context.Eip.ToString("X").PadLeft(paddingSize, '0'); WinAPI.CloseHandle(ThreadHandle); return returnValue; }
private static UInt32 SampleStatefulPolicyFunc(CustomParams parameters, CONTEXT context) { return((uint)((parameters.Value1 + parameters.Value2 + context.Features.Length) % 10 + 1)); }
private static bool InitHostProcess(string pszFormattedPath, ref HostProcessInfo HPI) { bool bResult; STARTUPINFO lpStartupInfo = new STARTUPINFO(); PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION(); // create child process bResult = CreateProcessW( null, pszFormattedPath, IntPtr.Zero, IntPtr.Zero, false, 0x04, IntPtr.Zero, IntPtr.Zero, ref lpStartupInfo, out lpProcessInformation); if (!bResult) { return(false); } HPI.SI = lpStartupInfo; HPI.PI = lpProcessInformation; // get peb->ImageBaseAddress of host process CONTEXT CTX = new CONTEXT(); CTX.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; // YOU Dont actually need getthreadcontext ->??? you just need peb->Imagebaseaddress bResult = GetThreadContext(HPI.PI.hThread, ref CTX); if (!bResult) { return(false); } HPI.CTX = CTX; // patch the peb fields in _RTL_USER_PROCESS_PARAMETERS +0x010 // +0x038 ImagePathName : _UNICODE_STRING // +0x040 CommandLine : _UNICODE_STRING? do u need to patch this or is created with CreateProcessW? IntPtr pPEB = (IntPtr)CTX.Ebx; //string _unformattedQuotedPath = pszFormattedPath.Trim('"'); //{ // /* init unicode string in foreign process */ // uint __out = 0; // int len = _unformattedQuotedPath.Length * 2; // int maxlen = len + 2; // IntPtr lpForeignImagePathName = VirtualAllocEx(HPI.PI.hProcess, IntPtr.Zero, (uint)maxlen, 0x3000, 0x40); // byte[] pBb = new UnicodeEncoding().GetBytes(_unformattedQuotedPath); // WriteProcessMemory(HPI.PI.hProcess, lpForeignImagePathName, pBb, (uint)pBb.Length, ref __out); // /* update the field */ // IntPtr _rtl_user_proc_params = ReadProcessMemory(HPI(IntPtr)((uint)pPEB + 0x010); // IntPtr _image_Path_name = (IntPtr)((uint)_rtl_user_proc_params + 0x038); //} // read peb byte[] _readBuffer = new byte[sizeof(uint)]; IntPtr _outBuffer = IntPtr.Zero; // ctx.ebx = peb* // ctx.ebx + 8 = ImageBaseAddress bResult = ReadProcessMemory( HPI.PI.hProcess, (IntPtr)(HPI.CTX.Ebx + 8), _readBuffer, sizeof(uint), out _outBuffer); if (!bResult) { return(false); } HPI.ImageBase = BitConverter.ToUInt32(_readBuffer, 0); // find how much mapped memory we have to work with IntPtr lpCurrentAddress = (IntPtr)HPI.ImageBase; MEMORY_BASIC_INFORMATION mbi = new MEMORY_BASIC_INFORMATION(); // iterate through mapped memory space while (VirtualQueryEx( HPI.PI.hProcess, lpCurrentAddress, out mbi, (uint)sizeof(MEMORY_BASIC_INFORMATION)) != 0) { if (mbi.State == StateEnum.MEM_FREE) { break; } lpCurrentAddress = (IntPtr)((uint)(lpCurrentAddress) + mbi.RegionSize); } // size of mapped memory ?? == Nt->SizeOfImage HPI.ImageSize = (uint)lpCurrentAddress - HPI.ImageBase; return(bResult); }
private static UInt32 SampleStatelessPolicyFunc2(CONTEXT applicationContext) { return((UInt32)applicationContext.Features.Length + 1); }
public static extern bool SetThreadContext(IntPtr hThread, ref CONTEXT lpContext);
public static void Run() { string interactionFile = "serialized.txt"; MwtLogger logger = new MwtLogger(interactionFile); MwtExplorer mwt = new MwtExplorer("test", logger); uint numActions = 10; float epsilon = 0.2f; uint tau = 0; uint bags = 2; float lambda = 0.5f; int policyParams = 1003; CustomParams customParams = new CustomParams() { Value1 = policyParams, Value2 = policyParams + 1 }; /*** Initialize Epsilon-Greedy explore algorithm using a default policy function that accepts parameters ***/ mwt.InitializeEpsilonGreedy <int>(epsilon, new StatefulPolicyDelegate <int>(SampleStatefulPolicyFunc), policyParams, numActions); /*** Initialize Epsilon-Greedy explore algorithm using a stateless default policy function ***/ //mwt.InitializeEpsilonGreedy(epsilon, new StatelessPolicyDelegate(SampleStatelessPolicyFunc), numActions); /*** Initialize Tau-First explore algorithm using a default policy function that accepts parameters ***/ //mwt.InitializeTauFirst<CustomParams>(tau, new StatefulPolicyDelegate<CustomParams>(SampleStatefulPolicyFunc), customParams, numActions); /*** Initialize Tau-First explore algorithm using a stateless default policy function ***/ //mwt.InitializeTauFirst(tau, new StatelessPolicyDelegate(SampleStatelessPolicyFunc), numActions); /*** Initialize Bagging explore algorithm using a default policy function that accepts parameters ***/ //StatefulPolicyDelegate<int>[] funcs = //{ // new StatefulPolicyDelegate<int>(SampleStatefulPolicyFunc), // new StatefulPolicyDelegate<int>(SampleStatefulPolicyFunc2) //}; //int[] parameters = { policyParams, policyParams }; //mwt.InitializeBagging<int>(bags, funcs, parameters, numActions); /*** Initialize Bagging explore algorithm using a stateless default policy function ***/ //StatelessPolicyDelegate[] funcs = //{ // new StatelessPolicyDelegate(SampleStatelessPolicyFunc), // new StatelessPolicyDelegate(SampleStatelessPolicyFunc2) //}; //mwt.InitializeBagging(bags, funcs, numActions); /*** Initialize Softmax explore algorithm using a default policy function that accepts parameters ***/ //mwt.InitializeSoftmax<int>(lambda, new StatefulScorerDelegate<int>(SampleStatefulScorerFunc), policyParams, numActions); /*** Initialize Softmax explore algorithm using a stateless default policy function ***/ //mwt.InitializeSoftmax(lambda, new StatelessScorerDelegate(SampleStatelessScorerFunc), numActions); FEATURE[] f = new FEATURE[2]; f[0].X = 0.5f; f[0].Index = 1; f[1].X = 0.9f; f[1].Index = 2; string otherContext = "Some other context data that might be helpful to log"; CONTEXT context = new CONTEXT(f, otherContext); UInt32 chosenAction = mwt.ChooseAction(context, "myId"); INTERACTION[] interactions = mwt.GetAllInteractions(); mwt.Unintialize(); MwtRewardReporter mrr = new MwtRewardReporter(interactions); string joinKey = "myId"; float reward = 0.5f; if (!mrr.ReportReward(joinKey, reward)) { throw new Exception(); } MwtOptimizer mot = new MwtOptimizer(interactions, numActions); float eval1 = mot.EvaluatePolicy(new StatefulPolicyDelegate <int>(SampleStatefulPolicyFunc), policyParams); mot.OptimizePolicyVWCSOAA("model_file"); float eval2 = mot.EvaluatePolicyVWCSOAA("model_file"); Console.WriteLine(chosenAction); Console.WriteLine(interactions); logger.Flush(); // Create a new logger to read back interaction data logger = new MwtLogger(interactionFile); INTERACTION[] inters = logger.GetAllInteractions(); // Load and save reward data to file string rewardFile = "rewards.txt"; RewardStore rewardStore = new RewardStore(rewardFile); rewardStore.Add(new float[2] { 1.0f, 0.4f }); rewardStore.Flush(); // Read back reward data rewardStore = new RewardStore(rewardFile); float[] rewards = rewardStore.GetAllRewards(); }
public bool hideDebugger() { CONTEXT context = new CONTEXT(); context.ContextFlags = (uint)CONTEXT_FLAGS.CONTEXT_ALL; if (!GetThreadContext(hThread_, ref context)) return false; // translate segment selector address to linear virtual address LDT_ENTRY ldtEntry; if (!GetThreadSelectorEntry(hThread_, context.SegFs, out ldtEntry)) return false; uint fsVirtAddress = (uint)((uint)(ldtEntry.Bytes.BaseHi) << 24 | (uint)(ldtEntry.Bytes.BaseMid) << 16 | (uint)(ldtEntry.BaseLow)); // TEB pointer is at [fs:0x18] uint tebPtr = fsVirtAddress + 0x18; int read; // read TEB virtual address byte[] tmpAddr = readProcessMemory((IntPtr)tebPtr, 4, out read); if (read != 4) return false; // PEB address is at offset 0x30 uint pebAddr = arrToAddr(tmpAddr) + 0x30;//(uint)(tmpAddr[3] << 24 | tmpAddr[2] << 16 | tmpAddr[1] << 8 | tmpAddr[0]) + 0x30; tmpAddr = readProcessMemory((IntPtr)pebAddr, 4, out read); if (read != 4) return false; uint patchAddr = arrToAddr(tmpAddr) + 2;//(uint)(tmpAddr[3] << 24 | tmpAddr[2] << 16 | tmpAddr[1] << 8 | tmpAddr[0]) + 2; byte[] patch = readProcessMemory((IntPtr)patchAddr, 4, out read); patch[0] = 0; writeProcessMemory((IntPtr)patchAddr, patch, out read); return read == 4 ? true : false; }
public static extern void RtlCaptureContext(ref CONTEXT context);
public CONTEXT HandleToHandle(IntPtr Agohandle, IntPtr Nowhandle, CONTEXT context) { uint offset = (uint)Nowhandle - (uint)Agohandle; context.Ebp = context.Ebp + offset; context.Eip = context.Eip + offset; context.SegCs = context.SegCs + offset; context.EFlags = context.EFlags + offset; context.Esp = context.Esp + offset; context.SegSs = context.SegSs + offset; return context; }
public static extern bool StackWalk64(uint machineType, IntPtr hProcess, IntPtr hThread, ref STACKFRAME64 stackFrame, ref CONTEXT contextRecord, IntPtr readMemoryRoutine, IntPtr functionTableAccessRoutine, IntPtr getModuleBaseRoutine, IntPtr translateAddress);
static extern bool GetThreadContext(IntPtr hThread, ref CONTEXT lpContext);
public static extern bool SetThreadContext(IntPtr hThread, ref CONTEXT pContext);