Slashdot Mirror


Hijacking .NET

Matt Solnit writes "What can I say - Dan Appleman never fails to please. In this e-book, he takes a look at 'hijacking' .NET by accessing private members in .NET classes. Private members are, in essence, pieces of code that you don't want other programmers to access. You use them to support your own code, and you make public the pieces that you want to make available to other developers. Typically, a language ensures that a member marked as private is hidden from anyone who doesn't have your source code, but Appleman shows how in .NET it's not so." Read on for more of Matt's review of this guide to tricking private members to do your bidding. Hijacking .NET - Volume 1 author Dan Appleman pages 46 publisher Dan Appleman rating 10 reviewer Matt Solnit ISBN (N/A) summary An eye-opening look at how you can use undocumented and private features from the .NET framework.

In the .NET Framework, it's possible to access a private member of any class -- your own, another developer's, or even the classes in the .NET Framework itself! Appleman demonstrates this with a great example that uses private members to get the list of groups that the current user is a member of -- in a single line of code -- by accessing a private member that is not exposed by the .NET Framework.

Appleman also explains the tradeoffs of using this technique. The code you're using is not documented, and it's not guaranteed to be present in future versions. He describes how to deal with these problems, and how to make the most of the technique while remaining relatively safe.

Once the basic technique is explained, Appleman takes you into how to find out what private members are available, and how to call them. He shows how to use the object browser available in Visual Studio .NET and the Microsoft IL Disassembler, freely available in the Framework SDK, to discover the private members in a class and determine how to call them correctly.

The example is great -- Dan shows you how he used "hijacking" with a collection of private members to develop a FileAccessControlList class that can be used to manipulate ACL's on Windows files. This is a piece of functionality that is not included with the .NET Framework, but developers have a need for all the time. To write the code from scratch would take days, including translating Windows API declarations to C# or another .NET language and poring over MSDN documentation. As it turns out, all the pieces are in the Framework -- they're just not public. Appleman accomplishes the task in under 200 lines of code, all of which is included with the e-book. As a bonus, you get a great introduction to how Windows security works, and how the example could be extended to other ACL-controlled things like Registry keys.

The fact that private in .NET isn't really private is something that isn't well known, and even if you're not interested in security, this e-book is worth a read just to get some insight into what you can do with the .NET framework, and what other people might someday try to do to your code.

As far as the author's writing style, I will say that Dan has a great knack for intuiting what needs to be explained and what doesn't. His laid-back approach makes everything seem fun -- this is a book you could read on a Saturday afternoon in a hammock.

This e-book is not for beginning .NET programmers, but should be easy for intermediate developers to understand. The whole text weighs in at just under 50 pages, and is well worth the cost of $9.95. Sample code is provided in both C# and VB .NET.

This e-book can be purchased and downloaded immediately from amazon.com or through the author's web site.

33 of 514 comments (clear)

  1. C++ by Anonymous Coward · · Score: 5, Informative

    This is nothing new - you can do the same thing in C++. It's easy to access private variables or functions by manipulating a pointer.

    So what's the big deal?

  2. Duh. Its called reflection by Asmodeus · · Score: 5, Informative

    ..and is a very old technique.
    Java, Modula2, Lisp and smalltalk all allow
    this.
    RTFM

    1. Re:Duh. Its called reflection by Ageless · · Score: 2, Informative

      I can't speak for anything but Java, but in Java reflection does not allow you to access private members. That's part of the security of Java.

    2. Re:Duh. Its called reflection by lurp · · Score: 2, Informative
      Actually, Java does let you access private members through reflection. See java.lang.reflect.AccessibleObject.

      Access can be controlled by a security manager; but the default for a java application is to allow access.

    3. Re:Duh. Its called reflection by egomaniac · · Score: 5, Informative

      I love it when a flat-out wrong post gets modded to 5. You most fucking certainly can access private methods and fields from within Java.

      For instance, to set the private field "x" on a Component:

      import java.awt.*;
      import java.lang.reflect.*;

      public class YouAreWrong {
      public static void main(String[] arg) throws Exception {
      Button youAreWrong = new Button();
      System.out.println("Button.getX() == " + youAreWrong.getX()); // youAreWrong.x = 5; would result in a compile error, as x is a private field
      Field x = Component.class.getDeclaredField("x");
      x.setAccessible(true);
      x.set(youAreWrong, new Integer(5));
      System.out.println("Button.getX() == " + youAreWrong.getX());
      }
      }

      Go try it and see what happens.

      --
      ZFS: because love is never having to say fsck
  3. More version incompatible program by plcurechax · · Score: 3, Informative

    I suspect the most common use of this is not attempts at bypassing poorly thought out security. I hope MSFT programmers are not hiding passwords in .NET classes. The most common usage will be "tweaks" and such that will be dependent on a specific .NET framwork version/release.

    By delving into the private classes, you might be able to get speedups on a specific (or common) platform, say MSFT's .NET framework version 1.0 for Windows 2000/XP, but come next release, these tweaks are likely to break. That's why private members of classes are private, because they are not part of the documented API.

  4. How it's done by Jabes · · Score: 5, Informative

    This will be done using reflection. It's pretty easy to instantiate private objects, and call private members using the reflection functions in .net (System.Reflection) I'll post an example if anyone is that interested, but there are quite a few examples kicking around on the net.

    However, the security model of .net only allows you to make these reflection calls if your application is running in "full trust". There is a very finely grained security model in .net, and applications can be trusted to make certain calls depending on the location they're running from (eg over the internet from an http:// address, on a network share, on the local disk); on whether the application is signed; by the vendor of the application; or even down to just a single program.

    At the moment .net programmers mostly assume they're running in full trust mode (which if its on the local hard disk, they are). But this is a poor assumption which will fall by the wayside in the future as .net takes off.

    To do other "unsafe" things (like use pointers, or interop into unmanaged code, generate dynamic code) you also need high permission levels.

    Now let's compare this with the unmanaged world. I can load up a DLL and call what the hell I want. I can even jump right into the middle of a function if I want. I can over-run buffers and blow my stack. I can do what the hell I want within my virtual address space. I can send messages to other applications and make them do screwy things. And I'm probably running as a local administrator so I can do things to other processes too.

    So is this a security concern? I don't think so.

    I must admit, I haven't read the book - and I'm not going to shell out $10 to find out if I'm right.

  5. Re:Is this a C# or a .NET problem? by Anonymous Coward · · Score: 5, Informative

    This is no security hole. If you're able to run code on the target machine then you can do pretty much anything you want (or can) already.

    Just because you can find out some "inner state" of an object doesn't mean that you're God now.

    Oh, and the same "exploit" can be done with C++ - does this have a negative affect on security? No.

    Encapsulation was never meant to be a security feature.

  6. Re:Private methods and by Ageless · · Score: 2, Informative

    This is not true in Java. No matter what the compiler spits out it is verified by the VM before it is executed and if the bytecode is trying to access something it is not allowed to the VM will cause that code to fail. This is part of the security that Sun touts about Java.

  7. Re:So .Net is like C++? by Anonymous Coward · · Score: 1, Informative

    In Java the check is usually done only at compile time. Starting the VM with "-Xfuture" as an argument will force the checks to happen at runtime as well.

  8. Security by cooldev · · Score: 5, Informative

    Private members aren't for hiding code or data from other malicious programs; if they're being used in that way that's a flaw.

    It's simply a compile-time verification that you're using the object through it's intended public interface instead of relying on the internal implementation. If you disregard it you just end up throwing away a lot of the benefits of OO and you build fragile apps.

    That said, people should be aware of this so they don't mistakenly think that "private string m_password" is a secure way to store data.

    BTW: A long time ago I did this in Java by programmatically altering the bytecode of a .class file from another app.

  9. Stop the anti-MS BS all the damned time by fzammett · · Score: 4, Informative

    This is NOT a security issue... A number of other languages allow this, most notably Java.

    Making a member private is NOT a security mechanism. It is a DESIGN mechanism. The point is to enforce a public interface to a class, not absolutely securing internal data or functions from external callers. Yes, they are similar and in some cases pretty damn close to synonymous, but they are still different goals.

    This isn't a flaw in .NET, unless MS says that in fact they want to doubly use the private mechanism as a security measure. No other language that I'm aware of does this, you could even argue that it would be a plus in .NET's favor.

    If you want to say this design pattern is stupid, by all means do so. I would tend to agree. But if you want to use this as an opportunity to simply bash MS and .NET, your simply ignorant or just want to toss mud.

    --
    If a pion (n-) collides with a proton in the woods & noone is there to hear it, does lamdba decay into the source pa
    1. Re:Stop the anti-MS BS all the damned time by Get+Behind+the+Mule · · Score: 1, Informative
      This is NOT a security issue... A number of other languages allow this, most notably Java.


      Making a member private is NOT a security mechanism. It is a DESIGN mechanism.



      Uh, if you put an intemperate heading over your post, perhaps it would be better if you refrain from putting nonsense into its body.

      Java certainly does not allow access to private class members from client code. That will cause a compiler error, end of story. The only way it could conceivably be done is through object serialization and deserialization, since the serialized form must respect the class definition, and deserialization must restore objects to their original state. The default serialization code makes it possible, but cautious programmers can prevent serialization from exposing private members by writing their own readObject() or readResolve() methods. (See chapter 10 of Joshua Bloch's Effective Java.)

      And yes, exposing private members certainly is a security issue, because it gives client code the ability to manipulate the implementation of a class, which is meant to be encapsulated. The code can be made to do things that the programmer did not intend, and that is one of the things that makes software insecure.
  10. Re:So .Net is like C++? by Erv+Walter · · Score: 5, Informative

    This .NET behavior is not a security hole.

    The .NET CLR does runtime checks to verify that code is not doing things it's not allowed to do (aka, code can't leave the "sandbox"). Accessing private methods using this technique does not circumvent these checks--the CLR will detect and prevent *inappropriate* accesses.

    The key point is that .NET applications can be running in many different security environments. Installed applications running off your hard drive essentially have no sandbox. Applications running from the network or within a browser have a much more restrictive sandbox and these "hacking .NET" techniques would be caught (assuming the private code being called is inapproriate for the sandbox).

    --
    -- Erv Walter
  11. Re:Is this a C# or a .NET problem? by Erv+Walter · · Score: 5, Informative

    Keep in mind that there is not always a sandbox for .NET applications. The security policys being enforced are configurable, but by default, installed applications running off your hard drive essentially have no sandbox. On the other hand, applications running from the network or within a browser have a much more restrictive sandbox and these "hacking .NET" techniques would be caught (assuming the private code being called is inapproriate for the sandbox).

    The .NET CLR does runtime checks to verify that code is not doing things it's not allowed to do (aka, code can't leave the "sandbox"). Accessing private methods using this technique does not circumvent these checks--the CLR will detect and prevent *inappropriate* accesses.

    --
    -- Erv Walter
  12. Not a security issue by Jeffrey+Baker · · Score: 3, Informative
    People seem to be making this into a big security issue, but I don't see it that way at all. Private declarations shouldn't be used to provide security. You can assume that if you put a piece of code or data into a computer, other programs may be able to access the storage thereof. No big surprise there. This is true of introspection techniques, self-modifying code, and related styles of programming.

    The declaration of something as private, or not exported, or static, or the analog provided by your favorite programming language is a tool for the programmer, not the computer. It tells the programmer that this interface or piece of data is not be used by anyone but the author. It means that the interface or data could change at any time, and any use of it is a hack in the classic sense. It will probably work, in appearance or in actuality, but it will break unpredictably.

    Private declarations may be enforced with varying vigor by compilers or runtimes, but usually there is a way around such enforcements. At the extreme, you can usually just directly access the memory in question, if the kernel allows that (or even if it doesn't, in the case of a super-user).

  13. Re:Is this a C# or a .NET problem? by 1000StonedMonkeys · · Score: 5, Informative

    Not quite true. .NET has a fine-grained security mechanism that allows code to execute with specific priviledges. It can do that because .NET, like Java, is run by a VM. What the original poster is getting at is that you might be able to bypass these access controls if you're able to access the private data members of .NET system classes.

  14. Re:Posted on BugTraq by Zeinfeld · · Score: 4, Informative
    Isn't this a security bug, you think that you've hidden some code, but infact it isn't.

    No, not really, the private keyword is not meant to be a security mechanism. If you want to secure the data from program access you have to do it at the Kernel level.

    You can view this info in the debugger if you have the source for the class.

    The reason for making a method private is that the programmer does not undertake to preserve the API contract in future releases. So basically what this guy is doing is no different from those early MSDOS programs that bypassed the BIOS calling interface to call code directly. It was fast, you avoided the overhead of the context switch. However it also meant that the code was likely to fail on the next release of the PC.

    --
    Looking for an Information Security student project suggestion?
    Try http://dotcrimeManifesto.com/
  15. It is all by design... by CrazyJ020 · · Score: 4, Informative
    Access modifiers (public, private, protected, internal, etc) are not designed for security! Code access security is intended for this purpose. With that said, you can still use code access security to prevent access to private members. Access to these members can be only done with reflection classes. The ReflectionPermission can be utilized to prevent code from accessing private members. From the document:
    CAUTION Because ReflectionPermission can provide access to private class members and metadata, it is recommended that ReflectionPermission not be granted to Internet code.
  16. Re:Is this a C# or a .NET problem? by John+Miles · · Score: 4, Informative

    In C++ the compiler will not let you access private methods or variables

    Ridiculous.

    class hidden
    {
    private:
    int frotz;
    int ozmoo;
    };

    class hack_o_matic
    {
    public:
    int frotz;
    int ozmoo;
    };

    int main(void)
    {
    hidden H;
    hack_o_matic *V = (hack_o_matic *) (ampersand) H;
    printf("Hidden frotz member = %d",V->frotz);
    }

    The poster above who pointed out that both the review and its subject are goofy is correct. Data-hiding is an OOP convention, not a security feature.

    C++ is a particularly good example (for values of 'good' that approximate 'horribly broken'), because the only way you can expose a class's public functionality is through a declaration of the entire class that includes all of its private members, which can subsequently be accessed through pointer hacks like the above. If you want to hide data for security purposes, as opposed to hiding data for design purposes, you have no choice but to use wrappers.

    --
    Dahlmann tightly grips the knife, which he may have no idea how to use, and steps out into the plain.
  17. C++ will let you do anything! by BaldBass · · Score: 5, Informative
    "In C++ the compiler will not let you access private methods or variables."

    No and no. Example:
    producer.h:

    class ThoughtToBeSecure {
    private:
    void highlyGuardedMethod();
    int highlyGuardedVariable;
    };

    hacked_producer.h:

    class ThoughtToBeSecure {
    public:
    inline void protectionBypass() {
    highlyGuardedMethod();
    }
    inline void hackTheVariableToo(int value) {
    highlyGuardedVariable= value;
    }

    private:
    void highlyGuardedMethod();
    int highlyGuardedVariable;
    };

    malicous_user.cpp:

    #include "hacked_producer.h"

    void sandboxHaHa(ThoughtToBeSecure x) {
    x.protectionBypass();
    x.hackTheVariableToo(0);
    }
    Looks like you need to brush up your C++ knowlege.
  18. Private members are not a security feature. by blair1q · · Score: 2, Informative

    OO coders have known this for a couple of decades, I think. (I forget; when was the "private member" invented?)

    Private members are a reliability measure, preventing subclasses from accessing members in dangerous ways, but certainly are not a security feature, because it's always possible to troll the object code.

    Oh, and BTW: The Internet is not secure, either. "Internet Security" is a security blanket, not a security door.

  19. Re:Is this a C# or a .NET problem? by jalilv · · Score: 4, Informative

    It is same in .NET too. .NET just provides classes for Reflection and Run-Time Type Information which will provide all the information about an object in memory. This information is available as a bunch of objects like MemberInfo, MethodInfo, PropertyInfo, ParameterInfo, FieldInfo etc. It is possible to change the values of private fields or invoke methods using these objects. It is in no way a security problem and relating it to sandbox is totally offtopic too. The runtime just provides the information, what you do with the information is upto you. As pointed out by others, it is possible to access private members in C++ too using some pointer artihmetic. Oh btw, it is possible to override private virtual method of a base class in a derived class in C++. Feeling surprized, aren't ya ?

    - Jalil Vaidya

  20. Flamebait alert by The+Bungi · · Score: 4, Informative
    OK, so let's review this "review":
    • Appleman's claim to fame are his efforts to bring advanced techniques to Visual Basic developers.
    • His approach was basically this: OK, this is how you dereference a pointer in VB. Get it? But wait - that's unsafe!. So click on this link to buy my SuperDuper Pointer Dereferencing Library for VB, priced to go at $99.
    • Appleman's "samples" were always flawed and biased, designed specifically to sell his ActiveX libraries and controls. He lost all credibility right after he published an essay on how to do multithreading from VB5, an essay that was also flawed in its premises and was also designed to sell his multithreading library. This "essay" was immediately slammed by the very people who wrote VB, including folks like Matt Curland.
    • So now this guy (who used to work for Desaware - surprised?) does a "review" of Appleman's essay on how to "hijack" .NET.
    • What Mr. Dan "The Wiz" Appleman is doing here is nothing more insecure than calling class members directly using a vtable in a C++ application. Member visibility in C# (and in any other language) is a OO feature, not a security one. I'm not going into a discussion of .NET app domain security - I'm sure anyone who is interested can head on over to MSDN and look by themselves. Suffice it to say that where it matters, you can't do this. And quite a few other things.
    • This "evil technique" can also be applied to C++ and it can also be applied to Java. Wow!
    • The only reason Slashdot posted this article is to reinforce the perception that .NET sucks and is "insecure".
    Witness the numerous clueless post on how "oh, I'm not surprised .NET is insecure" and "M$ is teh sux" and a few insightful ones debunking the very premise of this flamebait "story". A good number of "Hah! Java doesn't allow that" posts were duly bitchslapped below. But that doesn't matter in the end, because the premise itself is flawed. "Oh, look, I can access private members, I'm so 1337". I expected nothing more from Appleman, and I expected nothing more from the Slashdot "editors", who'll post anything that remotely looks like a problem with a Microsoft product. XML in Office anyone?

    Coming soon - a story entitled "m$ .nyet 'sploid", by "h^xx0r". Read more (40 characters in body).

  21. Re:By design? by daytrip00 · · Score: 2, Informative

    In fact, Microsoft ships a lite obfuscator with VS.NET 2003. I don't think most other IDEs do. You can buy better ones too if you really want to protect your source code.

  22. Private Perl [was Re:Conclusion] by fiji · · Score: 3, Informative

    Well... you can jump through hoops in Perl to make something _really_ private if you want:

    {
    my $private_val = 4;
    my $private_sub =
    sub { return "whee" };

    sub public_accessor {
    print %$private_sub . $private_val;
    }
    }

    As long as you declare your private subs as code references and use my, then no one can call them from outside that scope. Since Perl doesn't allow you to do pointer arithmetic the values are not accessible (unlike C++) (well, unless you have so craaazy lib loaded, then people can circumvent. But hell, you can always read the raw memory too).

    -ben

  23. Re:Conclusion by iang · · Score: 2, Informative

    This is of course also true in Java - there are a variety of ways you can get to private members there too. And of course in C++ you can always get at whatever you like by using pointers. .NET does at least improve upon traditional C++ in that your code can only get at private members if the security policy permits it. Code downloaded from the Internet for example (e.g. a .NET component running in a web browser like a Java applet would) is not, able to access private members in this way.

    --
    Ian Griffiths
  24. Re:Conclusion by JanneM · · Score: 2, Informative

    Yep. But (as Srinivasan writes in Advanced Perl Programming), making a closure like that will generate a new piece of code for each instance. Not a problem if the code snippets are reasonably small and the number of instances aren't huge, but something to bear in mind anyway.

    I haven't actually read Conway - maybe I should.

    --
    Trust the Computer. The Computer is your friend.
  25. Depends on the current settings by gburgyan · · Score: 3, Informative
    RTFM.

    Check the documentation on the ReflectionPermissionFlag Enumeration to see what's going on. By default, for code that you're running on your own machine, you can do anything that you want. You can modify the settings with the framework configuration applet, or with some command line programs.

    The end result is, you can turn this feature off.

    I'm tired of /. being used to sell sh!t in posts.

  26. Re:Even easier... by Anonymous Coward · · Score: 1, Informative

    Or just do this ...

    #define private public
    #define protected public
    #define class struct

    Struct and classes are essentially the same in C++; however, structs have public visibility by default.

  27. Re:Classes by arkanes · · Score: 2, Informative
    You ensure that you won't access it by ACCIDENT. Private is to help you write clean code, not to protect your code from someone trying to break it.

    Another place it's use is in design by contract (the Digital Mars C++ compiler has it), where you make "promises" about the state of an object, can you can only break that promise within a private member. Note, though, that like the private keyword this is a compiler enforced directive on the developer, NOT a security model! It's to help you write bug-free code, not to keep someone from accessing your private data.

    A private member indicates that it's used to provide internal functionality to a class - that it shouldn't be used from outside that class. Private members are subject to change, because they're an implementation detail.

  28. No Security Hole - Just a Hideous Idea by Grunk · · Score: 2, Informative
    First, let me say I have not read the ebook - just the abstract. I'm assuming it uses either Reflection or some technique that uses unverifiable code (which essentially means it can own your machine if you allow it to run).

    As many people have already pointed out, this is not a security hole in the .NET Framework. Member visibility is a statement about what you intend to support and document, but is not strictly a statement of security. Additionally, the .NET Framework security model prohibits code like this from running, depending on security policy and where the code comes from.

    That being said, let me show how this can be done, and how using code access security, you can prevent this. Note that the default policies for code from the Internet and Intranet zones will not allow this code to run.

    Note that if you want to prevent member access, the .NET Framework does provide a way to do this, unlike other runtime environments or languages like Java or C++. Look at the strong name identity permission in the MSDN documentation or a great security book for more details.

    As many have already pointed out, calling someone else's internal member is an excellent way of making your application fragile and adding a source of potentially incorrect behavior. There's no guarantee that someone else's private members will be there or work the same way in a future version (including a service pack) - that's why they're private.

    The author's point of using P/Invoke declarations from the .NET Framework is also a very bad one, since they may change with no notice. For instance, any P/Invoke method that uses a handle may have accidentally used an Int32 for the handle type in V1. In V1.1, it might use a IntPtr, while in V2.0 it will likely use a subclass of SafeHandle, a new handle wrapper that doesn't exist in released versions.

    About the only good reason to use Reflection to call private members is for hiding details of a Reflection-based set of functionality where the details of a particular implementation aren't interesting to users. An example would be TypeConverters. Here there's a general design pattern and you may write a TypeConverter for your type, yet you could mark it private if it is really not worth seeing in an object browser or Intellisense. Using Reflection, an instance of this class could be created. However, this isn't a generally recomended technique.

    With this being said, here's an example of how to use Reflection to call private members, and shows that the .NET Framework does indeed do a security check here. This app should run correctly if you run it locally if you haven't modified your machine's security policy, but if it is run over a network share, it will fail.

    using System;
    using System.Reflection;
    using System.Security.Permissions;
    using System.Security;

    public sealed class MyPublicClass
    {
    private static int PrivateFoo()
    {
    return 5;
    }
    }

    public sealed class CallPrivateMemberTest
    {
    private static void CallPrivateMember()
    {
    // Remember that calling private members is a good way of building
    // an incredibly brittle application. This is a hideously bad idea,
    // outside of some well-constrained scenarios. And of course, you
    // can use strong name identity permission to prevent people from
    // calling private methods like this.
    Type type = typeof(MyPublicClass);
    MethodInfo mi = type.GetMethod("PrivateFoo", BindingFlags.Static | BindingFlags.NonPublic);
    Object retVal = mi.Invoke(null, BindingFlags.Static | BindingFlags.NonPublic, null, null, null);
    Console.WriteLine("Called private method. It returned: {0} [{1}

  29. Re:Conclusion by ProfKyne · · Score: 2, Informative

    So what is the target demographic, mechanics? Albino carpet cleaners? Of course it's Perl and C programmers.

    Give me a break. MS isn't going to make much money coming up with the next Perl or C. Perl is used for two very good reasons: devotion of the user base, and the CPAN. MS couldn't replicate either of those under any circumstances, and there isn't much money to be made in trying. C, on the other hand, is primarily used for writing Unix software. (Note that I did not say C++.) Not much of a market for Microsoft either.

    .NET is targetting the Java market, pure and simple.

    --
    "First you gotta do the truffle shuffle."