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.

84 of 514 comments (clear)

  1. Make any private member acessible. by D4MO · · Score: 2, Insightful

    Use a memory hex editor!

    --

    Rocket science is easy. Neurosurgery, now *that's* difficult.
  2. 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. Re:Conclusion by dash2 · · Score: 3, Interesting

      Not entirely true. The default way to build objects in Perl exposes private functions and members, and just trusts the API user to be sensible. But there are well-documented ways to create truly private functions and members - like using file-scoped variables or anonymous file-scoped subroutines. Damian Conway's book (Object-Oriented Perl) describes this in detail.
      Perhaps there are still ways to get round this security by something more lowlevel, like peeking directly into RAM, but they certainly aren't at all easy.

    3. Re:Conclusion by ProfKyne · · Score: 3, Insightful

      Neither Perl nor C stuff depends on this encapsulation for any security stuff.

      Perl and C programmers are not target demographic of the .NET initiative.

      --
      "First you gotta do the truffle shuffle."
    4. 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
    5. Re:Conclusion by Anonymous Coward · · Score: 3, Funny

      Microsoft has secuirty holes in there software.

      So as long as I run it here, I'm OK. Is that what you are saying?

    6. 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.
    7. Re:Conclusion by MSBob · · Score: 2, Insightful

      Depends on your security policy settings. You can restrict your policies so that nobody can get private member/field access through reflection.

      --
      Your pizza just the way you ought to have it.
    8. Re:Conclusion by Ralph+Wiggam · · Score: 3, Interesting

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

      -B

    9. 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."
    10. Re:Conclusion by ProfKyne · · Score: 2, Interesting
      • Perl.Net -- not a Microsoft product, therefore not related to the discussion ("target demographic of .NET initiative").
      • Managed Extensions for C++ -- not C, therefore not related to the discussion (I said "C programmers" and in another branch of this thread I make it clear that I used C and not C/C++ for an explicit reason).
      --
      "First you gotta do the truffle shuffle."
  3. 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.

  4. Posted on BugTraq by oliverthered · · Score: 3, Insightful

    Isn't this a security bug, you think that you've hidden some code, but infact it isn't.

    --
    thank God the internet isn't a human right.
    1. 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/
  5. 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...

    1. Re:By design? by Sique · · Score: 3, Interesting

      I completely fail to see what's nasty about it. If it's not documented, you just plain should not rely on it. Isn't hat the way all code works?

      The problem is the same like the old one which let you disassemble VisualBasic programs back to the sourcecode about some years ago.

      If you put a trade secret inside your code, it is now much easier to access by an outsider because she doesn't have to rely on the binary code alone, but can spy on the structure of the program. This gives her a pretty good clue which algorithm was used and which data structures were used.

      Basicly it makes everything you do in .NET a "half open source" program.

      --
      .sig: Sique *sigh*
    2. 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.

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

  7. 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 :-/

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

    1. Re:C++ by crazyphilman · · Score: 3, Interesting

      I don't think you should be modded down. It's an interesting point. Open source types do sometimes tend to "overlook" the shortcomings of C++ (and their other favorite languages like Perl, Python, Ruby, etc) because it's a political thing for them, and you end up getting into these big propaganda wars. You could say they're "drinking the kool-aid", just like all the frothing, rabid managers back in the dot-com days used to.

      But I think most open-sourcers are a little more sedate than that; they like C++ because C++ is completely free and nonproprietary (gcc is GPL, and C++ has been an ANSI standard for way over a decade, hasn't it?). So, in a sense, it's a language that no one can ever take away from you, and which has been more or less frozen in its current state (new functionality is generally handled with additional libraries) for years. C# and Java, on the other hand, are proprietary languages, so it is theoretically possible for the companies that own those technologies to change them on a whim, or even kill them off. I sympathize with this view somewhat, but I don't fully agree with it.

      Is the "freeness" of a tool enough to support its use? Should we choose our tools based on how free they are, or on how useful they are to us? How do you pick a compiler, really? It's interesting.

      I like Java, personally. It has pretty nice features and a rich API. I lust after C# somewhat, but my boss won't let me use it (he likes VB.Net -- pity me).

      --
      Farewell! It's been a fine buncha years!
    2. Re:C++ by anshil · · Score: 2, Insightful

      """Should we choose our tools based on how free they are, or on how useful they are to us"""

      Well in the case is the freedom not just a special kind of usefullness? Especially if usefullness is weighted in a longer term

      --

      --
      Karma 50, and all I got was this lousy T-Shirt.
  9. 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.

    1. Re:Maybe the title should be changed by Jerf · · Score: 3, Insightful

      If the alternative to writing a quick ACL changer is multiple days of intense hacking, vs. a couple hours with the right pokes at private members, it will take a lot of internal interface changes before the amount of time spent tracking the internal API exceeds the time it would have taken to do it right the first time. Since the capability doesn't officially exist, your (a) point is meaningless (even this platform doesn't officially support it) if you can assert that everybody will use the same platform, and given we're talking .Net the odds that a an awful lot of .Net programs will run only on Microsoft's implementation anyhow is pretty high, and odds are (b) doesn't bother you because it may never happen (changing the internals like that also implies work for that developer, so it's not a bad bet they won't be in a hurry to change the internals for their own sake), and even if it doesn your probably still ahead.

      Encapsulation is not an absolute law, it's a risk that must be analysed like any other risk, and treating it like an absolute law will sometimes cause you to do sub-optimal things. I can't be 100% certain with the given information, but odds are that the choice to use internal private methods and data to do ACL manipulation are a good bet. Yes, you may lose, but implementing ACL manipulations yourself may lose too: If the ACL system changes, you have to track it yourself, while the odds are decent that the internal private members will automatically track the changes!

      Violating encapsulation is almost always bad, but that's a long way from "always bad".

  10. 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 Anonymous Coward · · Score: 2, Interesting

      It does *if* you have the correct permissions. Just like .Net.

      If you're running a .Net app off a webpage, it won't have private reflection permission either.

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

    4. 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
    5. Re:Duh. Its called reflection by mnmoore · · Score: 2, Interesting

      This is not necessarily true.

      If a SecurityManager is installed (as one would be in the applet environment or any other environment running less-than-completely-trusted code) Class.getDeclaredField() for a non-public member may throw a SecurityException (depending upon the policy enforced by the particular SecurityManager).

    6. Re:Duh. Its called reflection by gh · · Score: 2, Interesting

      Here's a juicier example for Java...

      "hi there".equals("cheers !") == true

      Not only does Heinz Kabutz demonstrate accessing private members, he shows how one can alter the behavior of interned Java strings!

  11. 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.
  12. 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.

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

    2. Re:Private methods and by yatest5 · · Score: 2, Insightful

      Er, write your own VM then. Client-side security is no security at all i.e. you're free to fuck up your own computer any which way you want.

      --
      • Mod parent up! [a] by Anonymous Coward (Score:5) Thurs, June 31, @13:37
  14. 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....
  15. Why should they always bypass logic? by ptaff · · Score: 2, Funny

    So, a private member is not private.

    All this fighting for Intellectual Property, for information privacy, DRM, to discover that actually, behind the scenes, in the Microsoft world,

    a private member is not private

    Look, ma, we'll sell this slow API, and on our side we'll use undocumented features, make private members public, get a performance boost and say afterwards we've got a better product and that it was all fair play.

    Innovation, would say Ballmer.

  16. 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".

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

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

  19. Sweet! by mschoolbus · · Score: 2, Funny

    I can finally call the BSOD member! uh.. nevermind...

  20. 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'.
  21. 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).

  22. 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.
  23. 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.

  24. Don't do that!!!! by Rajesh+Raman · · Score: 2, Funny

    You'll be arrested for breaking the DMCA!! After all what is a private method? Code that has access protection!

    Besides, it's impolite to access stranger's privates if you weren't supposed to. If you're a 'friend', on the other hand, you presumably have access to all the privates of interest.

  25. 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.
  26. I Love Short Books by jetkust · · Score: 2, Insightful

    The whole text weighs in at just under 50 pages

    Good. I always hate books that are 1000 pages long just so the author can meet some type of quota. When in reality, the book is just full of extra fluff,and is much less useful as a learning tool because of it. To me, the best programming books are short. You can read them,learn, flip through them with your thumb, and each page has a lot of information. Once it gets too long it looses focus. And at this point, searching the internet and reading online help files starts seeming like a way better idea.

  27. New .NET keyword by kmahan · · Score: 2, Funny

    Today Microsoft announced a major new feature in their .NET c# language. They have introduced a new keyword "really". To be used with the "private" keyword. By declaring something "really private" you can make sure that it will not be exported in a "blatantly obvious" manner.

    For added security you can use the "really" keyword multiple times to define your level of security. So "really private" is less secure then "really really private".

    Use of this keyword with other keywords such as "public" can have unpredictable results.

    --
    Invalid Checksum. Retrying.
  28. 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.
  29. 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.

  30. The C Programmer's Handbook by kmahan · · Score: 2, Interesting

    The best "C" book out there is (was) "The C Programmer's Handbook" by Bolsky (AT&T Bell Laboratories). 84 pages. Small. Designed as a reference. C Syntax, precedence rules, a few funtions, ascii table, etc.

    They used to include the book with each 3B (and other) unix box.

    It was written to be useful, not to be big.

    --
    Invalid Checksum. Retrying.
  31. Not a problem at all by MickLinux · · Score: 3, Funny

    How could this ever be a problem?

    This implies that Microsoft, in switching to the .net development model, is going open source!

    Unofficially, of course. And people who implement it without being registered members of the Department of Homeland Security *could* be branded terrorist hijackers. But not to worry: only the evil ones will be. The others will accept automatic induction into the DHL framework.

    --
    Correct Horse Battery Staple: 72 bits of entropy. Enter "Correct H" into google. When it generates the phrase, that's
  32. Security by Get+Behind+the+Mule · · Score: 2, Interesting

    Good heavens! I'm a little startled at the thread so far -- all of these people stoutly declaring that violation of private class member access is not a security issue. I frankly thought that the Slashdot crowd understands these things a little better. If this matter is really so poorly understood, then the state of software security is in pretty bad shape.

    Enforcement of access levels is an important feature of the security inherent in a programming language. Yes, you can trick your way around private in C++, and that is a security weakness of C++. Access to private members means that you have access to the internal implementation of a class, which the programmer specifically did not mean to let you have. To be sure, the fields you can manipulate may not do anything very interesting, and a hacker might not find a way to use them to compromise a whole system; but then again, may he can. You just can't know for sure any more. Generally, any code that can be made to execute instructions that the programmer did not intend is a potential security weakness. C programmers who write sprintf without bounds checking may be exposing their machine to a buffer overflow exploit; you just don't know.

    Here's an example from Scott Oaks in Java Security: Suppose I'm using a shopping cart application that I downloaded from www.goodguys.com, and I trust it with my credit card number. Suppose they implement it by storing a CreditCard object as a member field. Suppose I'm also playing a game downloaded from www.badguys.com, and it's running in the same virtual machine; so it could conceivably access classes of the other application. I certainly hope that the first application prevents access to the CreditCard object, and I certainly hope that the virtual machine enforces that restriction very strictly.

  33. private != secure by Vicegrip · · Score: 3, Insightful

    The point of private declarations was never to provide security. It was to get users of said code to access an object through a defined interface.

    A program, as far as the OS is concerned, has legal access to its entire process address space. So, whilst it's true that the virtual machine might be able to control access to private members by code written to run on top the vm, that data is still in memory and can be accessed by anything that can bypass the memory manager in the virtual machine. A linked library written in your favorite natively-compiled language of choice fills this bill nicely.

    In this case, the .NET manager does not completely protect private members. This is, at most, only ugly from a language purity sense. Probably it's a function of running natively through a jit compiler instead of on-top a VM.

    Summary: these new virtual machines do a decent job of protecting private members, but nobody in their right mind should rely on the mechanism for security.

    --
    Do not spread "09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0" over the internet, thank you.
  34. 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!
    1. Re:finding them? sure. calling them? no. by asills · · Score: 2, Interesting

      .NET has the exact same thing. If you run your .NET code in a "sandbox" you can disable reflection permissions, thus making it impossible for a running application to reflect over your assemblies.

      Just like java, however, get it out of a sandbox and you can do whatever you want to it.

      --
      -- What did Spock find in Kirk's toilet? The captain's log.
  35. 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).

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

  37. Re:Isn't this a security issue? by tshak · · Score: 2, Insightful

    Now, in Java, acecss to private class members is strictly forbidden by the JVM.

    No, it's not. Please read up in this thread to see a few posts with examples of how to access private members in Java.

    But a lot of the .NET classes that Microsoft provides are written in C/C++ and have to access the system - and by messing up the private variables in these classes, there's no end to what you could possibly do...C#/.NET is supposed to be able to run in a sandbox...


    The point is that .NET does run in a sandbox of sorts, and the accessability of a class member can not circumvent that. So what if I can access a private member of some class that can delete system files? The runtime will detect that you aren't allowed to access the system files regardless of the accessibility of the method attempting to do so. Even if it's "Microsoft's code", it's not trusted because it's part of your program and running under it's security context, so the same security restrictions are placed on Microsoft's code as is yours, since your program is the one accessing it.

    --

    There is no longer anything that can be done with computers that is nontrivial and clearly legal. -- Paul Phillips
  38. You are WRONG by grungeman · · Score: 2, Interesting

    It is not possible in Java. Otherwise you could access parts of java.lang.SecurityManager, which itself is written in Java. Not sure about .Net, but in Java you could do a lot of really nasty stuff if this was possible.

    If this was possible in Java, Micrsosoft would have published at least three big reports on how insecure Java is (of course through some "independant" third party consulting companies)

    --

    Signature deleted by lameness filter.
  39. Another poor API from MS by solprovider · · Score: 2, Interesting

    If the alternative to writing tons of code is accessing private functions of the internal API, then the API was designed very poorly.

    Everybody seems to agree that a quick ACL changer is useful. The code already exists in private functions. If the private functions should not be public because they bypass data reliability checks, the API designers should provide a public function that provides a safe method to call the private function.

    Encapsulation should be an absolute law. The maintenance headaches of ignoring encapsulation should be too great to encourage bypassing it.

    Providing useful functionality in private functions without allowing the functionality through public functions is security through obscurity. It either enourages programmers to write poor code, or forces the programmers to do extra work. The whole point of "platforms" is that they greatly reduce the amount of code needed to implement an application while providing basic functionality such as security and networking.

    Imagine if Apache did not exist and every application needed to implement a web server. Every web project would require much more code. Now imagine if the only method to get Apache to display a web page was to use tricks to access private functions. Everybody would do it. Now imagine MS wrote the API. Oops, that is what we have here. Really basic and useful functionality is hidden from the programmer. "Luckily" the platform security is so poor that everybody knows how to access the functions anyway.

    Apparently these tricks are posted on Microsoft's web site (based on from other posts since I am not going to check.) Apparently MS knows the functions are useful. Apparently MS knows the language is broken.

    Will MS fix the API?
    Will MS fix the language?
    Will MS encourage these tricks?
    Will MS break the code that uses these tricks?
    Will MS reduce the amount of work necessary to write apps on their platform?
    Will MS divide programmers between the
    - experienced ones who know the illegal tricks,
    - newbies who thought documentation was complete, and
    - good programmers who expect MS to fix the code someday and are not willing to risk using these tricks?

    I am happy I am not one of those programmers who is faced with the choice to write good code or write MS code.

    --
    I spend my life entertaining my brain.
  40. getting around IllegalAccessException by fizbin · · Score: 3, Insightful

    Sure you do, if you try to access them without first calling setAccessible .

    However, it's pretty easy to turn that exception off unless there's a SecurityManager installed.

    Conclusion? Don't make any java code a security boundary without putting a SecurityManager properly in place. This also implies that java code at security boundaries has trouble being fast, but that's the case with any code at security boundaries.

  41. Some clarifications by DanAppleman · · Score: 2, Insightful
    I've enjoyed reading the many comments so far (well, most of them). Just a few clarifications:

    1. I am not anti-Microsoft. I thoroughly enjoy coding in .NET. The eBook is not anti-Microsoft or anti-.NET

    2. This eBook does not break .NET security or demonstrate a flaw in .NET security. It does, however, teach an important point - that member visibility is not a security boundary. Failure to consider this could result in a developer doing a security Assert within a private member and inadvertantly create an exploitable security flaw in their code - which is an extremely serious issue.

    3. This is not a design flaw in .NET. Private member access is necessary for object serialization in .NET and is itself secured via code-access security.

    Dan

    1. Re:Some clarifications by The+Bungi · · Score: 2, Insightful
      The eBook is not anti-Microsoft or anti-.NET

      Then perhaps you shouldn't have named it 'Hijacking .NET', eh? What's wrong with '.NET Internals' or something that didn't smack of evil unauthorized and insecure hacking?

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

  43. This is NOT a problem! by spitzak · · Score: 2, Interesting
    I'm going to agree with the intelligent majority here. This is not a security feature and is not any kind of failure of Microsoft. Private members are designed to encourage properly-written code, but they don't enforce it.

    The author is promoting bad programming practice, if his code becomes in common use he will force Microsoft to lock the internal implementation of the objects, which will make them inefficient and may lock in bugs. If his code is not popular than Microsoft will probably change it under him and break all his code, and this is perfectly within their rights, as the whole point of "private" is that this portion is not part of the API and it may change!

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

  45. subtitled... by Royster · · Score: 2, Insightful

    ...How to Write Code Guaranteed to Work Only with Microsoft's Implementatyion of .NET and Not Mono.

    --
    I have discovered a truly marvelous sig, unfortunately the sig limit is too small to contain i
  46. El Stupido... by Lodragandraoidh · · Score: 3, Insightful

    Seems like a bad thing to implement an interface to a non-documented API for mission essential code.

    The problem with this is that Microsloth can easily change their non-public interface without telling anyone and your code will break. Other than the lack of security implied by accessing things that are supposed to be secure, this interoperability issue will come back to haunt anyone who implements these 'tricks' IMHO.

    Don't put this in mission essential code, or you will recieve a phone call late one night by your operations staff for unknown reasons...you have been warned.

    --

    Lodragan Draoidh
    The more you explain it, the more I don't understand it. - Mark Twain
  47. 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}