Author Archives: Tobint

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.

OOP and Security

A new article has been posted at http://www.codemilitia.com/blogs/tobin.titus/articles/10.aspx

(begin excerpt)

A brief discussion broke out at work today surrounding collections and how they should be exposed in a client class. The proper OO way to expose a collection as a property is to provide a get accessor only. The get accessor should most likely always return an instance. Here is an example:

public class GoodClient {
   private TrustedCollection _data = null;
   public GoodClient() {}
   public TrustedCollection Data {
      get {
         if( _data == null ) {
            _data = new TrustedCollection();
         }
         return _data;
      }
   }
}

The get accessor checks for a null private member and creates a new instance if needed. This follows good encapsulation design.

So what does this have to do with security?

Lets consider that your collection’s “Add” and “Insert” methods might do some data validation on the parameters passed to the method before adding an item to the collection. Let’s look at an example of a class that does some validation:

public class TrustedCollection : CollectionBase {
   public TrustedCollection() { }
   public virtual void Add( DateTime date ) {
      DateTime now = DateTime.Now;
      DateTime is21 = new DateTime( now.Year - 21, now.Month, now.Day );
      if( date > is21 ) {
         throw new ArgumentException(
            "The person must be 21 years old.", "date" );
      }
      List.Add( date );
   }
}

Remember, the first rule of application security is that all input is evil. If your client depends on this validation to occur, it had better not provide a set accessor. Let’s look at how we can defeat this by using an inherited class and a set accessor.

(end of excerpt)

Continue

Home Network Paranoia

Some have called me paranoid, but I have a slogan of “Friends don’t let friends use wireless networks.”  The reason for this is that wireless networks compromise the need for physical access to a network to perform any attack on the internal network. 

Well, I of course, do have exceptions to my wireless rule.  I’m planning on getting a new PDA with 802.11 capabilities, I’d like to be able to access the internet from it.  As such, I’ve decided go add a wireless router to my home network.  Before I did such, I wanted to make sure that my devices and laptop would only have access to the internet from the wireless network, and not to my internal network.  I don’t any stranger standing in the woods of my back yard able to access my TaxCut and MS Money files through a wireless hack, and considering the Feds can do it in 3 minutes now, I think my paranoia is justified. 

I’m not a network security guru. I used to be a network administrator, but that was over 6 years ago and hardware was much different then.  As such, I’m publishing my network layout and asking for comments or suggestions or holes that anyone might see. 

network

As you can see, my internet access comes in through a cable modem which connects to a VoIP-capable router (yes, I use Vonage).  The reason for using this router as my opening router is somewhat physical.  In my garage, where I terminated all of my network runs, I also terminated a cable line and phone lines at a patch panel.  Since the VoIP router also provides data ports, it’s perfect for acting as a distribution for both my planned wireless router and my 8 port routing switch.  The outgoing voice line patches into a telephone patch panel distribution that supplies the house telephone runs.  The 8 port router serves as the first layer of defense for my data network It then provides access to the whole house through the patch panel distribution point where I ran all of my data lines to. (I luckily got to do all my own structured wiring while the house was being built).

Its important to note that I do not allow access from the wireless network across the internal side of the VoIP router, and I again block packets originating from the wireless router at the 8 port.  The 8 port router and the VoIP router does, however have some rules for open ports that my wife needs to play games, and that I need for various services I have running on my internal network.  Because of this, I’ve added another Cisco PIX firewall in my upstairs office to prevent any inbound requests to my file server, my development PC, and of course the computer I use for family record keeping. The file server is behind the firewall, but I have rules set up to allow access to it from the other house PC’s.

In any case, as I look at my network, I start to realize how imperfect it is.  I’m looking for advice from anyone on how to make it more secure but still provide the needed functionality to our standard home PC’s and to our private personal-data machines.