Please can some one help i cant get my hook to fire up

Mar 10, 2010 at 7:01 PM

Hi can any body help i must be stupid but i have been throught the tutorial how many time been on this site how many times my code look sright but i cant get it to fire up CreaDCW or StartDocW for some reason i get the demo to work i can get Writefile to work but thats it so please any body Chris even if you could help Please i am getting Desperate it but be something stupid i am doing but it is just not firing up

Thanks Jermey

Mar 11, 2010 at 9:15 AM

How about posting some code? :)

Mar 11, 2010 at 10:23 AM

Hi Norm2782 thank you very much for getting back to me here is my code i really think it is something i am doing stupid i have one question regarding the P-Invoke dllimport i went to the P-invoke site (http://www.pinvoke.net//) site and was wondering do you use CreateDCW or just CreateDC as they say on the site but in my code i used CreateDCW, but here goes i really think it is something small im doing wrong because as i said i can get writefile to work as well as the demo

main.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
using EasyHook;
using System.Windows.Forms;


namespace ProcessMonitor
{

    public struct DEVMODE // i need because CreateDCA structure
    {

        public const int CCHDEVICENAME = 32;
        public const int CCHFORMNAME = 32;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
        public string dmDeviceName;
        public short dmSpecVersion;
        public short dmDriverVersion;
        public short dmSize;
        public short dmDriverExtra;
        public int dmFields;

        public short dmOrientation;
        public short dmPaperSize;
        public short dmPaperLength;
        public short dmPaperWidth;

        public short dmScale;
        public short dmCopies;
        public short dmDefaultSource;
        public short dmPrintQuality;
        public short dmColor;
        public short dmDuplex;
        public short dmYResolution;
        public short dmTTOption;
        public short dmCollate;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHFORMNAME)]
        public string dmFormName;
        public short dmLogPixels;
        public int dmBitsPerPel;    // Declared wrong in the full framework
        public int dmPelsWidth;
        public int dmPelsHeight;
        public int dmDisplayFlags;
        public int dmDisplayFrequency;

        public int dmICMMethod;
        public int dmICMIntent;
        public int dmMediaType;
        public int dmDitherType;
        public int dmReserved1;
        public int dmReserved2;
        public int dmPanningWidth;
        public int dmPanningHeight;

        public int dmPositionX; // Using a PointL Struct does not work
        public int dmPositionY;
    }

 

    public class DemoInjection : EasyHook.IEntryPoint
    {
        public DemoInterface Interface = null;
        public LocalHook CreateFileHook = null;
        Stack<String> Queue = new Stack<string>();

        public DemoInjection(
            RemoteHooking.IContext InContext,
            String InChannelName)
        {
            Interface = RemoteHooking.IpcConnectClient<DemoInterface>(InChannelName);

            Interface.Ping(RemoteHooking.GetCurrentProcessId());
        }

        public void Run(
            RemoteHooking.IContext InContext,
            String InArg1)
        {
            try
            {
                CreateFileHook = LocalHook.Create(
                    LocalHook.GetProcAddress("gdi32.dll", "CreateDCW"),
                    new DCCreateDCA(CreateDCA_Hooked),
                    this);

                /*
                 * Don't forget that all hooks will start deaktivated...
                 * The following ensures that all threads are intercepted:
                 */
                CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });
            }
            catch (Exception e)
            {
                /*
                    Now we should notice our host process about this error...
                 */
                Interface.ReportError(RemoteHooking.GetCurrentProcessId(), e);

                return;
            }


            // wait for host process termination...
            try
            {
                while (Interface.Ping(RemoteHooking.GetCurrentProcessId()))
                {
                    Thread.Sleep(500);

                    // transmit newly monitored file accesses...
                    lock (Queue)
                    {
                        if (Queue.Count > 0)
                        {
                            String[] Package = null;

                            Package = Queue.ToArray();

                            Queue.Clear();

                            Interface.OnCreateFile(RemoteHooking.GetCurrentProcessId(), Package);
                        }
                    }
                }
            }
            catch (Exception ea)
            {
                // NET Remoting will raise an exception if host is unreachable
                Interface.ReportError(RemoteHooking.GetCurrentProcessId(), ea);
            }
        }

        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
        delegate IntPtr DCCreateDCA(
            String InDriver,
            String InDevice,
            String InOutput,
            DEVMODE InInitData);

        delegate void DCCreateDCAAsync(
            String InDriver,
            String InDevice,
            String InOutput,
            DEVMODE InInitData);

        // just use a P-Invoke implementation to get native API access from C# (this step is not necessary for C++.NET)
        [DllImport("gdi32.dll", CharSet = CharSet.Unicode, SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        static extern IntPtr CreateDCW(
            String InDriver,
            String InDevice,
            String InOutput,
            DEVMODE InInitData);

        // this is where we are intercepting all file accesses!
        // "CreateDCA" (ByVal lpDriverName As String, ByVal lpDeviceName As String,
        //              ByVal lpOutput As String, lpInitData As DEVMODE) As Long
        static IntPtr CreateDCA_Hooked(
            String InDriver,
            String InDevice,
            String InOutput,
            DEVMODE InInitData)
        {
            try
            {
                DemoInjection This = (DemoInjection)HookRuntimeInfo.Callback;
               
                lock (This.Queue)
                {
                    if (This.Queue.Count < 1000)
                        This.Queue.Push(InDevice);
                }
            }
            catch
            {
                //This.Queue.Push("ops, erro")
                //Interface.ReportError(RemoteHooking.GetCurrentProcessId(), e);
            }

            // call original API...
            return CreateDCW(
                InDriver,
                InDevice,
                InOutput,
                InInitData);
        }
   }
}

 DemoInteface.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace ProcessMonitor
{
    internal class MonitorEntry
    {
        public readonly String Access;
        public readonly DateTime Timestamp = DateTime.Now;
        public readonly Int32 ClientPID;

        public MonitorEntry(Int32 InClientPID,String InAccess)
        {
            ClientPID = InClientPID;
            Access = InAccess;
        }
    }

    /*
     * This is the class where our clients will connect to!
     *
     * Please note that setting any breakpoint here will cause the related
     * thread in the client process to block until you continue execution!
     * So don't wonder if your browser (for example) hangs when you set a
     * breakpoint ;-)... Let's say you can debug a part of the code the client
     * is executing (that's not technically correct)
     *
     * In Windows 2000 debugging the following seems to cause problems.
     */
    public class DemoInterface : MarshalByRefObject
    {
        public void ReportError(Int32 InClientPID,Exception e)
        {
            MessageBox.Show(e.ToString(), "A client process (" + InClientPID + ") has reported an error...", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }
        public void Ei()
        {
            MessageBox.Show("test");

        }
        public bool Ping(Int32 InClientPID)
        {
            return true;
        }

        public void OnCreateFile(Int32 InClientPID,String[] data)
        {
            //something happened
            MessageBox.Show("something happened");
           
        }

        public void CreateD(string demo)
        {
            MessageBox.Show(demo);
        }

                   
    }

}

program.cs 

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using EasyHook;

namespace ProcessMonitor
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                Config.Register(
                    "A simple ProcessMonitor based on EasyHook!",
                    "ProcMonInject.dll",
                    "ProcessMonitor.exe");
            }
            catch (ApplicationException)
            {
                MessageBox.Show("This is an administrative task!", "Permission denied...", MessageBoxButtons.OK);

                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form2());
        }
    }
}

Form2.cs 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security.Principal;
using System.Security;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Threading;
using EasyHook;

namespace ProcessMonitor
{
    public partial class Form2 : Form
    {

        private List<Process> LastProcesses = new List<Process>();
        static internal List<Int32> HookedProcesses = new List<Int32>();
        private String ChannelName = null;
        private IpcServerChannel DemoServer;

        /*
         * Please note that we have obtained this information with system privileges.
         * So if you get client requests with a process ID don't try to open the process
         * as this will fail in some cases. Just search the ID in the following list and
         * extract information that is already there...
         *
         * Of course you can change the way this list is implemented and the information
         * it contains but you should keep the code semantic.
         */
        //internal static List<ProcessInfo> ProcessList = new List<ProcessInfo>();
        private static List<Int32> ActivePIDList = new List<Int32>();
        //private static System.Threading.Timer ProcessTimer = null;

        /*
         * In general you shouldn't access the GUI directly from other threads,
         * so we are using an asynchronous approach!
         */
        static internal Queue<MonitorEntry> MonitorQueue = new Queue<MonitorEntry>();
        static internal Boolean IsMonitoring = true;

        public Form2()
        {
            InitializeComponent();

            DemoServer = RemoteHooking.IpcCreateServer<DemoInterface>(ref ChannelName,WellKnownObjectMode.Singleton);

        }

        private void button1_Click(object sender, EventArgs e)
        {

            try
            {

                //the PID im using is my Spool.exe file PID
                HookedProcesses.Add(56660); // this will ensure that Ping() returns true...

                RemoteHooking.Inject(
                    56660,
                    "ProcMonInject.dll", // 32-bit version (the same because AnyCPU)
                    "ProcMonInject.dll", // 64-bit version (the same because AnyCPU)
                    // the optional parameter list...
                    ChannelName);
            }
            catch (Exception Msg)
            {
                HookedProcesses.Remove(56660);
               
                MessageBox.Show(Msg.Message, "An error has occurred...", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

        }
    }
}

Mar 17, 2010 at 12:00 PM

Hi please can someone check my code if it is wrong or what but please can some body let me know i have send how many request now and yet no answer not even we can t help etc

thanks