How to prevent remote client from casting transparent proxy to actual object type? RRS feed

  • Question

  • Here's the situation. I have a remotable class that returns an interface:

    class Foo : MarshalByRefObject
        public ISomeInterface GetStuff();


    interface ISomeInterface
        void PublicMethod();

    Obviously, ISomeInterface is implemented by a class:

    class SomeClass : MarshalByRefOBject, ISomeInterest
        public void PublicMethod();
        internal void InternalMethod(); // not from ISomeInterface

    Now, the client code that I do not control does something like this:

    var someInterface = foo.GetStuf();
    var realObject = someInterface as SomeClass;
    if (realObject != null) realObject.InternalMethod();

    This works OK if foo is merely in another AppDomain. But if foo is truly remote, the casting works, but the call to the internal method fails with

    Runtime.Remoting.RemotingException: Permission denied: cannot call non-public or static methods remotely.

    What I want is to prevent client from casting SomeInterface to SomeClass. One way to do it is to wrap SomeClass in a dummy decorator that implements ISomeInterface and nothing else:

    class SomeDecorator : MarshalByRefObject, ISomeInterface
        ISomeInterface _source;
        public SomeDecorator(ISomeInterface source) { _source = source; }

        public void PublicMethod() { _source.PublicMethod(); }

    and then Foo.GetStuff() returns new SomeDecorator(new SomeClass());

    This works, but it seems cumbersome. Is there a way to tell TransparentProxy to stick to ISomeInterface and not allow any casts?

    • Edited by ikriv Friday, December 7, 2012 6:32 AM
    Friday, December 7, 2012 6:31 AM