I've started up work again on the OWASP .NET ESAPI. Since a few months ago, when I translated the OWASP ESAPI from Java to C#, I've decided to change course a bit.

Java and .NET are architecturally and semantically similar - a lot of the direct code translation I did could be automated. But they are drastically different platforms. ASP.NET has a lot more security functionality built-in around authentication, authorization, and user management (Forms Authentication, the RoleManager, and the Membership API, respectively). Including a whole new user model makes sense in the Java ESAPI because JEE doesn't give you APIs for the typical web site security architecture. ASP.NET does, and so re-inventing the wheel has become low priority.

Instead, I am going to focus on what I think will be helpful to ASP.NET developers. The .NET ESAPI will continue to mirror the Java ESAPI. But I'd like to spend my time extending rather than aligning, because there are some big opportunities to improve ASP.NET security.

Here's a list of things I'd like to build:

  • Web Controls that can validate and encode data. Web controls are central to ASP.NET (at least pre-MVC). ValidatorControls can be attached to most regular controls – why combine them into a "SecureControl"? While we're at it, let's make it easy by solving some common validation problems through regular expressions. Also, it's a shame that we still haven't addressed data encoding issues more cleanly than this. Integrate AntiXss and AntiSamy.NET into the control output!
  • A web.config file that contains default secure settings, with directions and discussion of risk. This could replace the default web.config file.
  • Cross-site request forgery prevention. ViewStateUserKey isn't enough – perhaps use .NET CSRF Guard.
  • Fix the default ASPNETSESSIONID session cookie to support regeneration and the secure property. Find out how to uproot the plumbing and make it seamless for everyone else.
  • Several other small fixes and gotchas that I'm sure I'll think of after I hit publish.

I'd also like to polish some things that already exist:

  • Make horizontal and vertical authorization rules easy to integrate into any application. How about instrumenting reads and writes in data-bound controls with authorization checks?
  • Make a simple cryptography library for .NET. It must be possible, but I still haven't seen it. Let the user worry about a password, and securing that – the library does everything else.

Some things I won't be looking into anytime soon:

  • A new user model for ASP.NET for performing authentication and authorization. See above.
  • Error handling, logging, exception management. See the Enterprise Library.
  • The implementation of encoding for different contexts. See AntiXss and AntiSamy.NET

Overall, I'm hoping to solve problems rather than follow a spec. The OWASP ESAPI is great and growing, and I think it's time that the OWASP .NET ESAPI do the same.

I'll be travelling to various OWASP Chapters in the next two months (Columbus, Buffalo, Denver, Boulder) to talk about the OWASP .NET ESAPI project. Hopefully I can drum up some support so that we can get some great ideas and the great minds to build them. If you reading and are interested in helping or have some feedback, please leave a comment and let me know.

Posted by Alex | 1 comment(s)

There’s an axiom in the appsec community - “all input is evil”. Every piece of data sent by the user may be teeming with virulent host compromising attacks, and that you better validate ANY and ALL user-modifiable parameters or your computer will explode in a mushroom cloud of buffer overflows.

There's a common misstep that people make when figuring out how to fix these issues.

“Is there a method I can use to validate all my data coming in?”

Well, it turns out that you can’t. Sorry. Each piece of data needs to be validated separately.

Phone numbers need to look like phone numbers, usernames need to look like usernames, uploaded images need to look like uploaded images, and there isn’t any method out there that’s “one size fits all”.

Input validation isn’t for wimps.

Posted by Alex | with no comments
Filed under:

Rudy and I did a Fishbowl Talk at TechEd, where we spoke extemporaneously about whatever was on our mind that week. Check it out here.

Posted by Alex | with no comments

Self-proclaimed "alpha-geekess" and all around nice person Rachel Appel has given me a virtual shout-out on her blog.

http://www.rachelappel.com/2008/07/17/YesItrsquosThatEasyToGetHacked.aspx

I guess our presentation at TechEd was good enough to get me labeled as a "security expert" whose screencast needs to be watched by "every single developer and every sys admin". Thanks Rachel!

Posted by Alex | with no comments

Since my demo at TechEd was besmirched with a few technical difficulties, I decided to record a screencast and post it to my blog. Enjoy!

Posted by Alex | with no comments

ViewStateUserKey is not a completely effective mitigation against Cross-Site Request Forgery. It doesn't work for non post-backs (I.e. GET requests), and it doesn't work if the ViewState MAC is turned off.

In several different places, we see a piece of advice repeated - use the ViewStateUserKey property to prevent One-Click Attacks. Often, this piece of advice is accompanied by the following code:

void Page_Init(object sender, EventArgs e)

{

ViewStateUserKey = Session.SessionID;

}

What exactly does this code do? To understand it, we first need to look at the ViewState mechanism itself. The ViewState is an ASP.NET mechanism used to persist the value of web controls between post-backs. This allows a lot of the drag and drop, UI-driven ASP.NET architecture to function "auto-magically" by serializing and de-serializing data automatically on the fly.

The ViewState is encoded and stored as a hidden field. This introduces security issues, because the value is under the control of the client. There may be a value stored in a field that you do not want someone to see and modify, like an admin-only control with the visible property set to false.

ASP.NET helps us out by introducing two mechanisms to help protect the ViewState. ViewState MAC prevents tampering with the ViewState by introducing a separate Message Authentication Code that is verified when the ViewState is submitted. ViewState Encryption protects the ViewState confidentially by encrypting the ViewState value. By default, the ViewState MAC is enabled, and ViewState Encryption is not.

The ViewStateUserKey property is an optional addition to the data used in ViewState MAC calculation. If that value changes between post-backs, the ViewState MAC calculation will fail and the page will cause an error.

When we set the value of ViewStateUserKey to something associated with a particular user (like a Session ID or a Username), we are making sure that the ViewState is valid only for that user.

Back to One-Click Attacks. One-Click Attack is sometimes incorrectly referred to as Microsoft's name for Cross-Site Request Forgery. However, this is not entirely correct.

One-Click Attacks refer to CSRF attacks that use a malicious ViewState to perform the request. Because web forms developed with ASP.NET use ViewState for post-backs, the attacker can perform the post-back they want the user to perform unknowingly, and record the ViewState. Due to the way that ASP.NET ignores HTTP verbs when using Request.Params versus Request.Form, and in web controls, this request can often be made via GET.

Example:

http://site/Default.aspx?__VIEWSTATE=%2FwEPDwULLTExOTcyMDExODNkZAShpi32DKvqCd4uvHuQ%2FmmnBcdY&TextBox1=<MALICIOUS_CONTROL_DATA_GOES_HERE>&Button1=Button&__EVENTVALIDATION=%2FwEWAwKEyYGZBwLs0bLrBgKM54rG3sCHijug9ibUUfHX808cCvcppg1i

This link can be used in a CSRF attack. It is then known as a one-click attack, because it uses the ViewState. This, however, is not:

http://site/DeleteUser.aspx?user_id=123456789

If the page is not a post-back (as in the case of a direct link), the ViewState MAC is never checked. Several ASP.NET applications allow you to modify data without submitting a form. Consider ASP.NET MVC - it doesn't even use post-backs.

Furthermore, the ViewState MAC can be disabled at the page level:

<%@ Page Language="C#" EnableViewStateMac="false"%>

or in web.config.:

<pages enableViewStateMac="false">

</pages>

ViewState MAC is often disabled for (perceived) performance reason, or (more likely) if there is some functionality in the application that causes the ViewState MAC to cause error.

This reminds of problems with Request Validation is ASP.NET - the mechanism works, sometimes. This can be dangerous, because people rely on it and can get burned. The solution is to write something similar to CSRFGuard from OWASP in .NET. I have a feeling that the newly resurgent OWASP .NET project will add this to their to-do list.

Posted by Alex | 2 comment(s)

Recently I developed a lab for our Writing Secure Code – ASP.NET training course where students modify Hacme Bank to run in Partial Trust rather than Full Trust.

A lot has been written about Partial Trust. It's not going to solve every security problem, but it's a smart thing to do. I wanted to show students that it was easy to take an existing application and get it to run with only the privileges it needed.

Turns out, there is more than one way to skin a cat. And, depending on your architecture, you may be spinning your wheels needlessly, as I learned the hard way.

Hacme Bank is based on the older .asmx web service architecture, with the web front-end calling a service layer, which calls the database.

If we configure the site to run in the default Medium Trust level, it does not have access to the Hacme Bank web service (a WebPermission error is thrown).

After a few hours of tinkering, reading, debugging, and throwing my innocent wireless mouse across the room (my preferred method of stress management), I discovered a couple of different methods that I could use to get this working. Thanks to Dominick Baier and Rudolph Araujo for seeding the clouds of this brainstorm.

The four options are:

  1. Set the originUrl attribute in the trust element of the web.config file
  2. Create a new custom trust level
  3. Partition the privileged code into an assembly and install in the Global Assembly Cache
  4. Partition the privileged code into an assembly and create a new custom trust level

And, for those of you who aren't into reading longish blog posts, here's a summary of what I found:

Approach

Pros

Cons

Set the originUrl attribute in the trust element of the web.config file

 Really easy

Only works for web permissions (like calling a web service)

Create a new custom trust level

Only necessary permissions are granted

All code runs with the extra permissions

Partition the privileged code into an assembly and install in the Global Assembly Cache

Only a small amount of code gets elevated privileges

The code that gets elevated privileges runs in Full Trust

Partition the privileged code into an assembly and create a new custom trust level

Only necessary permissions are granted and only a small amount of code gets elevated privileges

Difficult

 

Now for some background:

1. Set the originUrl attribute in the trust element of the web.config file.

originUrl is an optional attribute that punches a hole in medium trust, allowing web connections to hosts defined by a regular expression. This is used to facilitate exactly what we need – connecting to a web service at an arbitrary location.

This is implemented by an entry in the web_mediumtrust.config file:

<IPermission class="WebPermission" version="1">

<ConnectAccess>

<URI uri="$OriginHost$"/>

</ConnectAccess>

</IPermission>

Besides making this lab a little too easy, the originUrl attribute is limited to web permissions and is not useful for different permission elevation scenarios such as accessing the registry or using reflection.

2. Create a new custom trust level.

A more flexible approach is to create a new trust level. Usually this is done by copying over one of the policy files and adding the necessary permission. A good description is available at the Patterns and Practices site here.

While this approach gives us the tools to add arbitrary permissions to the code base, it doesn't exactly follow the principal of least privilege, because all of the code in the web site is granted the permissions, rather than just the code that requires them.

3. Partition the privileged code into an assembly and install in the Global Assembly Cache.

In order to segregate duties and reduce the overall privileges granted, we can rip out the code that needs permissions and throw it in to a new assembly. This is also known as sandboxing. All code that can run with low privileges is in a very low privilege environment, and is given limited access to higher privilege functionality. This approach has some similarity with the Silverlight security model and the security safe critical attribute – I'll blog about this later.

Once we have our privileged code in a separate assembly, we need to configure our environment so that the privileged code can be accessed safely. First, the privileged assembly should be decorated with the AllowPartiallyTrustedCallersAttribtue, strong nam signed, and (in this case) installed in the GAC. To protect the code from being accessed by other classes, we can add a Code Access Security demand that will prevent access by all but the required classes. We have a few options here:

  1. Use a StrongNameIdentityPermission. If we strong name the ASP.NET application (running with partial trust), we can verify the strong name in the privileged assembly. This, unfortunately, isn't as easy as you might think. It's not supported in Visual Web Developer Express 2008, and so it wouldn't work for my lab. In the full version of Visual Studio, we can strong name the assembly by adding a compiler option however this means that we need to create a new trust level. This is because modifying compiler options requires unmanaged code permissions. The suggestion is to use this modified trust level while debugging, then to deploy the assembly as a pre-compiled, strongly named assembly, with the unmodified trust level. I feel that this is probably a bad design choice – there should be a simple option for the Visual Studio built-in web server to perform strong naming on the ASP.NET code to support this type of scenario in medium trust. One note - Dominick points out that strong naming doesn't scale particularly well, since more than one strong name cannot be demand (this will result in an AND condition).
  2. Use the UrlIdentityPermission. I wasn't able to get this working, but theoretically you could restrict the caller's file location to the URL file://c:\directorytowebapp\*. Not sure if anyone has tried this successfully, but if you could, you may get around some of the difficulties around strong naming.
  3. Use a custom permission. This may be the most natural way to express the demand and justify the extra effort in creating a new permission, which isn't trivial.

Note that these permissions do not prevent Full Trust callers from accessing the assembly. See this blog post for a description of why "Full Trust Means Full Trust"

One major problem here is that the assembly will run in the GAC with Full Trust. This is a fairly significant privilege escalation, even for a very small piece of code. However, we can do better.

4. Partition the privileged code into an assembly and create a new custom trust level.

In this approach, we will combine approaches 2 and 3 to get the best of both worlds. We partition the code into a privileged assembly and the low privileged web site, taking into account the precautions discussed in the previous step. Then, rather than installing the code in the GAC, we create a custom policy file (as described in approach 2) and add a new code group which refers to our privileged assembly, and assign that code group a permission set that has only the requisite permissions. This approach is described in the hyperbolically-titled but otherwise helpful article "Never Write an Insecure ASP.NET Application Ever Again" and in Dominick's book (pages 330-332). One thing to note here is that you don't use the .NET Framework Configuration tool to set the security policy for the privileged assembly – you want to use the ASP.NET policies in the .config file. Boy, I wish I had known that a few days ago.

This approach gives us the best shot at least privilege, and is extremely flexible. However, it's probably not appropriate for the couple of hours that the students have to complete the lab. Hopefully in the future we'll get an easy way to a) secure a privileged assembly with a simple permission demand and b) create a new trust level based off medium trust and c) create a new code group in the custom trust level based on the strong name of the privileged assembly.

Posted by Alex | with no comments

Sent via OWASP ESAPI mailing list

The ESAPI.NET project is now available on Google code (http://code.google.com/p/owasp-esapi-dotnet/).

The ESAPI.NET project is an implementation of the original ESAPI code base (http://code.google.com/p/owasp-esapi-java/) in C#, using the .NET platform.

Some notes on the implementation:

1) The code uses nUnit for unit testing. Currently, all unit tests pass and there is >80% code coverage.

2) The code uses the built-in .NET documentation format. Sandcastle (http://blogs.msdn.com/sandcastle/) will be used to compile the documentation.

3) The code follows the .NET/C# coding conventions discussed here: http://www.irritatedvowel.com/Programming/Standards.aspx.

4) For unit testing purposes, the code uses the HTTP Interfaces and Duck Typing library described here: http://haacked.com/archive/2007/09/09/ihttpcontext-and-other-interfaces-for-your-duck-typing-benefit.aspx. Hopefully we can use Microsoft code in a future release, as I believe that the ASP.NET MVC framework will use similar constructs (the author of the blog above is the project manager for ASP.NET MVC).

5) In general, the code is more of a direct translation of the Java implementation than a re-write from scratch for the .NET framework. Future work may include more .NET specific security functionality as well as implementations leveraging existing .NET security mechanisms.

6) The code passes its unit tests, but probably has some kinks to work out based on actually applying the library to an ASP.NET application. The next step will be to build a sample ASP.NET application that uses the ESAPI features.

Please feel free to provide feedback. Thanks in advance!

Alex

Posted by Alex | with no comments

Back in my days at Cal, I worked part-time as a "Data Entry Specialist" (uh, typist) at the Earthquake Engineering Center Library in Richmond for a couple extra bucks. I typed abstracts into a database - nothing too glamorous, although it did pay for more than a few IB's Hoagies and Top Dogs for a hungry EECS student.

Beyond picking up a few pounds, I also picked up some tidbits from technical journals and abstracts about the process of engineering for disasters, like earthquakes. There were some common themes in these articles - from what I could tell in between the mostly incomprehensible (to me) dialogue on issues like torsion analysis and plasticity versus elasticity.

  • Studying failure is the best way to master compensating factors. 
  • Safety should not preclude efficiency.
  • Disasters occur when poor engineering meets unexpected circumstances.

What we as security practitioners do is roughly comparable to earthquake engineering, and these themes are just as true when discussing SQL injection as inelastic oscillations. A crumbling structure may be more dramatic than a hacked system, but security folks' specialized knowledge is highly prized because it removes mystery from tragedy and derives lessons for the next time. Earthquakes are unpredictable - like attacks. We must study what has happened in the past to understand how to protect ourselves in the future.

Looking back in this New Year is a good opportunity to consider what has worked, and what hasn't (I will post on my experiences with this later). I think overall software security specialists could collaborate more, interact more, and gain from each other's real-world experience. However, because security knowledge can be sensitive, it may not be as simple as submitting every piece of analysis to the local college intern to enter into a world readable database.

Posted by Alex | with no comments

Let's suppose I wanted to steal a car. One way I could do it is to buy a car, make a copy of the key, sell the car to a victim, tail them and then drive the car away with my copied key while the unsuspecting victim is off purchasing a Frappucino.

Maybe this wouldn't work in the paper-and-ink real world, but it's actually pretty easy in the virtual one. It is analogous to the web application attack called Session Fixation.

Session Fixation is a vulnerability caused by an attacker forcing a victim to use a known session ID. Once the victim has authenticated, the attacker can hijack the session using the known session ID. There are multiple ways an attacker could get a victim to use a known session ID. For example, the attacker could entice a user to respond to a phishing email by clicking the following link:

https://www.example.com/index.html?sessionid=[knownvalue]

Note that this link appears to come from the correct domain, and would not cause an SSL error message. The caveat is that the application must accept the session ID as a get argument.

Additionally, an attacker could access a shared terminal (in a library, or a café) and visit several vulnerable sites, collecting session IDs, without authenticating. They could then continue to attempt to access these sites and see if the session has been authenticated (while keeping the session from expiring) until a victim logs in to a site using the shared terminal.

The most efficient way to curtail this vulnerability is to regenerate the session ID when a user logs in. It renders the known session ID useless. Let's take a look at how this applies (or doesn't!) to Java and .NET.

Java

In Java, there is not well-supported programmatic access to the JSESSIONID cookie. You can't change the name of the cookie or set cookie properties (such as HttpOnly) very easily. However, in Java, it is possible to invalidate and recreate the session (not the session ID, necessarily) using the following code:

session.invalidate();

session=request.getSession(true);

This is also the OWASP recommendation, although it isn't explained in much detail on the site. Note I said that this does not regenerate the session ID necessarily. Looking at the comment thread for this blog, it appears JBoss doesn't regenerate the JSESSIONID using this code. I haven't confirmed this myself, but there is no guarantee in the Java specification that the session.invalidate will actually regenerate the session ID if it is recreated using request.getSession during the same request. So be careful and test if you use this method - I tried the code with Tomcat, and it worked, but I can't vouch for the other Java application servers.

In addition, you have to manually copy over all of the current data in the session. This may be necessary when designing an experience like Amazon.com, where you can add things to your cart before you log in. You would have to make sure that this information is persisted in the new session after authentication. This is an inconvenience, but is certainly doable.

ASP.NET

ASP.NET may have less of a problem with session fixation if you are using the ASP.NET Forms Authentication mechanism. A separate Forms Authentication token will be used after authentication, and since the attacker cannot set this value before the victim authenticates, it prevents a full-scale session fixation attacker. However, while this makes the ASP_NETSESSIONID less useful, it doesn't entirely negate the threat of session fixation.

For instance, depending on how the application is designed, an attacker could use his or her own Forms Authentication token along with the hijacked session to access data from the hijacked session.

ASP.NET does not directly support functionality to regenerate a session ID. See the documentation regarding the issue here. There is a not-so quick and dirty way to do it by setting the ASPNET_SessionID value to the empty string and redirecting so that the value is regenerated.

I think both platforms need to re-examine the fact that session ID regeneration is an important security feature, and implement simple APIs for regenerating the session ID without creating a new session. Perhaps they should even perform session regeneration on login and privilege escalation by default, creating a pit of success. I think this points to the fact that session mechanisms in web applications have a huge, but often underappreciated, security relevance.

Posted by Alex | with no comments

HttpOnly is an HTTP cookie property originally developed by Microsoft that makes cookies "non-scriptable" - any attempts to access the cookie value through JavaScript will fail.

HttpOnly mitigates the threat of session hijacking through cross-site scripting, but only partially - more on this later.

Until recently, HttpOnly was only supported in Internet Explorer 6, SP1 and up. Now, however, the latest version of FireFox supports HttpOnly.

It's easy to specify a cookie as HttpOnly, it raises the bar for an attacker, and it doesn't affect most regular functionality. So why not set your session identifier cookies to HttpOnly?

Well, if you're developing ASP.NET, PHP, or Ruby on Rails web applications, you're in luck. Just set a property, or change a config file, and you're golden.

But what about J2EE? Well, there is no HttpOnly property supported in the Cookie interface. You can set your own cookies to be HttpOnly:

response.setHeader("Set-Cookie", "originalcookiename=originalvalue; HTTPOnly");

But that doesn't work for JSESSIOND, the J2EE session identifier, since it is handled by the container. So, you're out of luck. Or are you?

<Pause for commercial break>

</Pause for commercial break>

Welcome back. After fiddling around with HacmeBooks, the Foundstone Free Tool for demonstrating common web application vulnerabilities in Java, I was able to get the HttpOnly property set on the JSESSIONID cookie.

Here's the code below (from a ServletFilter):

// Check if this is where the JSESSIONID is being set (assuming that JSESSIONID is the only cookie used)
if (response.containsHeader("SET-COOKIE"))
{
    String sessionid = request.getSession().getId();
    response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; Path=/HacmeBooks; HttpOnly");
}
// Continue down the Filter Chain
chain.doFilter(request, response);

This code is far from ideal - it essentially replaces the JSESSIONID cookie set by the server, so any properties (path, expires, secure, etc.) that the server sets have to be specified in the code. It also won't work if other cookies besides JSESSIONID are being used (you could fix this by looking at the request and making sure JSESSIONID isn't already set).

However, until Java gets around to supporting HttpOnly cleanly, this is the best way I could figure to set this property on the JSESSIONID.

*BONUS*

I mentioned that there are some people who have taken HttpOnly to task for being an incomplete mitigation for XSS.

Jeremiah Grossman talks about using the HTTP TRACE verb to get access to HttpOnly cookies in the reflected request.

pdp suggests that HttpOnly is meaningless because most attackers don't really care about session hijacking through XSS - there are more damaging attacks that can be leveraged through XSS.

RSnake points out that in FireFox XMLHttpRequest can be used to access the cookie and bypass HttpOnly. Additionally, some older, obscure browsers (IE5 on Mac, WebTV) choke and die on the header instead of safely ignoring it.

Amit Klein suggest several different methods, including some mentioned above, for bypassing the HttpOnly protection.

I think for all of its shortcomings, HttpOnly is still a good idea. The bugs will get worked out, and everyone will be a little safer.

Posted by Alex | 2 comment(s)

ASP.NET ValidateRequest is a security mechanism designed to prevent cross-site scripting attacks in ASP.NET applications. It looks at data in the HTTP request parameters, and issues an error if it finds anything that is "suspicious". And, for the most part, it works fine. But, like many security technologies, there are two big problems - false positives and false negatives. First off, let's take a look at how ValidateRequest works. Using the .NET Reflector tool, we can see the attack detection algorithm in the IsDangerousString method of the CrossSiteScriptingValidation class, which is the crux of the ValidateRequest functionality:

This method looks for either a less than or ampersand character in the string. If one exists, it first checks to make sure it is not the last character (I'm not entirely sure why, but it seems this would only allow fairly benign strings). Then, if the offending character is a less than character, the method checks if the next character is a letter, an exclamation point, or a forward slash. If so, it is considered dangerous. Also, if the offending character was an ampersand, and the next character is a hash mark, the string is considered dangerous. This algorithm iterates through the string, stopping at each instance of one of these symbols.

Now that we have a good idea how this functionality works, let's examine why it isn't always ideal.

False Positives

ValidateRequest looks for anything that resembles HTML that code be used to execute script. Unfortunately, the detection technique can be a bit trigger-happy. Some strings that appear to be malicious are perfectly normal and expected. Examples:

  1. Rich text controls often use HTML characters for markup.
  2. XML in AJAX calls has been known to trip the ValidateRequest error.

Many people advise turning ValidateRequest off at the first sign of problems. The first Google hit for ValidateRequest is a link to an article from 2004 titled "Surviving ValidateRequest" discussing why it's not always in a developer's best interest to use the mechanism (although it does discuss the threats and countermeasures regarding cross-site scripting in the article as well). Here's a quote:

"Another problem with ValidateRequest set to true is that it is a rather broad and stupid protection, erring on the side of catching too much rather than letting something dangerous slide by."

OK, fair enough, simply disable ValidateRequest when it causes problems, and figure out how to prevent XSS by yourself in those cases. But something so strict that it chokes on regular input has got to prevent all bad input, right?

False Negatives

No one claims that ValidateRequest is perfectly effective in stopping cross-site scripting attacks. But what does it miss? From a recent blog post:

"ValidateRequest may miss some crafty inputs."

Well, what are these "crafty" values? One is mentioned in the article - an exploit which is mentioned in the Microsoft Security Bulletin MS07-040.

There is another, perhaps more common (and still unpatched) form of XSS which isn't stopped by ValidateRequest. It is known as HTML Attribute-Based Cross Site Scripting, according to Jeremiah Grossman. The attacker uses an HTML attribute to insert an event handler that causes a script to run.

ValidateRequest doesn't even attempt to look for this - there are no angle brackets required.

For example, take the following ASP.NET code:

This code is used to display a page which renders a link to an article on Wikipedia.

We can enter this value:


This will cause the following HTML to be rendered:

This will cause script to execute when the person moves their mouse over the link:

So we have caused cross-site scripting in spite of ValidateRequest being enabled. This is due to the fact that not all cross-site scripting attacks require the use of less than or ampersand characters. For example, consider what would happen if a parameter value was echoed directly in JavaScript (this can happen in AJAX apps). The results can be scary!

ValidateRequest is not a panacea. Instead, consider augmenting the functionality with stronger protection afforded by the Anti XSS library, and as always, implement and enforce strict validation.

Posted by Alex | with no comments

In ASP.NET 2.0, the Protected Configuration functionality can be used to automatically encrypt and decrypt sections of the Web.config file. This is useful for keeping sensitive data like connection strings and cryptographic keys secret from internal personnel who require access to other areas of the configuration file.

Web.config files contain application level configuration, and they are often deployed with the code, from development/testing/staging environments to production environments. Because secrets like connection string should be different in production, the Web.config file has to be modified. However, another piece of functionality, the configSource attribute or the appSettings element, allows configuration sections in Web.config to be located in external files.

These two functionalities work just fine together. This makes deployment easier because secrets can be stored statically and encrypted on each machine, or just the production machine, plus the Web.config file doesn't need to be modified each time.

Example

connectionStrings section in Web.config (staging and production) refers to external source

 

Staging connection string defined in connectionString.config (staging)

 

Production connection string defined in connectionString.config (production)

 

Encrypt the connectionStrings section for the application (production) using aspnet_regiis

 

Encrypted connectionStrings setting connectionStrings.config (production)

 

Now, the Web.config file can be deployed without overwriting the connectionStrings attribute, and the production database password is encrypted! It's the best of both worlds - security and convenience playing nicely. Just remember not to deploy the connectionString.config file.

 

Posted by Alex | with no comments

A vast amount of server-side development is J2EE. Huge, multi-national corporations run on it exclusively. But, it wasn't always that way….

Back in the early days of Java, the client-side Applet was king. The partnership with Netscape thrust the Java onto the world stage. Early press releases all focused on the web experience provided by Applets.

But there was this pesky security issue - due to the fact that Java Applets are distributed and run through a browser, they can encounter some nasty code on the web. In order to deal with evil code, Applets are run in a Sandbox with limited permission. However, Applet developers said that this Sandbox was too restrictive. No access to the file system, or the clipboard, or native code, or really anything useful.

So, in Java 1.1, you could digitally sign applets so that they were trusted. This would give the Applet full permission, and theoretically users would manage their own trusted key store.

In Java 2, Sun added Certificate Authorities to the Applet specification, so that anyone with enough money to pony up could create a universally trusted Applet. This was tempered by the fact that now the user could create a policy to restrict these signed Applets to a specific set of permissions. So signed Applets ask for permission to run, and are granted AllPermissions, unless there is a specific client-side policy for that Applet, which takes precedence. But no one likes configuring security policies, do they? Remember, this is the unwashed masses of browser users, and they don't know a Java policy file from a can of Shinola.

Enter the Java Plugin, which now handles Applets for most browsers. In the previous 1.3 version of the Plugin, Applets signed with invalid certificates (self-signed or expired) would simply fail to load. If the signing certificate was valid, the user got a dialog box asking whether to run the Applet.

In the Java Plugin 1.4, the behavior was changed to load Applets even with invalid certificates. The only difference between Applets with valid signatures and invalid signatures is the warning messages.

Applets signed with an invalid certificate:

Applets signed with a valid certificate:

To me, this represents a tremendous over-simplification. Signed Applets now basically use the same, all-or-nothing security model as standard executables!

The error message for an unsigned .exe file (in IE7):

At least this has a red shield (bad) rather than an orange shield (maybe bad)!

Nowadays, in addition to the huge amount of server-side Java development, there is Java on mobile devices, smart cards, and entire operating systems in Java. But the original thing that made Java tick – the Applet – is becoming less and less relevant every day, and I can't help thinking it's due to the fatally flawed security model which has now almost completely lost its teeth.

References

Java Technology: The Early Years: http://java.sun.com/features/1998/05/birthday.html

Java 2 Platform Security: http://www.informit.com/articles/article.aspx?p=433382&seqNum=2

Using JDK 1.1 Signed Applets with Java Plugin: http://java.sun.com/products/plugin/1.2/docs/signed.html

Java Security, Evolution and Concepts: http://java.sun.com/products/plugin/1.2/docs/signed.html

 

Posted by Alex | 2 comment(s)

Reading articles, browsing marketing materials, and listening to presentations about application security, you hear variations on a theme:

"Input validation is absolutely critical to application security, and most application risks involve tainted input at some level." – OWASP

While I don't think authors overstate the importance of problems stemming from invalid data, I have noticed these discussions gloss over two key points.

  1. Input validation is only part of the problem. Output validation is important as well.
  2. Validation (in the general sense) has two distinct concerns: validation and sanitization.

Input validation is only part of the problem. Output validation is important as well.

All data input from an untrusted source should be validated. If you enter a blog comment, I want to make sure it isn't empty, it is less than 500 words, and it isn't spam and won't get my readers RickRolled. However, as that data is output from the web application, it should be validated as well. Here's why:

Think about cross-site scripting – we really want to prevent tainted data from exiting the system to the rendered web page on the client. This occurs when the data is output, not input. SQL injection is also tainted data exiting the system (through a SQL query) and parameterized queries are output validation. And since these different validation rules might process the same data (say, a blog comment that is reflected in a subsequent page for approval and then stored to the database), it makes more sense to validate the data upon exit, rather than on entrance.

It's like international air travel – you pass through customs at your arrival airport (output), because at your departure airport (input), they don't know the rules for what's allowed and what isn't.

Thus, I propose that "Data Validation" be used in favor of "Input Validation" as a more accurate (although less precise) term to include input and output validation.

Validation (in the general sense) has two distinct concerns: validation and sanitization.

Validation is a Boolean operation which gives a yes or no answer to the question "Is this data acceptable in the current context?"

Sanitization (which includes encoding, escaping, and stripping) refers to transforming data in some manner so as to make it acceptable in the current context.

These two approaches can be used independently or in concert and the correct way to perform these operations from a security perspective is highly dependent on the context in which they are used.

So validation is (usually) both validation and sanitization.

Another issue which might be brought up in the subject of validation is canonicalization, which is a separate issue that warrants its own future blog post.

Just some food for thought when designing validation mechanisms – it's not all yes or no decisions, and it's not all at the front door.

Posted by Alex | with no comments
More Posts Next page »