Использование EasyHook не распознается компилятором c # - PullRequest
0 голосов
/ 31 октября 2019

Я использую Easyhook для своего проекта, чтобы подключить процесс на моем компьютере. Прямо сейчас я экспериментирую с этим и пытаюсь реализовать пример FileMon, который отображается здесь .

В настоящее время я пытаюсь создать FileMonInject.dll, но когда я пытаюсь скомпилировать его черезконсоль разработчика c #, но когда я пытаюсь скомпилировать, она показывает ошибку:

ошибка CS0246: не удалось найти тип или имя пространства имен 'EasyHook' (вы пропустили директиву using илиссылка на сборку?)

Я включил ссылку на Easyhook в оба файла (FileMon и FileMonInject разделены) и синтаксических ошибок нет. Я попытался очистить, восстановить, выбрав различные файлы EasyHook.dll, которые я нашел в папке проекта. Я даже пытался изменить .Net Framework с 3.5 Client Profile на 4, но ничего не работает.

Вот мой код:

using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Text;
using EasyHook;
using System.Threading;
using System.Runtime.InteropServices;

namespace FileMon
{
    public class FileMonInterface : MarshalByRefObject
    {
        public void IsInstalled(Int32 InClientPID)
        {
            Console.WriteLine("FileMon has been installed in target {0}.\r\n", InClientPID);
        }

        public void OnCreateFile(Int32 InClientPID, String[] InFileNames)
        {
            for (int i = 0; i < InFileNames.Length; i++)
            {
                Console.WriteLine(InFileNames[i]);
            }
        }

        public void ReportException(Exception InInfo)
        {
            Console.WriteLine("The target process has reported" +
                              " an error:\r\n" + InInfo.ToString());
        }

        public void Ping()
        {
        }
    }

    class Program
    {
        static String ChannelName = null;

        static void Main(string[] args)
        {
                 Config.Register(
                        "A FileMon like demo application.",
                        "FileMon.exe",
                        "FileMonInject.dll");

                RemoteHooking.IpcCreateServer<FileMonInterface>(
                     ref ChannelName, WellKnownObjectMode.SingleCall);

                Console.WriteLine("before inject");
            try
            {
                RemoteHooking.Inject(
                    Int32.Parse("12644"), // Int32.Parse(args[0]),
                    @"C:\Users\u101040.DESHALIT\source\repos\FileMon\FileMon\NetFX4.0\FileMonInject.dll",
                    @"C:\Users\u101040.DESHALIT\source\repos\FileMon\FileMon\NetFX4.0\FileMonInject.dll",
                    ChannelName);

                Console.WriteLine("after inject");

                Console.ReadLine();
            }
            catch (Exception ExtInfo)
            {
                Console.WriteLine("There was an error while connecting " +
                                  "to target:\r\n{0}", ExtInfo.ToString());
                Console.ReadLine();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using EasyHook;

namespace FileMonInject
{
    public class FileMonInterface : MarshalByRefObject
    {
        public void IsInstalled(Int32 InClientPID)
        {
            Console.WriteLine("FileMon has been installed in target {0}.\r\n", InClientPID);
        }

        public void OnCreateFile(Int32 InClientPID, String[] InFileNames)
        {
            for (int i = 0; i < InFileNames.Length; i++)
            {
                Console.WriteLine(InFileNames[i]);
            }
        }

        public void ReportException(Exception InInfo)
        {
            Console.WriteLine("The target process has reported" +
                              " an error:\r\n" + InInfo.ToString());
        }

        public void Ping()
        {
        }
    }

    public class Main : EasyHook.IEntryPoint
    {
        FileMonInterface Interface;
        LocalHook CreateFileHook;
        Stack<String> Queue = new Stack<String>();

        public Main(
            RemoteHooking.IContext InContext,
            String InChannelName)
        {
            // connect to host...

            Interface =
              RemoteHooking.IpcConnectClient<FileMonInterface>(InChannelName);
        }

        public void Run(
            RemoteHooking.IContext InContext,
            String InChannelName)
        {
            // install hook...
            try
            {
                CreateFileHook = LocalHook.Create(
                    LocalHook.GetProcAddress("kernel32.dll", "CreateFileW"),
                    new DCreateFile(CreateFile_Hooked),
                    this);

                CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });
                Console.WriteLine("in 1");
            }
            catch (Exception ExtInfo)
            {
                Interface.ReportException(ExtInfo);
                Console.WriteLine("in 2");
                return;
            }

            Interface.IsInstalled(RemoteHooking.GetCurrentProcessId());

            // wait for host process termination...
            try
            {
                while (true)
                {
                    Thread.Sleep(500);

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

                        lock (Queue)
                        {
                            Package = Queue.ToArray();

                            Queue.Clear();
                        }

                        Interface.OnCreateFile(RemoteHooking.GetCurrentProcessId(), Package);
                    }
                    else
                        Interface.Ping();
                }
            }
            catch
            {
                // NET Remoting will raise an exception if host is unreachable
                Console.WriteLine("in 4");
            }
        }

        [UnmanagedFunctionPointer(CallingConvention.StdCall,
            CharSet = CharSet.Unicode,
            SetLastError = true)]
        delegate IntPtr DCreateFile(
            String InFileName,
            UInt32 InDesiredAccess,
            UInt32 InShareMode,
            IntPtr InSecurityAttributes,
            UInt32 InCreationDisposition,
            UInt32 InFlagsAndAttributes,
            IntPtr InTemplateFile);

        // just use a P-Invoke implementation to get native API access
        // from C# (this step is not necessary for C++.NET)
        [DllImport("kernel32.dll",
            CharSet = CharSet.Unicode,
            SetLastError = true,
            CallingConvention = CallingConvention.StdCall)]
        static extern IntPtr CreateFile(
            String InFileName,
            UInt32 InDesiredAccess,
            UInt32 InShareMode,
            IntPtr InSecurityAttributes,
            UInt32 InCreationDisposition,
            UInt32 InFlagsAndAttributes,
            IntPtr InTemplateFile);

        // this is where we are intercepting all file accesses!
        static IntPtr CreateFile_Hooked(
            String InFileName,
            UInt32 InDesiredAccess,
            UInt32 InShareMode,
            IntPtr InSecurityAttributes,
            UInt32 InCreationDisposition,
            UInt32 InFlagsAndAttributes,
            IntPtr InTemplateFile)
        {
            try
            {
                Main This = (Main)HookRuntimeInfo.Callback;

                lock (This.Queue)
                {
                    This.Queue.Push(InFileName);
                }
                Console.WriteLine("in 5");
            }
            catch
            {
                Console.WriteLine("in 6");
            }

            // call original API...
            return CreateFile(
                InFileName,
                InDesiredAccess,
                InShareMode,
                InSecurityAttributes,
                InCreationDisposition,
                InFlagsAndAttributes,
                InTemplateFile);
        }
    }
}

Есть предложения?

...