Monthly Archives: April 2005

You are browsing the site archives by month.

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?

Updating Controls From Worker Threads

I thought this was an issue that has been hashed over enough times, but the other day I was asked this question and I’m still amazed that many folks are unfamiliar with this concept.

In WinForms applications, sometimes its desirable to execute a long running method in a worker thread. For instance, you may be retreiving data over a web service that has a heavy load and usually takes several seconds to execute.. When the work has completed, it’s typical that you would want to update the user interface: be that a grid, a tree view control, or some other container that displays the results of your call to the long running process.  Sounds simple enough right?

Before you get in a hurry, consider one thing.  Data created on one thread is owned by that thread as long as it is local data.  This can be overcome though by marshaling the data across threads.  This is a function of Thread Local Storage implemented through managed code. Virtual address space of a process is shared across all threads.  While the data of a thread is unique, it can be “shared” or copied but you need to tell the application to copy the data to a the UI thread before updating the UI with the data.  This can be done using Control.Invoke().

Take a look at what happens when you don’t use this method.  Createa  new Windows Forms project, add a TreeView control (tvResults) and two buttons.( btnNormalExe and btnThreadExe ).  Add the following methods on the form:

public void WorkerThread() {
    Cursor.Current = Cursors.WaitCursor;
    // Simulate Long Process (5 seconds)
    Thread.Sleep( new TimeSpan( 0,0,0,5,0 ) );

    UpdateResults();
    Cursor.Current = Cursors.Arrow;
}

public void UpdateResults() {
  // Update UI
  tvResults.Nodes.Add(
    String.Format( "UI Updated on Thread ID {0} at {1}", 
       AppDomain.GetCurrentThreadId().ToString(),
       DateTime.Now.ToString() ) );
}

For btnNormalExe add the following code:

 

private void btnNormalExe_Click(object sender, System.EventArgs e) {
  WorkerThread();
}

For btnThreadExe add the following code:

private void btnThreadExe_Click(object sender, System.EventArgs e) {
  Thread t = new Thread( new ThreadStart( WorkerThread) );
  t.Start();
}

Now run the form and click on the normal execution button first. Once the method completes, click on the thread execution button.  You’ll receive an exception when the threaded execution completes:

An unhandled exception of type 'System.InvalidOperationException' 
occurred in system.windows.forms.dll
Additional information: The action being performed on this control 
is being called from the wrong thread. You must marshal to the 
correct thread using Control.Invoke or Control.BeginInvoke to 
perform this action.

Just as the exception says, we are going to modify our call to make sure we get back on the UI’s thread before updating it.  In this way, the form’s thread owns the data, not the worker thread. Modify the UpdateResults() method as follows:

public void WorkerThread() {
  Cursor.Current = Cursors.WaitCursor;
  // Simulate Long Process (5 seconds)
  Thread.Sleep( new TimeSpan( 0,0,0,5,0 ) ); 

  //UpdateResults(); 
  this.Invoke( new TreeViewUpdater( UpdateResults ) ); 
  Cursor.Current = Cursors.Arrow;
}

Notice that when you execute both the normal execution button and the threaded execution button the tree view control updates with the same thread ID. This is because the call to control.Invoke puts the call back on the form’s thread.

I will cover this in more depth in the weeks to come, to shed more light on what’s happening in the background.

Post Navigation