Tag Archives: Security

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?

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.

File uploading in a web environment

A recent question was asked on the ASP.NET forums:

“i’m building a page to let people upload images to my site. they are supposed to see the images after uploading them.
i wondered if somebody can take ane “exe” file, change the extension to “jpg”, upload it, and then run it by pressing the “view picture” button. will my server run this exe file? if yes, how can i check if it image (“jpg” and “gif”) or something else?
great thanks…”

The question actually encompasses a very frequent request that users have. The fact that someone knew to ask about this before just implementing the upload feature proves that the mentality toward securing applications has been changed slightly from “Lets implement as many features as we can” to “How will implementing this feature affect the security of my application”.  This mentality, I feel, is spurred by several factors such as Microsoft’s increased Trustworthy Compupting initiative.

Since I feel its good to reward people for thinking about security first, I will do my best to answer this question for the user here on my blog. In the next few days, I will be launching a series of posts relating to uploading files in a web environment, the security issues, and better ways to implement the feature.  I’ll start by defining the functionality that is ultimately wanted, provide some insight into the various ways to implement this functionality and the security issues surrounding each approach, and then move on to designing a solution and perhaps even provide some sample code.

For now, let’s focus on the functionality and delve a bit into some various ways to implement this feature.

In general, the developer wants users to be able to upload image files to a website, and let someone or several people view the images after they are uploaded. This feature is implemented in the very software that is used to run this blog — Community Server.  Over the years, this feature has been implemented in more ways than I care to count.  Some folks store the uploaded file as is to the file system.  Others have stored the binary data as a BLOB in a database.  Others have used hybrids of this mechanism.  For this portion of the article, we will focus on a file-based approach and follow up with a database approach.

Storing in the File System

The most logical way to store files, it would seem, is in a file system.  From a public internet standpoint, however, one has to consider the trade offs of this approach.  The first problem is that your web user account (most likely the ASPNET account) has to have permission to write to the file system in order to pull this off.  The second issue is that if you write to a file within the scope of your web’s root folder, those files can most likely be accessed through IIS as well (and since this particular user desires for the images to be available to the public, they almost have to be available).  The security concerns are massive.  A user could upload a web-executable script to the server that they could then use as a trojan to gain access to the rest of the server. More advanced hacks could be used to compromise memory buffers and cause an executable to run in the server process (one of the main resons behind the new aspnet_wp running under the context of a low-privileged user).  There are some ways to decrease the risk involved in this method, however.  Some of them involve security through obscurity (not sufficient by itself).  Some of them involve coupling the best of OS security, web security and application security. 

Directory Structure

For starters, consider the fact that you do not want any files that are uploaded to be scriptable on the server side.  So lets set up a directory structure and security for our saved files. Start by creating your main upload directory outside of the web root.  For example, if your web root is found at C:inetpubwwwroot , create your image directory at C:inetpubuploadroot.  So why did we do this?  This prevents anyone from uploading malicious scriptable code to your server that can be executed on the server.  Once you create your directory, make sure you grant read and write permission to ASPNET user (if you are not using impersonation)  or to the Groups and Users which you will allow to upload files.  In my case, I granted the following permissions:

Administrators      Full Control
ASPNET             List Folder Contents, Read, Write
Network Service  List Folder Contents, Read, Write
System                 Full Control

Uploading your File

Once you have set up your directory structure, you’ll need to create your upload page. You only need an HTML file control and a submit button. Once you add your HTML controls, make sure you run them at the server side.

screenshot

Once you’ve set up the page, add the following code to save the file:

private void btnSubmit_Click(object sender, System.EventArgs e) {
 HttpPostedFile file = fleUpload.PostedFile;
 if( file != null ) {
     string serverFilePath = String.Format(   
        @"C:domainstitus.touploadroot{0}",
        file.FileName.Substring( 
        file.FileName.LastIndexOf(@"") ) ); 
        // TODO: Write file validation routine.
        if( ValidateIsJpeg( file ) ) {
           file.SaveAs( serverFilePath );
        }
  }
}

Validating The File

This get’s the job done for uploading, but it still isn’t secure and we haven’t given the user any way to retreive the file.  Now, I’m not an expert in image file types, but I know that each has a format.  I would HIGHLY recommend that you learn the proper methods to validate each file type you intend to accept and write a routine to test the uploaded file against the expected format.  For JPEG files, you can read an online FAQ at http://www.faqs.org/faqs/jpeg-faq/ that will explain the format and give you clues on how to validate this file.   Remember that ALL INPUT IS EVIL and with file uploading, this is particularly important.  However, I’ll leave this implementation up to you since this can get rather complex and will change based on each file type you want to accept. 

In Part #2, we’ll discuss how to retreive images that are stored on the file server using an HttpHandler.

Forms Authentication Cookies in the QueryString

Most folks don’t like their authentication data appearing in the query string, and with good reason. However, one does have to consider some trade offs when enabling cookieless sessions.

A user recently posted the following in an ASP.NET security forum.:

I use Forms Authentication technique in my Web application interactive with mobile devices. The configuration is like the following:

 < authentication mode="Forms" >
   < forms loginUrl="login.aspx" timeout="30" protection="All" path="/" />
 </ authentication >
 < authorization >
   < deny users="?" />
 < /authorization >
 < sessionState mode="InProc" 
      stateConnectionString="tcpip=127.0.0.1:42424" 
      sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" 
      cookieless="true" timeout="20" />

Mangled URLs are used during sessions due to the cookieless=true setting. But why is the authentication cookie (in my case, its name is ASPXAUTH) also carried in the URIs? I know that this cookies is needed to be present in HTTP headers, but what configuration has defined this cookie is embedded in the query string of the URL like this?

http://localhost/myapp/(wcaz3svlxsdfinygyttuiu45)/default.aspx?__ufps=594900&.ASPXAUTH=887134660EC8D9CE8D72

The answer is simple but again requires you to consider the trade-offs when using cookieless sessions. This behavior is largely in part because the SessionStateModule class writes data to the cookies collection using HttpRequest.AddResponseCookie()

The AddResponseCookie() method looks to see if the cookie collection is null (and it will be if you are using cookieless sessions). If it is null, it will then append the asp.net auth cookie to an internal HttpValueCollection. These values are then written to the QueryString when the handler writes the response back to the user.

The fact that this is an cookie doesn’t go away because it’s a “special cookie”. In fact, what good would your cookie do if it was, in fact, written back in the header? The whole reason behind cookieless sessions is to allow sites to work that don’t support client-side cookies. If someone didn’t support cookies, and your authentication cookie was written back in the header instead of the QueryString, your cookie-based forms authentication cookie wouldn’t work either.

Keep this in mind when enabling cookieless sessions and forms authentication together.

String.Format vs StringBuilder.AppendFormat

So here’s a question, what’s the difference between String.Format( string, object[]) and StringBuilder.AppendFormat( string, object[] ) ?

For those of you thate don’t know, String.Format allows you to parameterize your strings, by placing replacement tokens througout a string template.  You can later fill in those tokens with parameterized data by passing it in as an array. Here is an example:

string.Format("I own a {0} and {1} name is '{2}'", 
        "cat", "her", "Ellie" );

Of course this would output the sentence: “I own a cat and her name is ‘Ellie'”.  You can also achieve the same thing by calling StringBuilder.AppendFormat much like the following example:

StringBuilder sb = new StringBuilder();
sb.AppendFormat( "I own a {0} and {1} name is {2}", 
        "cat", "her", "Ellie" );

At first glance, you may be thinking that these are somewhat interchangable with the exception of performance. By now, we all know StringBuilder is usually faster for excessive string manipulation. What you may not know is that string.format calls the StringBuilder.AppendFormat method under the hood.  Additionally, StringBuilder will throw an exception if the number of parameters does not match the number of tokens found in the template string.  Try compiling and running a program that executes the following statement:

[STAThread]
static void Main(string[] args) {
  string x = string.Format(
    "{4} owns a {0} and {1} name is {2}.", "cat", "her", "Ellie" ); 
  Console.WriteLine( x );
  // For those of you that know WriteLine takes format strings... shhhhh
  // I'm trying to make a point here!
}

You will receive the following exception.

An unhandled exception of type 'System.FormatException' 
occurred in mscorlib.dll

Additional information: Index (zero based) must be greater 
than or equal to zero and less than the size of the argument 
list.

This exception is actually thrown by StringBuilder.AppendFormat and the String.Format method bubbles the exception up without providing the consumer with any recourse if the parameters dont’ match up.  However, if you call StringBuilder.AppendFormat yourself, you can place the code in a try catch block, and reap the benefits of a string that has been formatted as best as it can be with the parameters provided. Take the following code, for instance:

[STAThread]
static void Main(string[] args) { 
  StringBuilder sb = new StringBuilder();
  try {
    sb.AppendFormat( "{0} owns a {1} and {2} name is {3}.",
        new object[] {"Tobin", "cat", "her"} );
  }
  catch(FormatException ex) {
    Console.WriteLine("An exception occurred: {0}", ex.Message ); 
  }
  finally { 
    Console.WriteLine( sb.ToString() ); 
  } 
  Console.ReadLine();
}

Notice here that we have caught the exception, reported on it, but can still write the string builder’s text to the screen — or at least the part that was parsed.

Now here’s the questions I pose for all of you:

  1. Since you now know that you can bypass the token-count to parameter-count validation check by using StringBuilder, should you incorporate this into your applications in instances where you don’t know how many parameters you are going to have?
  2. Would you consider this to be a bug, or a reasonable feature and why?

Canonicalization issues and File Paths

I keep running into code lately that does some pretty elaborate security testing but in the end leaves a very large issue unaddressed — canonicalization errors related to file I/O.

Michael Howard and David LeBlanc dedicated an entire chapter in Writing Secure Codeto the idea that “All Input is Evil“. The concept is that you should not rely on the fact that input coming from any source — trusted or not is going to be in a format that you accept. You should validate, validate, and validate again even if your I/O function isn’t intended to access anything of great importance.

Canonicalization is the process of breaking something down to it’s most simple form. Let’s take a look at an example:

public FileStream OpenFile( string fileName )
{
string fullPath = string.Format(@”C:inetpubwwwroot{0}”, fileName);
return new FileStream(fullPath, FileMode, FileAccess);
}

You may have ony intended to give this function access to code stored in the default web root. But what would happen if someone called your function like this:

File f = OpenFile(”..\..\windows\system32\config\sam”);

The elipsis at the begining of the path would direct the file to go up a directory and doing it twice would put the user at your root directory, giving someone access to your entire file system.

You could use a regular expression to check for this type of thing right? Well, yes, but it wouldn’t be enough. Your regular expression would test for the “..\” sequence, but what happens if someone encodes the path with %2E instead of the “.”. Would your regular expression be smart enough to check for that? Probably not. There are a ton of ways to represent a path differently and you should use many different forms of validation. However, one of my favorite is to use the DirectoryInfo and FileInfoFullName” property. Creating a new FileInfo instance passing it your intended path will break the path down into it’s actual meaning. Once this is done, you can use the FullName member to obtain the canonicalized path. As a matter of completion, here is some sample code to get you started:

public FileStream OpenFile( string fileName )
{
string fullPath = string.Format(@”C:inetpubwwwroot{0}”, fileName);
string canonicalizedPath = new FileInfo(fullPath).FullName;
return new FileStream(canonicalizedPath, FileMode, FileAccess);
}

Another option available is to use the Path class as follows:

public FileStream OpenFile( string fileName )
{
string fullPath = string.Format(@”C:inetpubwwwroot{0}”, fileName);
string canonicalizedPath = Path.GetFullPath(fullPath);
return new FileStream(canonicalizedPath, FileMode, FileAccess);
}

This performs the same work under the covers without creating a FileInfo instance.

This example does not explain everything that a dilligent coder worried about security should do to secure this method, but it should demonstrate the usefulness of the FullName member in validating file paths.

Universal Identity a Bad Idea

In a day and age when you are either griping about security or banging out articles on how to increase code security, it’s hard to believe what I saw with my own eyes today. A large and well-known website was looking for a developer to create a universal registration and login service much like Microsoft Passport. The specification called for “seamless integration capabilities into any given website.“

On the surface, these types of services seem like a wonderful idea that prevents someone from having to type in their personal data from one site to the next. Instead, the user would click on a “sign in” button very similar to the .NET passport, they would enter their credentials and data you decide to share with a vendor is magically shared with this site. Microsoft passport requires a rather interesting partnering process in order to get passport authentication on your site. This is supposed to prevent malicious sites from just implementing the “sign in” button and taking your data when you don’t know better.

The problem comes with “seamless integration” and forged sites. It should come as no surprise that Microsoft also has methods that allow passport screens to be thrown into your website’s layout making the login process seem more seamless than redirecting to the passport website itself. This is a very dangerous idea, however. Think about the scenario where you find a gadget you just have to have and, guess what, it’s on clearance for 25% off on this site. You decide to “register” on this site by clicking the login button. The familiar login screen pops up and you enter you r login information.

Have you spotted the problem yet? A crafty individual could create this site that has the same look and feel as the login website. Instead of allowing you to log in as you thought you might, the malware could display an error that would have you believe the site just isn’t working at the moment. No big deal, you go to another site and forget all about this site. The problem is that you have already transmitted your username and login information to this site and that information is now in the hands of an identity thief, and gives a stranger access to any site that uses your login information.

I remember watching a movie (I think it was “xXx“ with Vin Diesel) where a guy drives up to valet parking and hands over his keys. The valet then proceeded to steel the guy’s car. When it comes to embedding a universal login “block” into any page, it just isn’t safe. Anyone can mock up the interface and make it look identical to the login pages that you know and trust. Before you realize what you’ve done, you’ve given someone the “keys“ to any site that uses your login. Personally, I don’t use the same password in any two places. I certainly don’t like the idea of logging into a website just because their login block looks like something I trust.

Keep this in mind the next time you hit eBay and click the passport “sign in” button.

Post Navigation