EasyHook, .NET Remoting sharing interface between both client and server?

可紊 提交于 2019-12-03 14:07:08

问题


How can both the IPC client and IPC server call the shared remoting interface (the class inheriting MarshalByRefObject) to communicate, without having to put the interface class inside in the injecting application? For example, if I put the interface class in the injected library project that gets injected into my target process, my injecting application cannot reference that interface.

Edit: I have answered the question below.


回答1:


As of EasyHook Commit 66751 (tied to EasyHook 2.7 alpha), it doesn't seem possible to get the instance of the remoting interface in both the client (that process that initiated injection of your DLL) and the server (the injected process running your injected DLL).

What do I mean?

Well, in the FileMon and ProcessMonitor examples, notice how the shared remoting interfaces (FileMonInterface, embedded in Program.cs, for Filemon, and DemoInterface, in its own file, for ProcessMonitor) are placed in the injecting assembly. FileMonInterface is in the FileMon project. DemoInterface is in the ProcessMonitor project.

Why not the other round? Why not put FileMonInterface in the project FileMonInject, and put DemoInterface in ProcMonInject? Because then the interfaces will no longer be accessible to the calling applications (FileMon and ProcessMonitor).

The reason is because EasyHook internally uses:

RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(TRemoteObject),
                ChannelName,
                InObjectMode);

This remoting call allows clients to call your (server) interface, but the server itself (you, the application) cannot call it.

The Solution

Instead, use:

// Get the instance by simply calling `new RemotingInterface()` beforehand somewhere
RemotingServices.Marshal(instanceOfYourRemotingInterfaceHere, ChannelName);

What I did was add an overload to EasyHook's RemoteHook.IpcCreateServer() to accept my new "way" of doing .NET remoting.

It's ugly, but it works:

The Code

Replace the entire IpcCreateServer method (from brace to brace) with the following code. There are two methods shown here. One is the more detailed overload. The second is the "original" method calling our overload.

public static IpcServerChannel IpcCreateServer<TRemoteObject>(
        ref String RefChannelName,
        WellKnownObjectMode InObjectMode,
        TRemoteObject ipcInterface, String ipcUri, bool useNewMethod,
        params WellKnownSidType[] InAllowedClientSIDs) where TRemoteObject : MarshalByRefObject
    {
        String ChannelName = RefChannelName ?? GenerateName();

        ///////////////////////////////////////////////////////////////////
        // create security descriptor for IpcChannel...
        System.Collections.IDictionary Properties = new System.Collections.Hashtable();

        Properties["name"] = ChannelName;
        Properties["portName"] = ChannelName;

        DiscretionaryAcl DACL = new DiscretionaryAcl(false, false, 1);

        if (InAllowedClientSIDs.Length == 0)
        {
            if (RefChannelName != null)
                throw new System.Security.HostProtectionException("If no random channel name is being used, you shall specify all allowed SIDs.");

            // allow access from all users... Channel is protected by random path name!
            DACL.AddAccess(
                AccessControlType.Allow,
                new SecurityIdentifier(
                    WellKnownSidType.WorldSid,
                    null),
                -1,
                InheritanceFlags.None,
                PropagationFlags.None);
        }
        else
        {
            for (int i = 0; i < InAllowedClientSIDs.Length; i++)
            {
                DACL.AddAccess(
                    AccessControlType.Allow,
                    new SecurityIdentifier(
                        InAllowedClientSIDs[i],
                        null),
                    -1,
                    InheritanceFlags.None,
                    PropagationFlags.None);
            }
        }

        CommonSecurityDescriptor SecDescr = new CommonSecurityDescriptor(false, false,
            ControlFlags.GroupDefaulted |
            ControlFlags.OwnerDefaulted |
            ControlFlags.DiscretionaryAclPresent,
            null, null, null,
            DACL);

        //////////////////////////////////////////////////////////
        // create IpcChannel...
        BinaryServerFormatterSinkProvider BinaryProv = new BinaryServerFormatterSinkProvider();
        BinaryProv.TypeFilterLevel = TypeFilterLevel.Full;

        IpcServerChannel Result = new IpcServerChannel(Properties, BinaryProv, SecDescr);

        if (!useNewMethod)
        {
            ChannelServices.RegisterChannel(Result, false);

            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(TRemoteObject),
                ChannelName,
                InObjectMode);
        }
        else
        {
            ChannelServices.RegisterChannel(Result, false);

            ObjRef refGreeter = RemotingServices.Marshal(ipcInterface, ipcUri);
        }

        RefChannelName = ChannelName;

        return Result;
    }

    /// <summary>
    /// Creates a globally reachable, managed IPC-Port.
    /// </summary>
    /// <remarks>
    /// Because it is something tricky to get a port working for any constellation of
    /// target processes, I decided to write a proper wrapper method. Just keep the returned
    /// <see cref="IpcChannel"/> alive, by adding it to a global list or static variable,
    /// as long as you want to have the IPC port open.
    /// </remarks>
    /// <typeparam name="TRemoteObject">
    /// A class derived from <see cref="MarshalByRefObject"/> which provides the
    /// method implementations this server should expose.
    /// </typeparam>
    /// <param name="InObjectMode">
    /// <see cref="WellKnownObjectMode.SingleCall"/> if you want to handle each call in an new
    /// object instance, <see cref="WellKnownObjectMode.Singleton"/> otherwise. The latter will implicitly
    /// allow you to use "static" remote variables.
    /// </param>
    /// <param name="RefChannelName">
    /// Either <c>null</c> to let the method generate a random channel name to be passed to 
    /// <see cref="IpcConnectClient{TRemoteObject}"/> or a predefined one. If you pass a value unequal to 
    /// <c>null</c>, you shall also specify all SIDs that are allowed to connect to your channel!
    /// </param>
    /// <param name="InAllowedClientSIDs">
    /// If no SID is specified, all authenticated users will be allowed to access the server
    /// channel by default. You must specify an SID if <paramref name="RefChannelName"/> is unequal to <c>null</c>.
    /// </param>
    /// <returns>
    /// An <see cref="IpcChannel"/> that shall be keept alive until the server is not needed anymore.
    /// </returns>
    /// <exception cref="System.Security.HostProtectionException">
    /// If a predefined channel name is being used, you are required to specify a list of well known SIDs
    /// which are allowed to access the newly created server.
    /// </exception>
    /// <exception cref="RemotingException">
    /// The given channel name is already in use.
    /// </exception>
    public static IpcServerChannel IpcCreateServer<TRemoteObject>(
        ref String RefChannelName,
        WellKnownObjectMode InObjectMode,
        params WellKnownSidType[] InAllowedClientSIDs) where TRemoteObject : MarshalByRefObject
    {
        return IpcCreateServer<TRemoteObject>(ref RefChannelName, InObjectMode, null, null, false, InAllowedClientSIDs);
    }

That's it. That's all you need to change. You don't have to change IpcCreateClient().

Using the Code

Here's how you would use the new overloaded method:

Say you have

public class IpcInterface : MarshalByRefObject { /* ... */ }

as your shared remoting interface.

Create a new instance of it, and store its reference. You'll be using this to communicate with your client.

var myIpcInterface = new IpcInterface(); // Keep this reference to communicate!

Here's how you would have created that remoting channel before:

        ipcServer = RemoteHooking.IpcCreateServer<IpcInterface>(ref IpcChannelName, WellKnownObjectMode.Singleton, WellKnownSidType.WorldSid);

Here's how you would create that remoting channel now:

        ipcServer = RemoteHooking.IpcCreateServer<IpcInterface>(ref IpcChannelName, WellKnownObjectMode.Singleton, myIpcInterface, IpcChannelName, true, WellKnownSidType.WorldSid);

Don't forget to...

I got this solution from this StackOverflow post. Please be sure to do as he says and override InitializeLifetimeService to return null:

public override object InitializeLifetimeService()
{
    // Live "forever"
    return null;
}

I think this is supposed to keep the client from losing the remoting interface.

Uses

Now, instead of being forced to place your remoting interface file in the same directory as your injecting project, you can create a library specifically for your interface file.

This solution may have been common knowledge to those having had experience with .NET remoting, but I know nothing about it (might have used the word interface wrong in this post).



来源:https://stackoverflow.com/questions/13354882/easyhook-net-remoting-sharing-interface-between-both-client-and-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!