How to hook into application and process startup in windows?

后端 未结 1 906
不思量自难忘°
不思量自难忘° 2020-12-03 16:08

I am trying to write a program that will hook into application startup and capture the commandline. Don\'t have an idea where to start as I am pretty green in windows progra

相关标签:
1条回答
  • 2020-12-03 16:46

    You didn't mention your prefered programming language, so I'll use C# for example snippets.

    You can start a process and capture/write into its standard IO streams.

    The following snippet, opens a process and captures its StdOut stream:

    using (var process = Process.Start(new ProcessStartInfo(FileName = @"yourExecutablePath", UseShellExecute = false, RedirectStandardOutput = true)))
        using (var stdout = process.StandardOutput)
            Console.WriteLine(stdout.ReadToEnd());
    

    EDIT 1

    Looks like you want to hook Windows APIs like CreateProcess.

    One way to do so is to write a kernel driver and use hooking techniques such as SSTD patching. But writing a kernel driver IMO is cumbersome.

    In some cases you can use user-level hooks. There are a few libraries that might help you with that, including: EasyHook, Deviare, and MS Detour.


    EDIT 2

    You can also use WMI as @David Heffernan suggested but it will only notify you AFTER the process gets started (as opposed to hooking, which allows you to run some arbitrary code BEFORE the hooked function gets called and/or override the function call):

    using System.Management;
    
    // Run this in another thread and make sure the event watcher gets disposed before exit
    
    var start = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));    
    
    start.EventArrived += new EventArrivedEventHandler(delegate (object sender, EventArrivedEventArgs e) {
        console.WriteLine("Name: {0}, Command Line: {1}", e.NewEvent.Properties["ProcessName"].Value, e.NewEvent.Properties["Commandline"].Value);
    });
    
    start.Start()
    
    0 讨论(0)
提交回复
热议问题