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.

35 of 514 comments (clear)

  1. Conclusion by borgdows · · Score: 4, Funny

    If you code in a Microsoft programming language, you can't even trust your own code!

    1. Re:Conclusion by JanneM · · Score: 5, Insightful

      I thought so too at first, but I believe it's not really the same thing here. Neither Perl nor C stuff depends on this encapsulation for any security stuff. For instance, Perl has sandboxing through taint checking and the safe module, and they do not assume that the potentially malicious code cannot access private members. Indeed, the filosophy in Perl is quite different - you are free to access any member function you want, or even 'private' data; it is assumed, though, that you know what you're doing in that case and won't come crying if things break for you as a result.

      --
      Trust the Computer. The Computer is your friend.
  2. Is this a C# or a .NET problem? by Dominic_Mazzoni · · Score: 4, Interesting

    Is this a limitation of C# or of .NET?

    What does this mean for the security of .NET programs? I thought it was supposed to be possible to run .NET programs in a sandbox, protecting you from malicious code. It seems that being able to access private members in the .NET framework opens up a whole new world of possibilities for security holes...

    1. 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.

    2. 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
    3. Re:Is this a C# or a .NET problem? by Anonymous Coward · · Score: 5, Insightful

      This whole story is hilarious. All (decent) languages let you hide implementation details from the end user. Finding them isn't `hacking` - its `stupid` as it means that if a chunk of code is changed to use, say, a doubly linked list rather than an array, your code would break, whereas it wouldn't if you accessed only the public methods/variables.
      This `exploit` is laughable, pointless and ultimately going to waste your time. The sort of coders who could use it would have the skill to figure it out in the first place anyway.

    4. 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.

    5. 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.
    6. 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

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

      Sounds more like FUD from the *nix crowd.

      "The C++ access control mechanisms provide against accident - not against fraud. Any programming language that supports access to raw memory will leave data open to deliberate tampering..." The Annotated C++ Reference Manual, p 239.

      Encapsulation has NOTHING to do with security.

  3. By design? by DrTentacle · · Score: 4, Insightful

    Is this behaviour by design, or merely a side effect of the implementation? If it's a side effect, then don't rely on the support for this "feature" to continue in future releases of the .NET framework. MS has a nasty habit of changing undocumented features...

  4. So .Net is like C++? by Ed+Avis · · Score: 5, Interesting

    In Java, the bytecode interpreter makes sure you can't access private class members. This is needed for security - creating the 'sandbox' which is most well-known from applets, and IMHO isn't used enough elsewhere.

    OTOH in C++ the public/protected/private distinction is enforced solely by the compiler, and code has full access to the machine.

    Obviously in .NET you don't have the same raw hardware access, but it looks like for speed Microsoft omitted to check access qualifiers at run time. But I wonder, is this part of the .NET specifications, or is it just an implementation oversight? Does the same trick work on Mono for example?

    --
    -- Ed Avis ed@membled.com
    1. 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
    2. Re:So .Net is like C++? by patniemeyer · · Score: 5, Insightful

      In the first chapter of my book, Learning Java I make this comparison and show an example of how trivial it is to forge a pointer in C++.

      The thing that many people still just don't get about Java is that it was designed to supply this kind of safety *without* impacting performance. In Java byte code verification happens statically, before the code is executed using a kind of theorem prover.

      With certain concessions from the byte code you can prove that various types of problems (stack overflows/underflows, incorrect casts, etc.) cannot happen and you don't have to check for them at runtime. Of course in OO languages let you do things that require runtime checks, but at the bottom level Java can be statically compiled and optimized amost as far as C/C++ (only runtime array bounds checks are required) and because Java contains so much more information at runtime the new generation of profiling runtimes can do further optimizations dynamically that cannot be done in C/C++ (e.g. optimistically inlining methods and profiling garbage collection routines).

      Pat Niemeyer
      Author of Learning Java, O'Reilly & Associates and the BeanShell Java scripting language.

  5. Dan 'Obvious' Appleman by playtime222 · · Score: 5, Interesting

    Anyone who's looking into reflection at any depth knows that private members can be found and used without too much trouble. The only thing he's done here is actively tried to use the private functions of code he didn't right. What a genuis :-/

  6. 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?

  7. Maybe the title should be changed by julesh · · Score: 5, Insightful

    Maybe the title of this book should be changed to "1001 ways to write bad code". Relying on undocumented private members of classes violates encapsulation and pretty much guarantees that your code will not work with (a) compatible implementations on other platforms, and probably also (b) future versions on the same platform. Just Say No, is my advice.

  8. 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 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
  9. Harumph by renehollan · · Score: 4, Funny

    ...and here I thought that
    ((<sneaky_private_type_I_wanna_access> *)<void_starish_opaque_handle>)-><ha_take_that_hid den_member> = 0; was bad style.

    --
    You could've hired me.
  10. Private methods and by yatest5 · · Score: 5, Interesting
    members are set as such not as some security method but to protect users of a class from using them. The fact this can be *programmed around* is irrelevant.

    Standard users, using standard techniques are only allowed to use public members and this is correct.

    I think you'll find that if you're willing to write your own compiler, you can access provate methods in any language you care to name.

    As such, this artile is irrelevant, an really just another pathetic excuse for a load of whingers to make cheap attacks on MS when they could *actually be contributing some effort* to the OS movement.

    Carry on guys, good work.

    --
    • Mod parent up! [a] by Anonymous Coward (Score:5) Thurs, June 31, @13:37
  11. Microsoft Security by rossz · · Score: 4, Funny
    As a bonus, you get a great introduction to how Windows security works
    How is that possible. By his own statements he proves that Microsoft security DOES NOT work.
    --
    -- Will program for bandwidth
    1. Re:Microsoft Security by p3d0 · · Score: 4, Interesting

      No, security obviously doesn't rely on the inaccessibility of private members. Just like C++: if you use "private" for security, you're in for a surprise when someone adds "#define private public" before including your header file.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  12. Washington Strikes Again (see prior story) by rc5-ray · · Score: 5, Funny

    Read on for more of Matt's review of this guide to tricking private members to do your bidding.

    In related news, Washington State has banned the sale of this book because of gratuitous discussion of "private members".

  13. 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.

  14. 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.

  15. 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 Delirium+Tremens · · Score: 4, Insightful
      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... [Pedantic emphasis added]
      Ever heard of AccessibleObject, JVMPI or Custom ClassLoaders? There, you have at least 3 ways to access private fields in Java besides your 'only way'.
  16. Sigh by kahei · · Score: 4, Interesting

    typically, a language ensures that a member marked as private is hidden from anyone who doesn't have your source code,

    No, typically the process of compilation does that for a compiled language that is naturally hard to read, and an obfuscator is used to do it for interpreted languages that keep type information or are otherwise easy to read.

    If you use a language that stores lots of rich metadata in the executable (like .NET), and that has a clear and readable bytecode (like .NET or Java), then you should use an obfuscator if you don't want anyone to be able to see your code.

    This being slashdot, though, naturally it's all Microsoft's fault. But there's still an element of fun in deciding *why* it's all their fault! Is it:

    1 -- MS's fault for not obfuscating code by default?
    2 -- MS's fault for including metadata?
    3 -- MS's fault for not having .NET compile to x86 assembly language?
    4 -- MS's fault for not simply holding all compiled .NET assemblies in escrow on behalf of their authors, releasing them only to trusted parties?
    5 -- MS's fault for not changing the nature of information itself to make this particular information hard to interpret?

    --
    Whence? Hence. Whither? Thither.
  17. Completely Irrelevant by sethamin · · Score: 5, Insightful
    Oh for god's sakes people, this is just dumb. There's no real reason to take the performance hit and enforce this at run-time, because the protection of private member variables are there for your benefit. If you want to access undocumented variables that were never meant to be exposed, you're just asking for bugs and future incompatibility.

    Oh, and BTW, this has nothing to do with actual security. Relying on access level specifiers to protect sensitive data in memory is lunacy. The standard coding technique for dealing with things like passwords is to keep them around for as short a period of time as possible and then overwrite that memory afterwards with random bits. If you're storing them long term cleartext in memory then you've got bigger problems.

  18. 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/
  19. 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.
  20. 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.
  21. finding them? sure. calling them? no. by MORTAR_COMBAT! · · Score: 5, Interesting

    Naturally even with rudimentary decompilers (and even the Java reflection API) you can find out what private fields and methods are defined for a given Java class.

    However if they are private, you can't actually find out the values of those fields for a given object, or call those methods. You get an IllegalAccessException.

    This .NET exploit advertises itself to be much different. Sure, you can still find out what private stuff you want.

    But under .NET, it appears you can actually _invoke_ those methods, methods which are probably meant to be hidden under a separate security API layer, etc.

    --
    MORTAR COMBAT!
  22. 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).