Example #1
0
        public static void xMain(string[] args)
        {
            Injector.LogMessage("Starting the injection process...", false);

            var windowHandle = (IntPtr)long.Parse(args[0]);
            var assemblyName = args[1];
            var className    = args[2];
            var methodName   = args[3];
            var settingsFile = args[4];

            var injectorData = new InjectorData
            {
                AssemblyName = assemblyName,
                ClassName    = className,
                MethodName   = methodName,
                SettingsFile = settingsFile
            };

            Injector.Launch(windowHandle, injectorData);

            //check to see that it was injected, and if not, retry with the main window handle.
            var process = GetProcessFromWindowHandle(windowHandle);

            if (process != null && !CheckInjectedStatus(process) && process.MainWindowHandle != windowHandle)
            {
                Injector.LogMessage("Could not inject with current handle... retrying with MainWindowHandle", true);
                Injector.Launch(process.MainWindowHandle, injectorData);
                CheckInjectedStatus(process);
            }
        }
Example #2
0
        public static void InjectIntoProcess(IntPtr windowHandle, InjectorData injectorData)
        {
            var processFromHandle = ProcessWrapper.FromWindowHandle(windowHandle);

            if (processFromHandle is null)
            {
                return; // todo: add logging
            }

            InjectIntoProcess(processFromHandle, injectorData);
        }
Example #3
0
        static void Main(string[] args)
        {
            try
            {
                var exefile    = @"C:\Program Files (x86)\Microsoft Help Viewer\v2.3\HlpViewer.Ms.exe";
                var winclsname = "HwndWrapper[HlpViewer.Ms.exe;";
                if (!System.IO.File.Exists(exefile))
                {
                    exefile    = @"C:\Program Files (x86)\Microsoft Help Viewer\v2.3\HlpViewer.exe";
                    winclsname = "HwndWrapper[HlpViewer.exe;";
                }
                Process.Start(exefile, string.Join(" ", args)); // GetProcessFromWindowHandle(windowHandle);
                var s = new WindowHelper();
                int c = 0;
                while (c < 10)
                {
                    c++;
                    Thread.Sleep(1500);

                    var hwnd = s.GetHwndWrapper(winclsname);
                    if (hwnd == IntPtr.Zero)
                    {
                        continue;
                    }

                    var process = ManagedInjector.GetProcessFromWindowHandle(hwnd);

                    if (process != null && process.MainWindowHandle != null && !ManagedInjector.CheckInjectedStatus(process))
                    {
                        Thread.Sleep(1500);

                        var loc = typeof(HlpViewerEx.Program).Assembly.Location;
                        loc = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(loc), "HlpvwFake.dll");
                        var injectorData = new InjectorData
                        {
                            AssemblyName = loc,
                            ClassName    = "LoaderImpl",
                            MethodName   = "Worker",
                            SettingsFile = "Woo-hoo, Snoopy is here!"
                        };

                        Injector.LogMessage("Could not inject with current handle... retrying with MainWindowHandle", true);
                        Injector.Launch(process.MainWindowHandle, injectorData);
                        ManagedInjector.CheckInjectedStatus(process);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #4
0
        private void AddInjector(InjectorData injectorData, InjectorCollectionNode injectorsNode)
        {
            ConfigurationNode injectorNode =
                NodeCreationService.CreateNodeByDataType(injectorData.GetType(), new object[] { injectorData });

            if (injectorNode == null)
            {
                LogNodeMapError(injectorsNode, injectorData.GetType());
            }
            else
            {
                injectorsNode.AddNode(injectorNode);
            }
        }
 public static void InjectIntoProcess(ProcessWrapper processWrapper, InjectorData injectorData)
 {
     InjectSnoop(processWrapper, injectorData);
 }
 public static void InjectIntoProcess(IntPtr windowHandle, InjectorData injectorData)
 {
     InjectIntoProcess(ProcessWrapper.FromWindowHandle(windowHandle), injectorData);
 }
        private static void InjectSnoop(ProcessWrapper processWrapper, InjectorData injectorData)
        {
            var injectorDllName   = $"Snoop.GenericInjector.{processWrapper.Bitness}.dll";
            var pathToInjectorDll = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), injectorDllName);

            LogMessage($"Trying to load \"{pathToInjectorDll}\"...");

            if (File.Exists(pathToInjectorDll) == false)
            {
                throw new FileNotFoundException("Could not find injector dll.", pathToInjectorDll);
            }

            var parameters = new[]
            {
                processWrapper.SupportedFrameworkName,
                injectorData.FullAssemblyPath,
                injectorData.ClassName,
                injectorData.MethodName,
                injectorData.SettingsFile
            };

            var stringForRemoteProcess = string.Join("<|>", parameters);

            var bufLen = (stringForRemoteProcess.Length + 1) * Marshal.SizeOf(typeof(char));

            LogMessage($"Trying to allocate {bufLen} bytes in foreign process...");
            Trace.WriteLine(Marshal.GetLastWin32Error());

            var remoteAddress = NativeMethods.VirtualAllocEx(processWrapper.Handle, IntPtr.Zero, (uint)bufLen, NativeMethods.AllocationType.Commit | NativeMethods.AllocationType.Reserve, NativeMethods.MemoryProtection.ReadWrite);

            if (remoteAddress == IntPtr.Zero)
            {
                throw new Win32Exception();
            }

            LogMessage("Successfully allocated memory in foreign process.");

            var address = Marshal.StringToHGlobalUni(stringForRemoteProcess);
            var size    = (uint)(sizeof(char) * stringForRemoteProcess.Length);

            try
            {
                var writeProcessMemoryResult = NativeMethods.WriteProcessMemory(processWrapper.Handle, remoteAddress, address, size, out var bytesWritten);

                if (writeProcessMemoryResult == false ||
                    bytesWritten == 0)
                {
                    throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
                }

                var hLibrary = IntPtr.Zero;

                try
                {
                    // Load library into current process before trying to get the remote proc address
                    hLibrary = NativeMethods.LoadLibrary(pathToInjectorDll);

                    // Load library into foreign process before invoking our method
                    var moduleHandleInForeignProcess = LoadLibraryInForeignProcess(processWrapper, pathToInjectorDll);

                    try
                    {
                        var remoteProcAddress = NativeMethods.GetRemoteProcAddress(processWrapper.Process, injectorDllName, "ExecuteInDefaultAppDomain");

                        if (remoteProcAddress == UIntPtr.Zero)
                        {
                            LogMessage("Could not get proc address for \"ExecuteInDefaultAppDomain\".");
                            return;
                        }

                        var remoteThread = NativeMethods.CreateRemoteThread(processWrapper.Handle, IntPtr.Zero, 0, remoteProcAddress, remoteAddress, 0, out _);

                        try
                        {
                            if (remoteThread == IntPtr.Zero)
                            {
                                LogMessage("Could not create remote thread.");
                                throw new Win32Exception();
                            }

                            NativeMethods.WaitForSingleObject(remoteThread);

                            // Get handle of the loaded module
                            NativeMethods.GetExitCodeThread(remoteThread, out var resultFromExecuteInDefaultAppDomain);

                            LogMessage($"Received \"{resultFromExecuteInDefaultAppDomain}\" from injector component.");

                            if (resultFromExecuteInDefaultAppDomain != IntPtr.Zero)
                            {
                                throw Marshal.GetExceptionForHR((int)resultFromExecuteInDefaultAppDomain.ToInt64());
                            }
                        }
                        finally
                        {
                            NativeMethods.CloseHandle(remoteThread);
                        }
                    }
                    finally
                    {
                        FreeLibraryInForeignProcess(processWrapper, injectorDllName, moduleHandleInForeignProcess);
                    }
                }
                finally
                {
                    if (hLibrary != IntPtr.Zero)
                    {
                        NativeMethods.FreeLibrary(hLibrary);
                    }

                    try
                    {
                        NativeMethods.VirtualFreeEx(processWrapper.Handle, remoteAddress, bufLen, NativeMethods.AllocationType.Release);
                    }
                    catch (Exception e)
                    {
                        LogMessage(e.ToString());
                    }
                }
            }
            finally
            {
                Marshal.FreeHGlobal(address);
            }
        }
Example #8
0
        public void CanSerializeConfigurationFixture()
        {
            PolicyInjectionSettings settings = new PolicyInjectionSettings();

            PolicyData policy1 = new PolicyData(policy1Name);
            PolicyData policy2 = new PolicyData(policy2Name);

            settings.Policies.Add(policy1);
            settings.Policies.Add(policy2);

            CustomCallHandlerData handler1 = new CustomCallHandlerData(handler1Name, typeof(CallCountHandler));

            handler1.SetAttributeValue("customHandlerAttribute", "customHandlerAttributeValue");

            CustomMatchingRuleData customMatchingRule = new CustomMatchingRuleData(matchingRule1Name, typeof(TypeMatchingAssignmentRule));

            customMatchingRule.SetAttributeValue("customMatchingRuleAttribute", "customMatchingRuleAttributeValue");

            policy1.Handlers.Add(handler1);
            policy1.MatchingRules.Add(customMatchingRule);

            InjectorData     remotingInjectorData = new RemotingInjectorData("remoting");
            FakeInjectorData fakeInjectorData     = new FakeInjectorData("fake");

            fakeInjectorData.ExtraValue = 75;

            settings.Injectors.Add(remotingInjectorData);
            settings.Injectors.Add(fakeInjectorData);
            settings.Injectors.DefaultInjector = fakeInjectorData.Name;

            Dictionary <string, ConfigurationSection> sections = new Dictionary <string, ConfigurationSection>();

            sections.Add(PolicyInjectionSettings.SectionName, settings);

            IConfigurationSource configurationSource = ConfigurationTestHelper.SaveSectionsInFileAndReturnConfigurationSource(sections);

            PolicyInjectionSettings deserializedSection = (PolicyInjectionSettings)configurationSource.GetSection(PolicyInjectionSettings.SectionName);

            Assert.AreEqual(2, deserializedSection.Policies.Count);

            PolicyData deserializedPolicy1 = deserializedSection.Policies.Get(0);

            Assert.IsNotNull(deserializedPolicy1);
            Assert.AreEqual(policy1Name, deserializedPolicy1.Name);

            CallHandlerData deserializedHandler = deserializedPolicy1.Handlers.Get(0);

            Assert.IsNotNull(deserializedHandler);
            Assert.IsNotNull(deserializedHandler as CustomCallHandlerData);
            Assert.AreEqual(handler1Name, deserializedHandler.Name);
            Assert.AreEqual(typeof(CallCountHandler), deserializedHandler.Type);
            Assert.AreEqual("customHandlerAttributeValue", (string)deserializedHandler.ElementInformation.Properties["customHandlerAttribute"].Value);

            Assert.AreEqual(policy2Name, deserializedSection.Policies.Get(1).Name);

            MatchingRuleData deserializedMatchingRule = deserializedPolicy1.MatchingRules.Get(0);

            Assert.IsNotNull(deserializedMatchingRule as CustomMatchingRuleData);
            Assert.AreEqual(matchingRule1Name, deserializedMatchingRule.Name);
            Assert.AreEqual(typeof(TypeMatchingAssignmentRule), deserializedMatchingRule.Type);
            Assert.AreEqual("customMatchingRuleAttributeValue", (string)deserializedMatchingRule.ElementInformation.Properties["customMatchingRuleAttribute"].Value);

            Assert.AreEqual(2, deserializedSection.Injectors.Count);
            Assert.AreEqual(settings.Injectors.DefaultInjector,
                            deserializedSection.Injectors.DefaultInjector);

            InjectorData injector1Data = settings.Injectors[0];
            InjectorData injector2Data = settings.Injectors[1];

            Assert.AreEqual(typeof(RemotingInjectorData), injector1Data.GetType());
            Assert.AreEqual(typeof(FakeInjectorData), injector2Data.GetType());

            Assert.AreEqual(fakeInjectorData.ExtraValue, ((FakeInjectorData)injector2Data).ExtraValue);
        }
Example #9
0
        private static int Run(InjectorLauncherCommandLineOptions commandLineOptions)
        {
            Injector.LogMessage("Starting the injection process...", false);

            try
            {
                if (commandLineOptions.Debug)
                {
                    Debugger.Launch();
                }

                var processWrapper = ProcessWrapper.From(commandLineOptions.TargetPID, new IntPtr(commandLineOptions.TargetHwnd));

                // Check for target process and our bitness.
                // If they don't match we redirect everything to the appropriate injector launcher.
                {
                    var currentProcess        = Process.GetCurrentProcess();
                    var currentProcessBitness = ProcessWrapper.GetBitnessAsString(currentProcess);
                    if (processWrapper.Bitness.Equals(currentProcessBitness) == false)
                    {
                        Injector.LogMessage("Target process and injector process have different bitness, trying to redirect to secondary process...");

                        var originalProcessFileName = currentProcess.MainModule.ModuleName;
                        var correctBitnessFileName  = originalProcessFileName.Replace(currentProcessBitness, processWrapper.Bitness);
                        var processStartInfo        = new ProcessStartInfo(currentProcess.MainModule.FileName.Replace(originalProcessFileName, correctBitnessFileName), Parser.Default.FormatCommandLine(commandLineOptions))
                        {
                            CreateNoWindow   = true,
                            WorkingDirectory = currentProcess.StartInfo.WorkingDirectory
                        };

                        using (var process = Process.Start(processStartInfo))
                        {
                            if (process == null)
                            {
                                Injector.LogMessage("Failed to start process for redirection.");
                                return(1);
                            }

                            process.WaitForExit();
                            return(process.ExitCode);
                        }
                    }
                }

                var settingsFile = string.IsNullOrEmpty(commandLineOptions.SettingsFile) == false
                    ? commandLineOptions.SettingsFile
                    : new TransientSettingsData
                {
                    StartTarget        = SnoopStartTarget.SnoopUI,
                    TargetWindowHandle = processWrapper.WindowHandle.ToInt64()
                }.WriteToFile();

                var injectorData = new InjectorData
                {
                    FullAssemblyPath = GetAssemblyPath(processWrapper, commandLineOptions.Assembly),
                    ClassName        = commandLineOptions.ClassName,
                    MethodName       = commandLineOptions.MethodName,
                    SettingsFile     = settingsFile
                };
                Injector.LogMessage($"Start injecting \"{injectorData.FullAssemblyPath}\".");
                if (File.Exists(injectorData.FullAssemblyPath) == false)
                {
                    Injector.LogMessage($"Could not find \"{injectorData.FullAssemblyPath}\".");
                    return(1);
                }

                try
                {
                    Injector.InjectIntoProcess(processWrapper, injectorData);
                }
                catch (Exception exception)
                {
                    Injector.LogMessage($"Failed to inject Snoop into process {processWrapper.Process.ProcessName} (PID = {processWrapper.Process.Id})");
                    Injector.LogMessage(exception.ToString());
                    return(1);
                }

                Injector.LogMessage($"Successfully injected Snoop into process {processWrapper.Process.ProcessName} (PID = {processWrapper.Process.Id})");

                return(0);
            }
            catch (Exception ex)
            {
                Injector.LogMessage(ex.ToString());
                return(1);
            }
        }
Example #10
0
 protected InjectorNode(InjectorData data)
     : base(data.Name)
 {
 }