Dinner with the CLR team

Words really cannot describe the events that started a few weeks ago with a private invite to dinner with a few cool guys from the CLR team and ended just a few hours ago with a life changing experience for me. In your lifetime, there have probably been several times in your life where you have evaluated your skills and felt you were at the top of your game. Just the same, there have probably been other times where you just felt completely out of your league. Now, I’ve given a few presentations, written a few books and secured quite a few cool jobs in my lifetime so on my way to Atlanta to meet Brad Abrams, Kit George, Jason Zander, and Claudio Caldato from the CLR team, I was feeling pretty solid in my skill set. These guys, however, made this seasoned consultant feel like an end user.

To be perfectly honest, in context I am an end user. These guys are building the frameworks that I use to make money. By all definitions, I’m the guy that uses their stuff — ergo end-user. Now, before anyone gets the wrong idea, these were some of the most approachable and down-to-earth guys I’ve ever met. They didn’t belittle anyone or make any assumptions. They were truly engaging and were very interested in what feedback we had for them. They wanted to know what we were doing with .NET and how they could make our lives easier. The topics that I participated in ranged from talking with Kit about what’s new with security, to talking to Jason about all things memory management and the future of the CLR.

Now you may ask, “why was this a life changing experience?” I would of course have to answer thus: these guys got me excited about learning again. The brought back the same feeling I had years ago when I first started developing and everything was new and exciting. They reminded me about how much I didn’t know and how cool it could be to know that stuff. Two years ago, I caught myself falling down the “developer burn-out” stage that has happened to more than one developer that I know of in my life. I just couldn’t find it in me any longer to try REALLY hard to do my job. I bullied my way through that era and found myself interested in staying alive in the developer game.

But the group we talked to tonight had me more than just interested — I’m still jumping up and down in my heart. I’m excited again and I don’t think I’ll sleep for a solid month trying to play catch-up. I could have talked for months to these guys and I wouldn’t have blinked. If I say this appropriately, let me just say that I absolutely LOVED Jason Zander. Not that the whole team wasn’t brilliant, but this guy has been with Microsoft for 13 years. He’s been working with Microsoft since Windows 3.x and remembers compiling from OS2! As such, this guys has a wealth of knowledge that I couldn’t possibly pick up even if I didn’t have to make a living doing the grunt work.

I’m again looking at these words and finding myself , for once, unable to express even the slightest bit how in awe I am that these people know this much…

… just when you think you understand where the absolute top of the food chain is and think that maybe.. just maybe you could one day stand next to them and converse at their level, they start talking about the guys that “really know what they are talking about” that didn’t come to the dinner!!!

I just so happened to have had an old crappy 1megapixel camera in my truck glove box so I ran out and took the best pictures I could with the equipment I had. I had intended to drive all the way home tonight, get some sleep and blog about the dinner tomorrow. However, I’m so excited that I rented a room in a hotel in Greenville, ran to wal-mart to buy a new wi-fi card (since the motel I’m at has free wireless internet) and also a compact flash card reader. Please forgive the crappy photos, but I dumped them into a gallery for everyone’s amusement. Luckily, I was taking the pictures so I was out of most of them. 🙂

Guys thanks a million for showing up. Thanks a million for answering our questions. Thank you SO much for giving me a new bar to aim for. Thank you, thank you for bringing me back to life.

Charlotte Code Camp

I just got a moment to settle down and write a quick bit about the Charlotte Code Camp. It was a great experience despite the fact that I really only got to watch two presentations. Bill had a pretty cool presentation on speech server. Todd Fine (a Microsoft Regional Director) had a pretty cool presentation on Avalon. I have to say that every time I see this stuff I get very excited about the future of programming.

My presentation went over pretty well. I was hoping to have a larger crowd, but what do you expect when you are giving your presentation at the same time as Maxim Karpov , Doug Turnure, and Bill Ryan ? However, I was very surprised to see several evaluation forms with my code access security presentation picked as their favorite topic. Ibll be posting the presentation slides and source code on my blog here in a few days.

While Ibm thinking about it, if anyone is going to be in the Greenville, SC area on May 17th, we really need a GREAT turnout to the Microsoft MSDN event or we wonbt have Microsoft coming to town again. We need a turnout of 100 and we currently have just over 50 registered. We need about 130 registered to meet our goal and we only have a little over two weeks to do it! Please spread the word, we need attendance!

Exploit using System.String? Not Really

I’ve been playing around in the CLR for some time just playing with quirks and oddities.  I  noted some time ago that non-printable characters were easily stored in strings.  This really wasn’t a suprise except that a null character (“”) could be stored and appropriately retrieved from a string.  If I embedded a null character in a string, it didn’t cause the string to truncate when I read it back.  This made me wonder just how the string class knew how large its buffer was. How did it know which null character was it’s terminator?

Since my upcoming book deals, in part, with Reflection, I decided to try some playing around with the string object using MemberInfo. I found something rather interesting.  The string class keeps track of how large its buffer is in a member variable called m_stringLength.  So I started to wonder, what would happen if I created a string and then used reflection to change the length?

I decided to make this interesting.  I first created an example class that would represent a class handling sensitive data.  My code was simple and was as follows:

using System;

namespace CodeWithSecrets {

  // Lets assume this is a class that handles connection strings
  // or other sensative data.
  class ConnectionStringGuardian {
     public ConnectionStringGuardian() {
        connect = "uid=sa;pwd=LoveSexSecretGod";
     }
  }
}

I put this class in its own class library assembly named “CodeWithSecrets”. Then came the code that I would use to exploit the “ConnectionStringGuardian” class. 

using System;
using System.Reflection; 
using CodeWithSecrets;

namespace MalCode{ 
  class Malware {
    [STAThread]
    static void Main(string[] args) {
      ReadPastBuffer();
    }
    private static void ReadPastBuffer() {
      // Storing some variable
        String stringObj = "12345"; 
      // Store an object with private data in it
        ConnectionStringGuardian obj = new ConnectionStringGuardian();
      // Getting the String Type
        Type stringType = Type.GetType("System.String");
      // Getting a reference to the private field in System.String 
        FieldInfo fi = stringType.GetField( "m_stringLength", 
          BindingFlags.Instance|BindingFlags.NonPublic);
      // Read the string object 
        Console.WriteLine( "Reflected String: '{0}'", stringObj );
      // Set the private variable that keeps track of string length;
        Object parameter = 255;
        fi.SetValue( stringObj, parameter );
      // Read the reflected string  
      Console.WriteLine( "Expanded Buffer: '{0}'", stringObj );
      Console.ReadLine();
    }
  }
}

To explain what I’ve done here, I created a typical string holding an arbitrary value.  I then create an instance of my class that holds secret data.  Using reflection, I then access the private m_stringLength member to increase the size of the string’s buffer to 255. Finally, I output my string to the console to see if I can read past my buffer in a managed string. As you’ll notice, I write the string’s value to the console before increasing the buffer size, and then I write the strings value to the console again after modifying the buffer size.  The following screen shot depicts the results:

Malicious Code

Notice that I was able to read past the buffer and into the memory where the sensitive data was stored.  (First person to name the movie the sample password comes from gets a free Apress t-shirt if you send me your address.)

Now this is not really an exploit other than the fact that I can read memory to possibly sensitive data.  I tried to do other things to the memory such as stomp on it by calling the private “NullTerminate()” method that I found using reflection as well.  NullTerminate writes a null terminator at the end of a buffer using the m_stringLength value to determine just where to put that value.  This, unfortunately, did not overwrite the data in memory as I was expecting.  Ultimately, I was thinking that I might be able to break the type safety of an assembly by stomping on memory belonging to an instance. 

The problem with this code (or perhaps the good thing to note if you are an MS security expert) is that I have to use reflection to pull this off. I wouldn’t be able to execute this in a partial trust environment. If I downloaded this code in the internet zone, the reflection permission is not permitted by default. This severely cripples my attempts to make this tidbit worthwhile.  As Michael Howard responded to me: “fully trusted code is fully trusted code.”  True enough.

In any case, I hope this serves as some sort of education in some more internals of the string class. Let me know what you think. 

(P.S. No need to make the obvious statement that sensitive data shouldn’t be stored in classes.)

Old News, But Blog-worthy

There was an old article posted some time ago by James Gosling at Sun. I’ve been meaning to post about it but every time I had a spare moment, someone yanked it from me. In any case, in this article Gosling was shouting some ideas that Microsoft was breaking their Trustworty Computing Initiative’s rules by allowing C++ and C into the .NET family of developer products. Gosling was quoted as saying:

“If you look at the security model in Java and the reliability model, and a lot of things in the exception handling, they depend really critically on the fact that there is some integrity to the properties of objects. So if somebody gives you an object and says ‘This is an image’, then it is an image. It’s not like a pointer to a stream, where it just casts an image,”

Basically, Gosling wants people to feel that as soon as these products were made a part of the .NET product line, they made all other .NET code insecure due to violations of type safety.

Mr Gosling evidently hasn’t studied code access security 101. When an assembly is loaded in .NET it is verified by the CLR before it is allowed to execute. Verification is pretty extensive.

In brief, let’s consider what all happens when an assembly is loaded and executed. First off, the portable executable is validated to make sure it conforms to the PE/COEFF standard. Secondly, all the metadata is validated , making sure that all pointers have valid destinations. A symantec check looks for any sort of shinanigins such as circular inheritance. Next, the IL is verified to be valid and well-formed. As each method is JITed the code is verified to be memory type safe — looking for unsafe casts and attempts to access array indexes that are out of bounds. It probes for buffer overruns and underruns.

There is one caveat to all of this. C++ indeed cannot generally be verified. There is (currently) no way to verify type safety of code written in C++. So does this make Mr Gosling right about his statements? NO. He’s absolutely wrong — and I don’t just say that because I like pretending I know more than the CTO of a multi-national corporation. I say this because security policy in .NET by default rejects any code that cannot pass all of these verifications. To get .NET to run assemblies compiled in C++, it must have the permission to skip verification. If we look at the permission viewere in the .NET configuration tool, we can view any permission set that has the security permission selected. If we double click on the Security permission, there are several sub-permissions available to us. The one we are concerned with is the Skip verification permission. The diagram below depicts this setting in case you don’t feel like looking at this yourself.

This isn’t to say that Mr Gosling wasn’t right at all, but it does put a rather large kink in his argument that there is a HUGE security hole in .NET. Code that executes on the local machine will have this permission because by default all code running in the MyComputer zone runs with FullTrust. Full Trust includes all permissions — including the SkipVerification permission. Yes, if I’m honest with myself I have to say that is a problem, but not in the sense that someone will download code or execute something from the internet that will automatically wreck havoc on the entire type safety system. If I had one wish from he security team at Microsoft it would be to turn this feature off by default.

Selected for Microsoft Workshop

Today, I received a request from Microsoft and I must say that I am deeply honored. I cannot provide the details just yet other than to say it is to review the content of a workshop. I cannot wait to get started!

While I’m on the topic of Microsoft and content, I wanted to say just how impressed I am with their attitude in the last few years. Many years ago, you could at least make a somewhat convincing argument that Microsoft was a detached organism with a drive and mission much like a honey-bee. They were committed to their task and very efficient at what they did, but if you got in their way or tried to alter their course, they could sting you.

Today, Microsoft has a much friendlier faC’ade. They solicit advice from the community through structured beta programs. They glean information from online groups such as forums and newsgroups. They solicit the help of professionals and reward them for their help with the MVP program. You can drill directly into the psyche of the development teams by viewing their blog, posting comments, or contacting these guys directly. Microsoft is willing to accept your feedback. But much more importantly, the teams at Microsoft attribute value to what you have to say. You can tell that this is an initiative coming straight from the top. You can tell that the employees are following suit.

Microsoft, you’ve done something right. With all of the complaints that get ballied about, and noise that you hear when you clumsily attempt to protect your intellectual property, I wanted to make sure you got your dues when they are deserved. It is here that I start my stand-up-clap-fade-in and hope I can get a few folks to join me in a here-here.

.NET Security No No

OK. I’m going to cover this one time for guys in the peanut gallery.

Microsoft wised up some time ago and started shipping their Windows Server 2003 product with nearly every feature, apart from logging in, turned off. This was in response to the many-fold accussations that Microsoft was more concerned with functionality than security. (one could argue that they STILL are more concerned with features, but now consider security to be one of those features). In any case, today, when you install a Microsoft server product, it will have limited features, and this is a good thing.

What isn’t good is that developers and administrators keep bypassing this security by elevating priviledges for their code. They somehow feel that its appropriate to strong name their assemblies, and then grant full trust to any code with that strong name. This is an absolute NO NO!

Lets consider this scenario.If your house had priceless valuables stored in it, you would want the best security you could afford. You would remove the standard key/lock system, and replace it with biometric readers, voice print recognition systems, and panic button fail-safes. You might place further restrictions on rooms that contain your most prized possessions in case you have a dinner party — you wouldn’t want just anyone wandering into those rooms without your permission.

The same goes for your code. Think of permissions as the valuables to your code’s household. Grant permissions only when necessary, and only when all appropriate evidence has been supplied. Put fail-safes on your code by denying access to it by any callers that have elevated privileges. When clients access your application, don’t assume they should have access to all your code. If there are portions of your code that perform priviledged operations, require the client to provide additional evidence.

You need a layered approach to security. Granting Full Trust to your strong-named code will definitely help it run whatever you want it to, but you’ll also open the doors to anyone else that finds your valuable resources of interest.

DoS through TCP sequence number vulnerability

SecurityFocus is reporting that multiple vendors are affected by a newly found design flaw in common TCP implementations.  The flaw allows remote attackers to effectively end a TCP session by sending an RST or SYN packet with an approximated TCP sequence number and a forged source IP address.  This would reset the TCP connection and effectively cause a denial of service attack.  Microsoft is one of a long list of vendors on the affected list so you can bet the eggheads at SlashNot are going to highlight their name among them all.

Googling for web.config and other source code

I don’t remember which blogger pointed this out to me, but I wont take credit for the means of searching google in this fashion. However, there are some seriously misguided folks out there that obviously don’t know the first thing about security. Google allows you to search for pages with specific information in the title of the page as well as in the text of the page. Since many directory browsable websites have the word “Index of” in the title , it’s fairly easy to search for sites that are directory browsable. What’s more interesting is that you can then add an “in text” search that searches for specific files in those directory-browsable sites. This could be potentially dangerous if the wrong file were browsable. Take a look at the following search:

http://www.google.com/search?hl=en&lr=&q=intext%3Aweb.config+intitle%3A%22index+of%22+&btnG=Search

These are some of the very folks that want to blame Microsoft for all of their security and virus problems. Seems to me I saw some *cough* Apache servers serving up some of those pages. When will you people get the point that you are only as secure as you want to be and you can’t blame any one vendor for not doing all of your work for you?

BlueTooth Sniper Rifle

Are you sitting at home thinking “Man, I really want to be a computer security geek, but I want to look like a terrorist plotting to take down buildings all at the same time.” Well, this article has just the thing. A sniper rifle to pick off bluetooth communications from up to a mile away. Yikes! Instructions on how to make such a device and how to use it are suprisingly easy. Check out the article on Tom’s Networking: http://www.tomsguide.com/us/how-to-bluesniper-pt1,review-408.html

More String / StringBuilder Quirks

Circular References Between Classes:
I find it odd just how many circular references there are between StringBuilder and String. String.Format uses StringBuilder.AppendFormat while the StringBuilder.Chars property uses String.SetChar() (an internal method).

Unsafe Code and Unmanaged Code, No Assert?
While it is true that String, StringBuilder, and most other .NET assemblies use unmanaged and unsafe code. So why don’t you need to need to assert these permissions when using these common classes? The answer is not anything magical. Microsoft has to follow the same rules for Code Access Security and permissions that everyone else does. It just so happens that Microsoft has added their rules by default. Consider the following statement: Evidence + Policy = Permissions. OK so it’s not exact and you math majors out there might be wrything in your seats. But the basics are that an assemblies evidence is combined with code access security policy to yield all the permissions an assembly has. Do Microsoft-compiled assemblies have some special piece of evidence? Not special evidence, just your standard, every day Microsoft Strong Name evidence. Microsoft has added, during its installation, a rule that gives their strong name “full trust” permissions. You can view this in your .NET framework configuration 1.1 control panel applet. Navigate to the Security policy | Machine | My_Computer group. Under this group is the Microsoft and ECMA rules which provide the access your applications need to call the unsafe and unmanaged code in Microsoft assemblies.

Char Pointers? Why through StringBuilder but not through String?
I’m wondering why in the world StringBuilder.Chars would give access to the individual characters of a string (appropriately referenced through unsafe code pointers), but String.Chars hides this functionality, sticking to read-only access to the character indexer. I can understand, to some degree, that this might have been for thread-safety reasons. But, really, why do I have to create a StringBuilder if I want to use the faster user of pointers to modify individual characters in my string? Again, I can also understand that Microsoft might have wanted to limit the footprint of the string class since it is one of the native data types of .NET and is used so often. However, since the actual method (SetChar) that modifies the data is found in the string class anyway (back to that circular reference thing again) why wouldn’t you just make this available from the instance?

I have more problems with the behavior of these two classes, but really, who wants to write all those problems down?