Exemplo n.º 1
0
 private void CallDllMatchListView(int pid, ProcessModule module)
 {
     ListViewItem item = new ListViewItem();
     item.Name = pid.ToString() + " " + module.BaseAddress.ToString();
     item.Text = Program.ProcessProvider.Dictionary[pid].Name +
         " (" + pid.ToString() + ")";
     item.Tag = pid;
     item.SubItems.Add(new ListViewItem.ListViewSubItem(item, "DLL"));
     item.SubItems.Add(new ListViewItem.ListViewSubItem(item, module.FileName));
     item.SubItems.Add(new ListViewItem.ListViewSubItem(item, Utils.FormatAddress(module.BaseAddress)));
     OnMatchListView(item);
 }
Exemplo n.º 2
0
        public void TestModuleCollectionBehavior()
        {
            ProcessModule[] mArray = Process.GetCurrentProcess().Modules.Cast<ProcessModule>().ToArray();

            // Constructor
            ProcessModuleCollection moduleCollection = new ProcessModuleCollection(mArray);

            // Count
            Assert.Equal(mArray.Count(), moduleCollection.Count);

            // get_item, Contains, IndexOf
            for (int i = 0; i < mArray.Count(); i++)
            {
                Assert.Equal(mArray[i], moduleCollection[i]);
                Assert.True(moduleCollection.Contains(mArray[i]));
                Assert.Equal(i, moduleCollection.IndexOf(mArray[i]));
            }

            // CopyTo
            ProcessModule[] moduleArray = new ProcessModule[moduleCollection.Count + 1];
            moduleCollection.CopyTo(moduleArray, 1);
            for (int i = 0; i < mArray.Count(); i++)
            {
                Assert.Equal(mArray[i], moduleArray[i + 1]);
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => moduleCollection.CopyTo(moduleArray, -1));

            // Explicit interface implementations
            Assert.False(((ICollection)moduleCollection).IsSynchronized);
            Assert.NotNull(((ICollection)moduleCollection).SyncRoot);

            moduleArray = new ProcessModule[moduleCollection.Count];
            ((ICollection)moduleCollection).CopyTo(moduleArray, 0);
            Assert.Equal(moduleCollection.Cast<ProcessModule>().ToArray(), moduleArray);

            // GetEnumerator
            IEnumerator enumerator = moduleCollection.GetEnumerator();
            Assert.Throws<InvalidOperationException>(() => enumerator.Current);

            for (int i = 0; i < moduleCollection.Count; i++)
            {
                enumerator.MoveNext();
                Assert.Equal(moduleCollection[i], enumerator.Current);
            }
        }
Exemplo n.º 3
0
        public IntPtr FindPattern(string module, byte[] pattern, int offset = 0)
        {
            ProcessModule moduleInfo = m_Process.GetModule(module);

            return(FindPattern(moduleInfo, pattern, offset));
        }
 public ProcessModuleCollection(ProcessModule[] processModules);
Exemplo n.º 5
0
 private void SetVariables()
 {
     _baseAddress   = IntPtr.Zero;
     _processModule = _mainProcess[0].MainModule;
     _baseAddress   = _processModule.BaseAddress;
 }
Exemplo n.º 6
0
 /// <summary>
 /// Registers hook with Windows API
 /// </summary>
 /// <param name="proc">Callback function</param>
 /// <returns>Hook ID</returns>
 private IntPtr SetHook(KeyboardHookHandler proc)
 {
     using (ProcessModule module = Process.GetCurrentProcess().MainModule)
         return(SetWindowsHookEx(13, proc, GetModuleHandle(module.ModuleName), 0));
 }
        /// <summary>
        /// Injects a library into this Injector's process. <paramref name="libPath"/> can be
        /// relative or absolute; either way, the injected module will be referred to by module name only.
        /// I.e. "c:\some\directory\library.dll", "library.dll" and "..\library.dll" will all be referred to
        /// as "library.dll"
        /// </summary>
        /// <param name="libPath">Relative or absolute path to the dll to be injected</param>
        public void InjectLibrary(string libPath)
        {
            // (in?)sanity check, pretty sure this is never possible as the constructor will error - left over from how it previously was developed
            if (_process == null)
            {
                throw new InvalidOperationException("This injector has no associated process and thus cannot inject a library");
            }
            if (_handle == IntPtr.Zero)
            {
                throw new InvalidOperationException("This injector does not have a valid handle to the associated process and thus cannot inject a library");
            }

            if (!File.Exists(libPath))
            {
                throw new FileNotFoundException(string.Format("Unable to find library {0} to inject into process {1}", libPath, _process.ProcessName), libPath);
            }

            // convenience variables
            string fullPath = Path.GetFullPath(libPath);
            string libName  = Path.GetFileName(fullPath);

            // declare resources that need to be freed in finally
            IntPtr pLibRemote            = IntPtr.Zero;                          // pointer to allocated memory of lib path string
            IntPtr hThread               = IntPtr.Zero;                          // handle to thread from CreateRemoteThread
            IntPtr pLibFullPathUnmanaged = Marshal.StringToHGlobalUni(fullPath); // unmanaged C-String pointer

            try
            {
                uint sizeUni = (uint)Encoding.Unicode.GetByteCount(fullPath);

                // Get Handle to Kernel32.dll and pointer to LoadLibraryW
                IntPtr hKernel32 = Imports.GetModuleHandle("Kernel32");
                if (hKernel32 == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                IntPtr hLoadLib = Imports.GetProcAddress(hKernel32, "LoadLibraryW");
                if (hLoadLib == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                // allocate memory to the local process for libFullPath
                pLibRemote = Imports.VirtualAllocEx(_handle, IntPtr.Zero, sizeUni, AllocationType.Commit, MemoryProtection.ReadWrite);
                if (pLibRemote == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                // write libFullPath to pLibPath
                int bytesWritten;
                if (!Imports.WriteProcessMemory(_handle, pLibRemote, pLibFullPathUnmanaged, sizeUni, out bytesWritten) || bytesWritten != (int)sizeUni)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                // load dll via call to LoadLibrary using CreateRemoteThread
                hThread = Imports.CreateRemoteThread(_handle, IntPtr.Zero, 0, hLoadLib, pLibRemote, 0, IntPtr.Zero);
                if (hThread == IntPtr.Zero)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                if (Imports.WaitForSingleObject(hThread, (uint)ThreadWaitValue.Infinite) != (uint)ThreadWaitValue.Object0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                // get address of loaded module - this doesn't work in x64, so just iterate module list to find injected module
                IntPtr hLibModule;// = IntPtr.Zero;
                if (!Imports.GetExitCodeThread(hThread, out hLibModule))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
                //if(hLibModule == IntPtr.Zero)
                //    throw new Exception("Code executed properly, but unable to get an appropriate module handle, possible Win32Exception", new Win32Exception(Marshal.GetLastWin32Error()));

                // iterate modules in target process to find our newly injected module
                ProcessModule modFound = null;
                foreach (ProcessModule mod in _process.Modules)
                {
                    if (mod.ModuleName == libName)
                    {
                        modFound = mod;
                        break;
                    }
                }
                if (modFound == null)
                {
                    throw new Exception("Injected module could not be found within the target process!");
                }

                injectedModules.Add(libName, new InjectedModule(modFound));
            }
            finally
            {
                Marshal.FreeHGlobal(pLibFullPathUnmanaged);                                    // free unmanaged string
                Imports.CloseHandle(hThread);                                                  // close thread from CreateRemoteThread
                Imports.VirtualFreeEx(_process.Handle, pLibRemote, 0, AllocationType.Release); // Free memory allocated
            }
        }
Exemplo n.º 8
0
 public MyModule(ProcessModule r)
 {
     Name = r.ModuleName;
     Path = Directory.GetParent(r.FileName).FullName;
 }
Exemplo n.º 9
0
 public int ImageAddress(int pOffset)
 {
     this.BaseAddress = 0;
         this.myProcessModule = this.MyProcess[0].MainModule;
         this.BaseAddress = (int)this.myProcessModule.BaseAddress;
         return (pOffset + this.BaseAddress);
 }
 public void AdjustAddresses(ProcessModule module)
 {
     this.GlobalNameArrayAddress   = AdjustAddress(module, this.GlobalNameArrayAddress);
     this.GlobalObjectArrayAddress = AdjustAddress(module, this.GlobalObjectArrayAddress);
 }
Exemplo n.º 11
0
 /// <summary>
 ///     Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count.
 /// </summary>
 /// <param name="module">The <see cref="ProcessModule" /> object corresponding to the library to free.</param>
 public static void FreeLibrary(ProcessModule module)
 {
     FreeLibrary(module.ModuleName);
 }
Exemplo n.º 12
0
 /// <summary>
 ///     Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL).
 /// </summary>
 /// <param name="module">The <see cref="ProcessModule" /> object corresponding to the module.</param>
 /// <param name="functionName">The function or variable name, or the function's ordinal value.</param>
 /// <returns>If the function succeeds, the return value is the address of the exported function.</returns>
 public static IntPtr GetProcAddress(ProcessModule module, string functionName)
 {
     return(GetProcAddress(module.ModuleName, functionName));
 }
Exemplo n.º 13
0
 internal UiModule([NotNull] ProcessModule module)
 {
     this._module = module;
 }
Exemplo n.º 14
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="InjectedModule" /> class.
 /// </summary>
 /// <param name="processPlus">The reference of the <see cref="IProcess" /> object.</param>
 /// <param name="module">The native <see cref="ProcessModule" /> object corresponding to the injected module.</param>
 /// <param name="mustBeDisposed">The module will be ejected when the finalizer collects the object.</param>
 public InjectedModule(IProcess processPlus, ProcessModule module, bool mustBeDisposed = true)
     : base(processPlus, module)
 {
     // Save the parameter
     MustBeDisposed = mustBeDisposed;
 }
Exemplo n.º 15
0
        private void Screen_Load(object sender, EventArgs e)
        {
            // Create new black fullscreen window on every additional screen
            foreach (Screen s in Screen.AllScreens)
            {
                if (s.Primary)
                {
                    continue;
                }

                Form black = new Form()
                {
                    BackColor       = System.Drawing.Color.Black,
                    ShowIcon        = false,
                    ShowInTaskbar   = false,
                    WindowState     = FormWindowState.Maximized,
                    MaximizeBox     = false,
                    MinimizeBox     = false,
                    FormBorderStyle = FormBorderStyle.None,
                    ControlBox      = false,
                    StartPosition   = FormStartPosition.Manual,
                    Location        = new Point(s.WorkingArea.Left, s.WorkingArea.Top)
                };

                // Prevent black screen from being closed
                black.FormClosing += delegate(object fSender, FormClosingEventArgs fe) { fe.Cancel = true; };

                // Show black screen
                black.Show();
            }

            // Set username
            if (!string.IsNullOrEmpty(DisplayName))
            {
                lblUsername.Text = DisplayName;
            }
            else if (!string.IsNullOrEmpty(Username))
            {
                lblUsername.Text = Username;
            }
            else
            {
                lblUsername.Text = "User";
            }

            // Set focus on password box
            ActiveControl = mtbPassword;

            // Disable WinKey, Alt+Tab, Ctrl+Esc
            // Source: https://stackoverflow.com/a/3227562
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;

            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook            = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);

            // Minimize all other windows
            // Source: https://stackoverflow.com/a/785110
            IntPtr lHwnd = FindWindow("Shell_TrayWnd", null);

            SendMessage(lHwnd, WM_COMMAND, (IntPtr)MIN_ALL, IntPtr.Zero);

            // Make this the active window
            WindowState = FormWindowState.Minimized;
            Show();
            WindowState = FormWindowState.Maximized;
        }
 public void CopyTo(ProcessModule[] array, int index);
Exemplo n.º 17
0
 public uint FindPattern(ProcessModule pModule, byte[] bPattern, string szMask)
 {
     return(FindPattern((uint)pModule.BaseAddress, pModule.ModuleMemorySize, bPattern, szMask));
 }
Exemplo n.º 18
0
        public void Run(RemoteHooking.IContext context)
        {
            try
            {
                var  args        = Environment.GetCommandLineArgs();
                bool enableDebug = false;
                foreach (var arg in args)
                {
                    if (arg == "--launch-debugger")
                    {
                        Debugger.Launch();
                    }
                    if (arg == "-d" || arg == "--enable-debug")
                    {
                        Debugger.Launch();
                    }
                }
                var kernel           = GetKernelModule().BaseAddress;
                var loadLibraryAFunc = Kernel32.GetProcAddress(kernel, "LoadLibraryA");
                var hook             = LocalHook.Create(loadLibraryAFunc, new LoadLibraryADelegate(LoadLibraryHook), null);
                hook.ThreadACL.SetExclusiveACL(Array.Empty <int>());
                Hooks.Add("LoadLibraryA", hook);

                if (Is64Bit)
                {
                    Kernel32.LoadLibrary("EngineWin64s.dll");
                }
                else
                {
                    Kernel32.LoadLibrary("EngineWin32s.dll");
                }
                foreach (ProcessModule module in Process.GetCurrentProcess().Modules)
                {
                    Console.WriteLine($"Module: {module.ModuleName}");
                }
                module   = GetEngineModule();
                resolver = new DiaSymbolResolver(module);
#if DEBUG
                LogEngineSymbols(resolver);
#endif
                PdbSymbolImporter.ImportSymbols(resolver);
                LuaHelper.InitHelper(resolver);

                Hook <InitLuaDelegate>("?InitLua@ScriptManager@sgg@@SAXXZ", InitLua);
                Hook <ScriptManagerUpdateDelegate>("?Update@ScriptManager@sgg@@SAXAEBM@Z", ScriptManagerUpdate);

                scriptManager = new ScriptManager(resolver, enableDebug);
                Console.WriteLine($"Created ScriptManager");
                RemoteHooking.WakeUpProcess();

                while (true)
                {
                    var code = Console.ReadLine();
                    Console.WriteLine("> {0}", code);
                    scriptManager.Eval(code);
                    Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw;
            }
        }
 /// <summary>
 /// Initialize the ProcessPropertyPageProjectFlavorCfg instance.
 /// </summary>
 public void Initialize(ProcessModule project, IVsCfg baseConfiguration, IVsProjectFlavorCfg innerConfiguration)
 {
     this.project = project;
     this.baseConfiguration = baseConfiguration;
     this.innerConfiguration = innerConfiguration;
     mapIVsCfgToProcessPropertyPageProjectFlavorCfg.Add(baseConfiguration, this);
 }
Exemplo n.º 20
0
 /// <summary>
 ///     Sets hook and assigns its ID for tracking
 /// </summary>
 /// <param name="proc">Internal callback function</param>
 /// <returns>Hook ID</returns>
 private static IntPtr SetHook(MouseHookHandler proc)
 {
     using ProcessModule module = Process.GetCurrentProcess().MainModule;
     return(SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(module?.ModuleName), 0));
 }
Exemplo n.º 21
0
 private static long ScanForSignature(Process proc, ProcessModule m, SearchSignature s)
 {
     return(ScanForSignature(proc, s, m.BaseAddress, m.ModuleMemorySize));
 }
Exemplo n.º 22
0
 public uint FindPattern(ProcessModule pModule, string szPattern, string szMask)
 {
     return(FindPattern(pModule, szPattern, szMask, ' '));
 }
Exemplo n.º 23
0
        /// <summary>
        /// Writes a debug log to the given directory.
        /// </summary>
        /// <param name="screenshotPath">The path to store the screenshot into.</param>
        /// <param name="exception">The exception to log about.</param>
        private void WriteDebugLog(string dumpFolder, Exception exception)
        {
            using (FileStream file = new FileStream(Path.Combine(dumpFolder, DebugLogFileName),
                                                    FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                using (StreamWriter stream = new StreamWriter(file))
                {
                    //Application information
                    string       separator  = new string('-', 100);
                    const string lineFormat = "{0,20}: {1}";
                    stream.WriteLine("Application Information");
                    stream.WriteLine(separator);
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Version", Assembly.GetEntryAssembly().GetFileVersion()));
                    StringBuilder commandLine = new StringBuilder();
                    foreach (string param in Environment.GetCommandLineArgs())
                    {
                        commandLine.Append(param);
                        commandLine.Append(' ');
                    }
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Command Line", commandLine.ToString().Trim()));
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Current Directory", Environment.CurrentDirectory));

                    //System Information
                    ComputerInfo info = new ComputerInfo();
                    stream.WriteLine();
                    stream.WriteLine("System Information");
                    stream.WriteLine(separator);
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Operating System",
                                                   string.Format(CultureInfo.InvariantCulture, "{0} {1}{2} {4}",
                                                                 info.OSFullName.Trim(), info.OSVersion.Trim(),
                                                                 string.IsNullOrEmpty(Environment.OSVersion.ServicePack) ?
                                                                 string.Empty :
                                                                 string.Format(CultureInfo.InvariantCulture, "({0})", Environment.OSVersion.ServicePack),
                                                                 SystemInfo.WindowsEdition == WindowsEditions.Undefined ?
                                                                 string.Empty : SystemInfo.WindowsEdition.ToString(),
                                                                 SystemInfo.ProcessorArchitecture)));
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   ".NET Runtime version", Environment.Version));
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Processor Count", Environment.ProcessorCount));
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Physical Memory", string.Format(CultureInfo.InvariantCulture,
                                                                                    "{0}/{1}", info.AvailablePhysicalMemory, info.TotalPhysicalMemory)));
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Virtual Memory", string.Format(CultureInfo.InvariantCulture,
                                                                                   "{0}/{1}", info.AvailableVirtualMemory, info.TotalVirtualMemory)));

                    //Disk Drives
                    stream.WriteLine();
                    stream.WriteLine("Logical Drives");
                    stream.WriteLine(separator);
                    foreach (DriveInfo drive in DriveInfo.GetDrives())
                    {
                        stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                       "Drive", drive.Name));
                        stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                       "Label", drive.VolumeLabel));
                        stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                       "Type", drive.DriveType));
                        stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                       "Format", drive.DriveFormat));
                        stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                       "Total Size", drive.TotalSize));
                        stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                       "Available Space", drive.AvailableFreeSpace));
                    }
                    stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                   "Pagefile size", Environment.SystemPageSize));

                    //Running processes
                    stream.WriteLine();
                    stream.WriteLine("Running Processes");
                    stream.WriteLine(separator);
                    {
                        int i = 0;
                        foreach (Process process in Process.GetProcesses())
                        {
                            try
                            {
                                ProcessModule mainModule = process.MainModule;
                                stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                               string.Format(CultureInfo.InvariantCulture, "Process[{0}]", ++i),
                                                               string.Format(CultureInfo.InvariantCulture, "{0} [{1}.{2}.{3}.{4}{5}]",
                                                                             mainModule.FileName,
                                                                             mainModule.FileVersionInfo.FileMajorPart,
                                                                             mainModule.FileVersionInfo.FileMinorPart,
                                                                             mainModule.FileVersionInfo.FileBuildPart,
                                                                             mainModule.FileVersionInfo.FilePrivatePart,
                                                                             string.IsNullOrEmpty(mainModule.FileVersionInfo.FileVersion) ?
                                                                             string.Empty :
                                                                             string.Format(CultureInfo.InvariantCulture, " <{0}>",
                                                                                           mainModule.FileVersionInfo.FileVersion))));
                            }
                            catch (Win32Exception)
                            {
                            }
                            catch (InvalidOperationException)
                            {
                            }
                        }
                    }

                    //Exception Information
                    stream.WriteLine();
                    stream.WriteLine("Exception Information (Outermost to innermost)");
                    stream.WriteLine(separator);

                    //Open a stream to the Stack Trace Log file. We want to separate the stack
                    //trace do we can check against the server to see if the crash is a new one
                    using (StreamWriter stackTraceLog = new StreamWriter(
                               Path.Combine(dumpFolder, BlackBoxReport.StackTraceFileName)))
                    {
                        Exception currentException = exception;
                        for (uint i = 1; currentException != null; ++i)
                        {
                            stream.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                           "Exception {0}:", i));
                            stream.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                           lineFormat, "Message", currentException.Message));
                            stream.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                           lineFormat, "Exception Type", currentException.GetType().FullName));
                            stackTraceLog.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                                  "Exception {0}: {1}", i, currentException.GetType().FullName));

                            //Parse the stack trace
                            string[] stackTrace = currentException.StackTrace.Split(new char[] { '\n' });
                            for (uint j = 0; j < stackTrace.Length; ++j)
                            {
                                stream.WriteLine(string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                               string.Format(CultureInfo.InvariantCulture,
                                                                             "Stack Trace [{0}]", j), stackTrace[j].Trim()));
                                stackTraceLog.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                                      "{0}", stackTrace[j].Trim()));
                            }

                            uint k = 0;
                            foreach (System.Collections.DictionaryEntry value in currentException.Data)
                            {
                                stream.WriteLine(
                                    string.Format(CultureInfo.InvariantCulture, lineFormat,
                                                  string.Format(CultureInfo.InvariantCulture, "Data[{0}]", ++k),
                                                  string.Format(CultureInfo.InvariantCulture, "{0} {1}",
                                                                value.Key.ToString(), value.Value.ToString())));
                            }

                            //End the exception and get the inner exception.
                            stream.WriteLine();
                            currentException = currentException.InnerException;
                        }
                    }
                }
        }
Exemplo n.º 24
0
 public InjectedModule(ProcessModule module)
 {
     Module  = module;
     exports = new Dictionary <string, IntPtr>();
 }
Exemplo n.º 25
0
 internal SingleModule(ProcessModule module)
 {
     _module = module;
 }
Exemplo n.º 26
0
        public Background()
        {
            // Initialise low level keyboard hook
            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;

            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook            = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);

            // Open the file taskmgr.exe to disable the task manager
            // http://stackoverflow.com/questions/1660106/block-controlaltdelete
            fs = new FileStream(System.IO.Path.Combine(Environment.SystemDirectory, "taskmgr.exe"), FileMode.Open, FileAccess.ReadWrite, FileShare.None);
            // Hide the taskbar
            // http://www.codeproject.com/Articles/7392/Lock-Windows-Desktop
            ShowWindow(FindWindow("Shell_TrayWnd", null), (int)SHOWWINDOW.SW_HIDE);
            ShowWindow(GetDlgItem(FindWindow("Shell_TrayWnd", null), 0x130), (int)SHOWWINDOW.SW_HIDE);

            // Disable the maximise and minise buttons. Also set the form to full screen
            // http://http://stackoverflow.com/questions/3025923/disabling-minimize-maximize-on-winform
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.WindowState = FormWindowState.Maximized;

            // Remove the title bar
            // http://stackoverflow.com/questions/3594086/how-to-create-a-form-with-a-border-but-no-title-bar-like-volume-control-on-wi
            this.Text            = string.Empty;
            this.ControlBox      = false;
            this.FormBorderStyle = FormBorderStyle.SizableToolWindow;

            if (!File.Exists(ConfigFileName))
            {
                // The config file does not exist. Use the default values
                exitTimed  = DefaultExitTimed;
                exitTime   = DefaultExitTime;
                program    = DefaultProgram;
                programDir = DefaultProgramDir;
                return;
            }

            // Read the config file
            string line;

            string[] arrayVar;
            using (StreamReader reader = new StreamReader(ConfigFileName, true))
            {
                for (; !string.IsNullOrEmpty(line = reader.ReadLine());)
                {
                    arrayVar = line.Split('=');
                    switch (arrayVar[0].Trim())
                    {
                    case "Timed":
                        if (string.IsNullOrEmpty(arrayVar[1].Trim()))
                        {
                            exitTimed = DefaultExitTimed;
                        }
                        else
                        {
                            exitTimed = Convert.ToBoolean(arrayVar[1]);
                        }
                        break;

                    case "Time":
                        if (string.IsNullOrEmpty(arrayVar[1].Trim()))
                        {
                            exitTime = DefaultExitTime;
                        }
                        else
                        {
                            exitTime = Convert.ToUInt16(arrayVar[1]);
                        }
                        break;

                    case "Program":
                        if (string.IsNullOrEmpty(arrayVar[1].Trim()))
                        {
                            program = DefaultProgram;
                        }
                        else
                        {
                            program = arrayVar[1].Trim();
                        }
                        break;

                    case "ProgramDir":
                        if (string.IsNullOrEmpty(arrayVar[1].Trim()))
                        {
                            programDir = DefaultProgramDir;
                        }
                        else
                        {
                            programDir = arrayVar[1].Trim();
                        }
                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
            }

            InitializeComponent();

            // Set up for the timed mode - No exit before the time expires
            if (exitTimed)
            {
                timerExit.Enabled  = true;
                timerExit.Interval = exitTime * 60000;
                timerExit.Start();
            }
        }
Exemplo n.º 27
0
 /// <summary />
 public Module(Process process, ProcessModule processModule)
 {
     Process       = process;
     ProcessModule = processModule;
 }
Exemplo n.º 28
0
        //因为可能无法随时找到正确的地址,因此在程序开始时自动不断地寻找地址,找到可能正确的就保存下来以备后用。
        private void SearchAddressThread()
        {
            while (true)
            {
                Process[] process_search = Process.GetProcessesByName("FarmTogether");
                if (process_search.Length != 0)
                {
                    ProcessModuleCollection modules = process_search[0].Modules;
                    ProcessModule           dll     = null;
                    foreach (ProcessModule i in modules)
                    {
                        if (i.ModuleName == "UnityPlayer.dll")
                        {
                            dll = i;
                            break;
                        }
                    }
                    try
                    {
                        long DllAddrPlus = dll.BaseAddress.ToInt64() + ((IntPtr)0x151f010).ToInt64();
                        long nextaddr    = MRead(DllAddrPlus);
                        nextaddr  = MRead(nextaddr + 0x60);
                        nextaddr  = MRead(nextaddr + 0x48);
                        nextaddr  = MRead(nextaddr + 0x1c8);
                        nextaddr  = MRead(nextaddr + 0x10);
                        nextaddr  = MRead(nextaddr + 0x180);
                        nextaddr  = MRead(nextaddr + 0x28);
                        nextaddr += 0x208;//此地址保存当前季节1,2,4,8
                        int NowSeason = (int)MRead(nextaddr, false);
                        if (NowSeason == 1 || NowSeason == 2 || NowSeason == 4 || NowSeason == 8)
                        {
                            if (MRead(nextaddr + 0x8, false) - MRead(nextaddr + 0xc, false) <= (long)1020 && MRead(nextaddr + 0x8, false) - MRead(nextaddr + 0xc, false) >= (long)0)
                            {
                                TickBaseAddress = nextaddr;
                            }
                        }


                        else//从另外一个dll处出发寻找,另一种途径
                        {
                            dll = null;
                            foreach (ProcessModule i in modules)
                            {
                                if (i.ModuleName == "mono.dll")
                                {
                                    dll = i;
                                    break;
                                }
                            }
                            try
                            {
                                DllAddrPlus = dll.BaseAddress.ToInt64() + ((IntPtr)0x265a20).ToInt64();
                                nextaddr    = MRead(DllAddrPlus);
                                if (nextaddr == (long)0)//这些是因为CE找到的指针有时会变动,导致有可能找不到要找的地址
                                {
                                    continue;
                                }
                                nextaddr = MRead(nextaddr + 0xa0);//后续的偏移
                                if (nextaddr == (long)0)
                                {
                                    continue;
                                }
                                nextaddr = MRead(nextaddr + 0xc8);
                                if (nextaddr == (long)0)
                                {
                                    continue;
                                }
                                nextaddr = MRead(nextaddr + 0x20);
                                if (nextaddr == (long)0)
                                {
                                    continue;
                                }
                                nextaddr = MRead(nextaddr + 0xe0);
                                if (nextaddr == (long)0)
                                {
                                    continue;
                                }
                                nextaddr = MRead(nextaddr + 0x68);
                                if (nextaddr == (long)0)
                                {
                                    continue;
                                }
                                nextaddr = MRead(nextaddr + 0x28);
                                if (nextaddr == (long)0)
                                {
                                    continue;
                                }
                                nextaddr += 0x208;//此地址保存当前季节1,2,4,8
                                NowSeason = (int)MRead(nextaddr, false);
                                if (NowSeason == 1 || NowSeason == 2 || NowSeason == 4 || NowSeason == 8)
                                {
                                    if (MRead(nextaddr + 0x8, false) - MRead(nextaddr + 0xc, false) <= (long)1020 && MRead(nextaddr + 0x8, false) - MRead(nextaddr + 0xc, false) >= (long)0)
                                    {
                                        TickBaseAddress = nextaddr;
                                    }
                                }
                            }
                            catch { }
                        }
                    }
                    catch { continue; }
                }
                Thread.Sleep(500);
            }
        }
Exemplo n.º 29
0
        public AddressList_244_32(MemManager manager)
        {
            FoundAddresses = false;
            ProcessModule exe = manager.HookedProcess.MainModule;

            InjectLocation = manager.SigScan(exe.BaseAddress, exe.ModuleMemorySize, 5,
                                             "E8 ????????",      // call Talos.exe + 63C640

                                                                 // jmp 017F0000
                                             "??????????",       // OR
                                                                 // mov ecx,[esi+08]
                                                                 // test ecx, ecx

                                             "0F84 ????????",    // je Talos.exe + 641B8E
                                             "E8 ????????",      // call Talos.exe + 867970
                                             "85 C0",            // test eax, eax
                                             "0F84 ????????",    // je Talos.exe + 641AEC
                                             "83 3D ???????? 00" // cmp dword ptr[Talos.exe + 118860C], 00

                                             );
            if (InjectLocation == IntPtr.Zero)
            {
                return;
            }
            InjectInstructionLength = 5;

            IntPtr tmp = manager.SigScan(exe.BaseAddress, exe.ModuleMemorySize, 6,
                                         "F3 0F11 45 CC", // movss[ebp - 34], xmm0
                                         "E8 ????????",   // call Talos.exe + 83A330
                                         "83 C4 14"       // add esp, 14
                                         );

            if (tmp == IntPtr.Zero)
            {
                return;
            }
            DrawText = manager.ReadDisplacement(tmp, false);

            tmp = manager.SigScan(exe.BaseAddress, exe.ModuleMemorySize, 1,
                                  "E8 ????????",    // call Talos.exe + 82FE20
                                  "8B 4D FC",       // mov ecx,[ebp - 04]
                                  "8B 15 ????????", // mov edx,[Talos.exe + 11E8A20]
                                  "0F57 C0",        // xorps xmm0, xmm0
                                  "83 C4 18"        // add esp, 18
                                  );
            if (tmp == IntPtr.Zero)
            {
                return;
            }
            DrawBox  = manager.ReadDisplacement(tmp, false);
            Viewport = manager.Read <IntPtr>(IntPtr.Add(tmp, 9));

            tmp = manager.SigScan(exe.BaseAddress, exe.ModuleMemorySize, 8,
                                  "83 C4 1C",    // add esp,1C
                                  "85 C0",       // test eax, eax
                                  "74 ??",       // je Talos.exe + 641B7E
                                  "68 ????????", // push Talos.exe + 11D6B60
                                  "E8 ????????"  // call Talos.exe + 81F230
                                  );
            if (tmp == IntPtr.Zero)
            {
                return;
            }
            Font    = manager.Read <IntPtr>(tmp);
            SetFont = manager.ReadDisplacement(IntPtr.Add(tmp, 5), false);

            FoundAddresses = true;
        }
Exemplo n.º 30
0
        static private void ThreadListen(object ob)
        {
            Process[] procList = new Process[200];
            while (g_thListenStop)
            {
                //清楚无效的pid记录
                FlushProcessLib();

                //特定时间段检测
                bool spcTime = IsSpcTime();

                //Process curProcess;
                procList = Process.GetProcesses();
                if (spcTime && dic_Game_Process.Count > g_SpcTimeLimitNum)
                {
                    //MessageBox.Show("IsSpcTime");
                    CloseAllGame(ob);
                }
                else
                {
                    //MessageBox.Show("not IsSpcTime");
                }
                foreach (var curProcess in procList)
                {
                    try
                    {
                        if (curProcess.ProcessName.ToString().Contains("按键精灵") &&
                            g_bLimitKeyPress && spcTime)
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (FindWindow(null, "按键精灵") != 0 &&
                            g_bLimitKeyPress && spcTime)
                        {
                            CloseAllGame(ob);
                        }

                        if (curProcess.ProcessName.ToString().Contains("金山游侠"))
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (FindWindow(null, "金山游侠") != 0)
                        {
                            CloseAllGame(ob);
                        }

                        if (curProcess.ProcessName.ToString() == "Play" &&
                            g_bLimitEasyGame && spcTime)
                        {
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }


                        if (FindWindow(null, "简单游") != 0 &&
                            g_bLimitEasyGame && spcTime)
                        {
                            CloseAllGame(ob);
                        }

                        if (curProcess.ProcessName.ToString().Contains("main.dat") &&
                            g_bLimitBB)
                        {
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (FindWindow(null, "三国贝贝") != 0 &&
                            g_bLimitBB)
                        {
                            CloseAllGame(ob);
                        }

                        if (curProcess.ProcessName.ToString().Contains("LD.exe"))
                        {
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (FindWindow(null, "Ld") != 0)
                        {
                            CloseAllGame(ob);
                        }


                        ProcessModule m       = curProcess.MainModule;
                        string        descStr = m.FileVersionInfo.FileDescription;
                        if (descStr.Contains("按键") &&
                            descStr.Contains("精灵") &&
                            g_bLimitKeyPress && spcTime)
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (m.FileVersionInfo.FileDescription.Contains("main.dat") &&
                            g_bLimitBB && spcTime)
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (m.FileVersionInfo.FileDescription.Contains("Play.exe") &&
                            g_bLimitEasyGame && spcTime)
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (m.FileVersionInfo.FileDescription.Contains("金山游侠"))
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }
                        if (m.FileVersionInfo.FileDescription.Contains("LD.exe"))
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }

                        if (m.FileVersionInfo.FileDescription.Contains("SoWorker"))
                        {
                            //MessageBox.Show("使用受禁止的辅助工具将影响游戏的正常运行,请您遵守游戏规则!");
                            //如果找到,干掉所有的temp.tmp进程兵器杀出temp.tmp文件
                            CloseAllGame(ob);
                        }
                    }
                    catch
                    {
                    }
                }

                Thread.Sleep(g_ThreadListenSleep * 1000);
            }
        }
Exemplo n.º 31
0
 public LocalModule(ProcessModule module)
 {
     Module = module;
 }
Exemplo n.º 32
0
 public IntPtr FindPattern(ProcessModule moduleInfo, string pattern, int offset = 0) => FindPattern(moduleInfo, GetPattern(pattern), offset);
Exemplo n.º 33
0
 /// <summary>
 /// Gets the file name of this process module without the path
 /// </summary>
 /// <param name="module"></param>
 /// <returns></returns>
 public static string GetFileNameNoPath(this ProcessModule module)
 {
     return(Path.GetFileName(module.FileName));
 }
 public bool Contains(ProcessModule module);
Exemplo n.º 35
0
 public static PEInfomation Load(int ProcessID, ProcessModule module)
 {
     return(Load(ProcessID, module.BaseAddress));
 }
 public int IndexOf(ProcessModule module);
Exemplo n.º 37
0
 /// <summary>
 /// Sets hook and assigns its ID for tracking
 /// </summary>
 /// <param name="proc">Internal callback function</param>
 /// <param name="handle">Handle for resource (keyboard or mouse?)</param>
 /// <returns>Hook ID</returns>
 static IntPtr SetHook(MouseHookHandler proc, int handle)
 {
     using (ProcessModule module = Process.GetCurrentProcess().MainModule)
         //return NativeMethods.SetWindowsHookEx(handle, proc, NativeMethods.GetModuleHandle(module.ModuleName), 0);
         return(NativeMethods.SetWindowsHookEx(handle, proc, IntPtr.Zero, 0));
 }
Exemplo n.º 38
0
        //#####################################################################################################################
        #endregion

        public MainForm()
        {
            InitializeComponent();

            // string updtmess = HttpUtility.HtmlEncode(Regex.Escape("This is a test message\nhello\n123"));
            // MessageBox.Show(updtmess);
            // Clipboard.SetText(updtmess);

            ////this.numFoV.Maximum = Convert.ToDecimal(DefaultGameMode.c_FoV_upperLimit); //new decimal(new int[] { c_FoV_upperLimit, 0, 0, 0 });
            ////this.numFoV.Minimum = Convert.ToDecimal(DefaultGameMode.c_FoV_lowerLimit); //new decimal(new int[] { c_FoV_lowerLimit, 0, 0, 0 });

            //MessageBox.Show(pFoV.ToString("x8"));

            ////if (File.Exists(settingsFile)) ReadSettings();

            ////lblVersion.Text = "v" + c_toolVer;
            ////lblVersion.Visible = true;

            saveSettings = false;
            ReadGameMode();
            saveSettings = true;

            ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;

            objKeyboardProcess = new LowLevelKeyboardProc(captureKey);
            ptrHook            = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);

            ////IsGameInstalled();

            //MessageBox.Show(Path.GetTempPath());
            //if (gameFound)
            //{

            /*string dirName = Path.Combine(Path.GetTempPath(), "MW3_fov_lib");
             * if (!Directory.Exists(dirName))
             *  Directory.CreateDirectory(dirName);
             * string dllPath = Path.Combine(dirName, "MW3_fov_lib.dll");
             *
             * using (Stream stm = Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".Resources.MW3_fov_lib.dll"))
             * {
             *  try
             *  {
             *      using (Stream outFile = File.Create(dllPath))
             *      {
             *          const int sz = 4096;
             *          byte[] buf = new byte[sz];
             *          while (true)
             *          {
             *              int nRead = stm.Read(buf, 0, sz);
             *              if (nRead < 1)
             *                  break;
             *              outFile.Write(buf, 0, nRead);
             *          }
             *      }
             *  }
             *  catch { }
             * }
             *
             * if (!debug)
             * {
             *  IntPtr h = LoadLibrary(dllPath);
             *  if (h == IntPtr.Zero)
             *  {
             *      MessageBox.Show("Unable to load library " + dllPath, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             *      Application.Exit();
             *  }
             * }*/

            ////numFoV.Value = Convert.ToDecimal(fFoV);
            ////numFoV.Enabled = true;
            ////ToggleButton(!isRunning(false));

            TimerCheck.Start();
            //}
        }
Exemplo n.º 39
0
 public int ImageAddress()
 {
     this.BaseAddress = 0;
         this.myProcessModule = this.MyProcess[0].MainModule;
         this.BaseAddress = (int)this.myProcessModule.BaseAddress;
         return this.BaseAddress;
 }