Pregunta

Obtuve una aplicación (antigua) que llama a la función Winsocket:

struct hostent* FAR gethostbyname(
  __in  const char *name
);

Actualmente lo importa como WS32_DLL.#52 en su lugar, la llamada de nombre normal.

Mi intención es poder hacer algo como abrir un cuadro de mensajes cuando ocurre una búsqueda de host (que debería estar en la aplicación inicial).

Traté de crear una DLL C ++ con los comentarios de Pragma que apuntan al #52 y poniéndolo en el Dir de la aplicación (incluidos los archivos "Exe.local" y "Exe.Manifest" para tratar de redirigirlo) pero cargó el C: Windows System32 en su lugar.

Después de eso, creé el proyecto AC# que inició el proceso en sí (por lo tanto, obtuve el PID del objeto de proceso), agregando el DLL EasyHook.

Revisé el ejemplo en: http://www.codeproject.com/kb/dll/easyhook64.aspx

Cambiar las llamadas a:

    FileMon.FileMonInterface Interface;
    LocalHook CreateFileHook;
    Stack<String> Queue = new Stack<String>();

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

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

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

            CreateFileHook.ThreadACL.SetExclusiveACL(new Int32[] { 0 });
        }
        catch (Exception ExtInfo)
        {
            Interface.ReportException(ExtInfo);

            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
        }
    }


    [UnmanagedFunctionPointer(CallingConvention.StdCall,
        CharSet = CharSet.Auto,
        SetLastError = true)]
    delegate IntPtr DGetHostByName(
        String name);

    // just use a P-Invoke implementation to get native API access
    // from C# (this step is not necessary for C++.NET)
    [DllImport("ws2_32.dll",
        CharSet = CharSet.Auto,
        SetLastError = true,
        CallingConvention = CallingConvention.StdCall)]
    static extern IntPtr gethostbyname(
        String name);

    // this is where we are intercepting all file accesses!
    static IntPtr GetHostByName_Hooked(
        String name)
    {
        try
        {
            Main This = (Main)HookRuntimeInfo.Callback;
            MessageBox.Show("hi!");


        }
        catch
        {
        }

        // call original API...
        return GetHostByName(
            name);
    }
}

}

(Puede haber hecho que los errores tipográficos lo escribieran aquí, pero el proyecto compilado con éxito @ home).

La cuestión es que no sé lo que necesito hacer los enganches de estos métodos <-> la aplicación en sí.

Quiero decir ... ¿qué izquierdas simplemente enganchar con C# Easyhook (suponiendo que la aplicación sea "foo.exe")? ¿Necesito crear una DLL personalizada para Easyhook? (En ese caso, ¿qué contenido necesito definir por dentro?)

Lo encontré un poco ... "complejo" para un gancho de Helloworld, jeje.

Gracias por adelantado ;)

¿Fue útil?

Solución

Al final, usando el libro "Gray Hack Python" Taugh Me Cómo hacer todo esto con menos líneas, y lo mismo que quería.

Todavía no exe, pero ... eso es todo.

Usando pydbg + ganchos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top