Interpretation of method functions (plug-in prerequisites) in C#Dynamic Interception of Third Party Processes

1. Preface

Due to project needs, recently studied the method of rewriting third-party programs by cross-process communication (running), directly overwriting the method functions in third-party programs by the target methods in your own programs; has been confused, through the search engine found a large number of solutions, the data is scarce, and ultimately no effort was lost, after two days of research, finally in GitHubI found two open source codes on the page, and I can achieve my needs by combining the two open source codes.Following is a further analysis of the principles of practice, followed by the address of the source code;
By sharing this article, you will know how to overwrite a method in a program run by a third party by injecting a dll module to implement your own business in it. This scenario is especially useful in making plug-ins!!!

2. Scenes

If there is a third-party application, at this time we need to intercept the third-party application, such as an operation in the third-party application that needs to overwrite their business with our business, what is a good solution to solve this situation?It is impossible for us to modify the code of third-party programs, so what is the solution?In fact, there is still a way to "modify the code of third-party programs, how" to "modify". See the following principles of practice, the following will take you into a different world of code!!!!

3. Practice

Principle simplification diagram:

In practice, I will write two client programs directly for code demonstration.

3.1.Implementation Principle

  • Hook Target Method:
    If you need to override the method specified to intercept third-party programs, you need the Hook method, which finds the open source DotNetDetour on github after searching for data, but the open source author is from the.Net framework4.5Beginning support, no support for.Net framework4.0My needs need to run on the old machine xp,It must be supported4.0Framework, all of which I fork have a modified source code to support the.Net framework4.0Frame, fork source code address: https://github.com/a312586670/DotNetDetour
  • Inject injects dll into target process
    After writing the method Hooke dll module for the target process, you need to consider injecting the dll module into the third equation process in order to achieve complete hook success and overwrite the method for the target process. Here I use fastWin32 to open the source code with the following code address: https://github.com/a312586670/FastWin32

3.2Create third-party program Demo

For demonstration purposes, I created a target client program myself, mainly with the following core code methods:

public class ProcessService
{
        public string GetProcessInfo()
        {
            return "This is TargetClient Client (third-party program)";
        }


        public ProcessResponse GetProcessInfo(ProcessRequest request)
        {
            return new ProcessResponse()
            {
                Name = "This is TargetClient Client (third-party program)",
                Version = request.Version
            };
        }
}

The UI interface interaction code is as follows:

 /// <summary>
    ///MainWindow.xaml Interactive logic
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnInfo_Click(object sender, RoutedEventArgs e)
        {
            var service = new ProcessService();
            this.txtInfo.Text = service.GetProcessInfo();
        }

        private void btnComplateInfo_Click(object sender, RoutedEventArgs e)
        {
            var service = new ProcessService();
            var response = service.GetProcessInfo(new ProcessRequest() { Version = "v-Demo 1.0 Edition" });
            this.txtInfo.Text = response.Name + response.Version;
        }
    }

There are two button events in the code above, calling two methods of ProcessService. Let's run the target client Demo program, clicking on two buttons to run the result as follows:

3.3Create Core Hook Class Library

Okay, we have already written the target third-party Demo program above. Next we need to write a core one Jlion.Process.HookCore Class libraries override two methods of the target ProcessService.
I've built one here Jlion.Process.HookCore Class library, referencing the DotNetDetour class library after my fork through the nuget package, as follows:

After successful application, we build the core hook method with the following code:

  public class ProcessHookService : IMethodHook
    {
        [HookMethod("Jlion.Process.Target.Client.ProcessService", null, null)]
        public string GetProcessInfo()
        {
            TextHelper.LogInfo($"This is Jlion.Process.HookCore.HookService dll. rewrite TargetClient Client's GetProcessInfo Result after method");
            return "This is Jlion.Process.HookCore.HookService dll. rewrite TargetClient Client's GetProcessInfo Result after method";
        }

        [OriginalMethod]
        public string GetProcessInfo_Original()
        {
            return null;
        }

        [HookMethod("Jlion.Process.Target.Client.ProcessService", null, null)]
        public object GetProcessInfo([RememberType("Jlion.Process.Target.Client.Model.ProcessRequest", false)] object request)
        {
            var json = JsonConvert.SerializeObject(request);
            TextHelper.LogInfo($"json:{json}");

            var name = "This is Jlion.Process.HookCore.HookService dll. rewrite TargetClient Client's GetProcessInfo(obj)Result after";
            return new ProcessResponse()
            {
                Name = name,
                Version = "Rewrite dll Edition"
            };
        }

        [OriginalMethod]
        public object GetProcessInfo_Original([RememberType("Jlion.Process.Target.Client.Model.ProcessRequest", false)] object request)
        {
            return null;
        }
    }

I'm not writing about the use of DotNetDetour in detail here, so I need to know that it's accessible https://github.com/a312586670/DotNetDetour View specific documents

CoreJlion.Process.HookCoreThe hook class library has also been created. Next, you need to create a service class that initializes the Hook (especially important) and must also be a static method with the following code:

 public class HookService
 {
        /// <summary>
        /// Hook Initialization
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static int Start(string msg)
        {
            try
            {
                TextHelper.LogInfo("start"+msg);
                MethodHook.Install();
            }
            catch
            {
                return -1;
            }
            return 1;
        }
    }

Basically at this pointJlion.Process.HookCoreHook Core Class Library has been created

3.4Module Injection Client

After creating the client, you need to reference the FastWin32 class library, as shown below:

Client injection Dll core code is as follows:

public class InjectService
{
                //Injected Core dll Path
		public static string path = AppDomain.CurrentDomain.BaseDirectory+ "Jlion.Process.HookCore.dll";

		/// <summary>
		///process id
		/// </summary>
		public static uint pid = 0;

		/// <summary>
		///Startup
		/// </summary>
		public static void Start()
		{
			Inject();
		}


		#region Private Method
		private static void Inject()
		{
			try
			{
				Injector.InjectManaged(pid, path, "Jlion.Process.HookCore.HookService", "Start", "ss", out int returnValue);
			}
			catch (Exception ex)
			{
			}
		}
		
		#endregion
	}

The core of the code is Injector.InjectManaged(), which has two refactoring methods:

Parameter description:

  • processId: Process ID of the target process ->pid
  • assemblyPath: absolute path of dll injected by core Hook
  • TypeeName: The namespace of the Hook initialization method, typically the entry initialization method that needs to be executed after injecting a module dll. This is the namespace of the HookService.Start method (Jlion.Process.HookCore.HookService) in the Hook core dll.
  • methodName: Method name to execute after injection
  • Argument: The argument required by the method
  • returnValue: Returns the method return value that was run after injection
The client UI core code is as follows:
/// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnInject_Click(object sender, RoutedEventArgs e)
        {
            InjectService.pid = Convert.ToUInt32(txbPid.Text.Trim());
            InjectService.Start();
        }
    }

The core injection Client Demo is also written here. We will run the injected client, enter the target process pid (or find the target process Id in the program), and then execute the two buttons of the third equation sequence created above. The result is as follows:

By writing a client program, after clicking Inject dll, then clicking on two button events of a third-party program, the results are as follows:


You can see that after clicking, the result of the run has been rewritten by the dynamically injected Jlion.Process.HookCore.dll, but the above code can also be rewritten and the original target run at the same time by calling the method at the end of the'_Original'suffix and returning null as the body of the method.

4. Summary

The DotNetDetour framework allows you to write Hook overrides of methods for target processes, override third-party processes with new methods, or continue to execute third-party methods.
FastWin32 calls the Win32 API to inject the dll module into the third-party process, and executes the initialization method after injection, which can override the original Hook method.
Does it feel amazing to be here? It can be used in the following scenarios:

  • It must be thought of as a plug-in program, which writes its own coverage business by overwriting the target program.
  • Grey-producing areas are more practical
  • Crack third-party billing software, etc.

Interested friends can download the Demo source code to play:
github source code address: https://github.com/a312586670/processClientDemo

Tags: C# github JSON

Posted on Sun, 17 May 2020 20:05:18 -0400 by new@php