Archive for the ‘Security Testing’ Category

How safe is the safecrt handling of formatting strings?

April 25th, 2008 by

One rule of thumb in c/c++ is that you should never let the user be in control of a formatting string. This has been recognized as a security bug for years, and one that has been mostly cleaned up since it is so easy to identify and fix. With visual studio 2005, Microsoft released a safer version of the crt — functions that end with _s to tell you that they are security enhanced. So let's say you are being a good security citizen by using the safe-crt …. can a format string vulnerability (where the user controls the format string) still be exploited?

The MSDN docs don't really have the answer. A cursory reading of the “security enhancements in the CRT” page as well as others may lead you to believe that format string vulnerabilities are a thing of the past. One example shows a call to 'sprintf_s(buf,_countof(buf), “%s”,NULL)' and remarks that this results in a runtime error. Looks like they do some kind runtime-validation. However, unless they added magic pixie dust to their compiler that sends cosmic rays from outer space to fix up malicious format strings at runtime, it isn't really possible to have strongly-typed printf-style format strings in C.

So let's investigate how far the parameter validation will get you. Here is a little sample program I wrote to send nasty format strings to sprintf_s:


#include
#define OUT_SIZE 0x1000
int main(int argc, char** argv) {
char * out = new char[OUT_SIZE];
sprintf_s(out, OUT_SIZE, OUT_SIZE, argv[1]);
printf("%s\n", out);
return 0;
}

So let's try this with a couple of format strings:

Input: "%s"
Output: Error: ("Buffer too small", 0)

So far so good… but buffer too small?
What about just dumping stack variables?

Input: "%p %p %p %p %p %p"
Output: 00344FD0 00344FD0 0012FFB8 004019D3 00000002 00343728

Interesting… so looks like this type checking is not so robust after all. We've just dumped the stack.
Let's see if we can crash the program. Looks like there is a 0000002 on the stack… that probably won't appreciate being dereferenced.

Input: "%p %p %p %p %s"


Ok so we can crash the program. Can we do anything more interesting?
Let's say there was some interesting data somewhere in the program. To simulate this, I'll put my bank account number on the stack with the following line of code at the beginning of “main” “volatile char * bankAccount = “Account#123-456-7890″;” (the volatile helps convince the compiler not to throw it away since I don't use it).

Now when I call the function with the right input, I can dump my bank account number:

Input: test.exe "%p %s"
Output: 00344FD0 Account#123-456-7890 00344FD0

Ok but nobody really cares about Denial-of-service and Information-disclosure. Those are sooooo pri-3. Can we use take over the machine? As everyone knows, the hacker's favorite format string character is '%n'. '%n' writes the number of bytes written so far to the param from the stack. Let's try a '%n':

Input: test.exe "%p %n"
Output: Error: (state != ST_INVALID)

Blast! Foiled! It turns out Microsoft decided that %n was too much power, and that we mere mortals couldn't handle it. Good for them. There is an override, but it turns out to not be available using the Safe CRT. The moral of the story? The safe crt is a wonderful and powerful tool to help prevent buffer overruns. But there is no excuse for letting a user control a format string.

Handling Unicode when marshalling from .Net to a platform invoke

April 22nd, 2008 by

By default, the .Net runtime will marshall a string (and files in a value type) as a LPStr to a platform invoke (p/invoke) function. By default the .Net framework and runtime handles strings as UTF-16. That's two bytes representing a single Unicode 'code point', and more familiar, a single character. An LPStr on the other hand, is an ANSI character, so in order to convert, the runtime will perform a best-fit conversion to the classic windows-1252 code page. This conversion is well-documented here:

http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WindowsBestFit/bestfit1252.txt

This might not be so surprising to people in tune with Unicode, but it's can lead to huge security problems when security filters are at risk. For example, if you're performing HTML filtering or file canonicalization, you need to perform so after the conversion to LPStr.

This default marshalling behavior is documented at: http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute(VS.71).aspx

To properly and more safely deal with this, you can use the MarshallAsAttribute class to specify a LPWStr type instead of a LPStr. For example:

[MarshalAs(UnmanagedType.LPWStr)]

Because LPWStr is a pointer to a null-terminated array of Unicode characters, this ensures the Unicode code points are preserved across the marshalling.

Open redirects – what’s the problem?

March 2nd, 2008 by

Been getting this question a bit lately. First off, what's an open redirect? It's a function in your application which sends the user to some other location. The redirect could be a response from the server, such as an HTTP 301 or 302 response code, or a META redirect. The redirect can be delivered in several forms, the important part is that when an attacker can control the redirect location, they can exploit it for nefarious purposes – usually this means spam or phishing attacks.

For example, your application takes a request from the user, maybe it's a GET request for a certain page. Included in the request is a value indicating the location where the user should be redirected once they've finished on the page. So, the user requests a page like:

http://somesite.tld/page.aspx?name=value&returnUrl=http://somesite.tld/referringpage.aspx

As you can see, the returnUrl takes a value of the redirect location. Then your code acts on it somewhere by redirecting the user with something like:

Response.Redirect(returnUrl);

Spammers and phishers love this, it gives them good camouflage. For example:

http://somesite.tld/page.aspx?name=value&returnUrl=http://evil.tld/installMalware.bad

Now imagine the spammer has crafted up a nice email that looks like it originates from somesite.tld, includes all the logos, fonts, etc. They coerce the victim into clicking this link by saying something like “your account needs immediate attention” or “you've won 500 points”. User clicks the link, gets redirected to evil.tld, and may not realize that the domain has switched before they say Yes to install the thing that the spammer wants them to download.

Tricky, right. In fact this is a favorite of spam, malware, and phish, next to the old XSS bug.

What's the solution
Well, simply, don't redirect openly, rather, implement a SafeRedirect() function that looks something like:


public static SafeRedirect(string url) {
// check that protocol is either http:// https:// ftp:// or other specific protos you want to allow
// check that domain is in fact yourdomain.tld
// If these checks pass, then you can go ahead
Response.Redirect(returnUrl);
// If the checks fail, you can try to clean up the URL, but probably best to just fail and redirect to a safe landing page
}

That's about all there is too it.

Using ASP.Net session handling with secure sites (set the secure flag)

February 4th, 2008 by

One of the common problems we see with many web applications is reliance on ASP.Net sessionID without understanding the security ramifications. ASP.Net provides web developers with a powerful means of tracking user state and identity with very little coding. Rather than creating your own custom authentication cookie, handling the trickiness of forms auth or mapping your cookie to a Windows identity, password policy implementation, not to mention creating server objects to store the state for a given user, ASP.net does it all for you.

ASP.Net offers two methods of tracking session state- URL or cookie. URL based methods are used in cases where it is expected that some users will have disabled cookies and still need a server-side session to track state. This has become less common as more and more of the web relies on cookies. In addition the URLs look ugly and are considered unacceptableby many usability gurus.

The second method is a cookie sent as a header to the server. This cookie is sent over HTTP or HTTPS and is used by ASP.net to link an incoming request to the server-side state. So you are running your site on SSL, where is the problem? By default, the SessionID is just a cookie the browser sends it when making any response to the domain. If you go to https://yourapp/application, you will be sent a cookie over SSL that I cannot see. If I e-mail you a link to click for http://yourapp/application, I will see the cookie sent over HTTP as long as your server responds on port 80.

What you want to do is set the 'secure' flag on the cookie. You have many options for doing this: adsutil set w3svc/1/AspKeepSessionIDSecure 1 will tell ASP.net to mark the session cookie as Secure. When a cookie is marked as secure it will not be sent by the web browser unless the connection to the server is over https. You must be aware that the user will now have no session state if they browse to the site using http your application will need to redirect http requests to https in order to access the session state.

Is the ASP.Net session ID the only cookie I can protect in this way? No. You can use a web.config configuration to customize the security of all your cookies (http://msdn2.microsoft.com/en-us/library/ms228262.aspx). You will also be able to set cookies to be HttpOnly which adds its own element of security and is supported by newer browsers.

Finally, you can set both the secure flag and the HttpOnly flag for any other cookies you set programmatically through ASP.Net with http://msdn2.microsoft.com/en-us/library/ms228262.aspx.

A few other things to remember-

ASP.Net sessions expire after 20 minutes UNLESS a new request is seen. Otherwise they can remain until the server is recycled.

SessionIDs can be reused. When stored as a cookie the sessionID will go to any machine hosting the same parent domain. They will NOT have the server-side state though unless some clustering or back-end logic handles sharing state across servers. If you want to ensure that reuse does not happen, rather than using Session.Abandon you must overwrite the ASP.Net session cookie with an empty cookie value. To properly end a session or force a user to start a new one use Session.Abandon.

For more information checkout – http://msdn2.microsoft.com/en-us/library/ms972969.aspx

Whatever happened to?

January 16th, 2008 by

One of the most useful sites on the Internet was the Ports Database at http://www.portsdb.org

Unfortunately it went missing over a year ago and has not returned. The best alternative I have found is using the IANA list at http://www.iana.org/assignments/port-numbers and doing a manual search. Not ideal, but it works. Maybe we will put a little database up on this site in the future.

New risks for old credentials

January 16th, 2008 by

I was playing around with my Tivo this weekend and realized that many of the new features being offered on Tivo are handy but leave valuable information stored on your Tivo.

How so?

Well, Tivo now offers Amazon Unbox downloads, Yahoo Weather/Traffic, etc. All of these services require you to store your credentials on the device or on Tivo's website. Imagine what might happen if an attacker can break into the device and gather such information. With an Amazon account an attacker has access to any stored credit cards for purchases on the site. Even if an attacker cannot hack into your private network and break into the Tivo, what happens when the Tivo is put into the trash at the end of its life?

Web Services denial of service attacks – XmlTextReader

February 19th, 2007 by

Most Web Services I look at are built using the .NET Framework and ASP.NET. Today we’re seeing more with ASP.NET’s AJAX extensions but that’s a different story. Many developers choose to implement SOAP and XML as part of their WS solution, and in doing so can inadvertently open the application server up to DoS issues.

First there’s XML. When developers choose to implement XmlTextReader or XmlReader from the .NET Framework, they need to understand the behaviors of these classes. MSDN documents this quite well. I will usually do a quick code review to find implementations of these objects, because the issues can be identified a little faster through code than through testing.

XmlTextReader defaults to allowing external DTD’s to be specified. This leads to a whole enchilda of issues, and gives attackers a nice bit of control over the host server. Be sure to set the ProhibitDTD property equal to true. Furthermore, there’s no strict schema validation unless the developer implements one.SOAP is fine, but developers need to implement a custom SOAP extension to enforce strict schema validation. Otherwise it gets pretty easy for an attacker to abuse the WS by embedding things like:

  • large payloads
  • large number of elements
  • nested elements
  • malformed data

To name a few… Without strict validation, I’ve seen web services easily abused. For example, by sending a few large requests, it becomes trivial to consume memory on the host server which eventually leads to resource starvation. To learn more about implementing a custom SOAP Extension to tackle this problem, read the MSDN article:

http://msdn.microsoft.com/msdnmag/issues/03/07/XMLSchemaValidation/

To fuzz or not to fuzz web services…

January 13th, 2007 by

Is it worth the time to run input fuzzing tests against web services? When engaging a client for a security review I’m often the one to pose this question. Sure, why not… right? Well honestly there’s a more precise way to answer this question. First we really need to understand the goals of the security review, so a few questions are in order.

  1. Has threat modeling been done or is this my job?
  2. How much time and budget do we have for a security review?
  3. How complex are the web services? e.g. how many parameters do they take and in what format
  4. Are the web services written in managed code?
  5. Is user-input passed to unmanaged code?

Let’s take these answers from a common scenario:

  1. Yes threat modeling is complete
  2. We have about 2 or 3 weeks that you can use to test
  3. Very complex, they use WS-Security, take hundreds of parameters, some encrypted, using custom formats, SOAP, as well as embedded XML blobs
  4. Yes, they’re written in C# using the .NET Framework
  5. Some specific elements of user-input are handled by unmanaged code modules

Some things not obvious in these questions are:

  • that the client is highly interested in finding Denial of Service (DoS) issues
  • that millions of people will be using these Web Services whether they know it or not
  • that no input fuzzing has been done to date

With 2-3 weeks we could get a lot done in a security review focused just one the web services. It’s becoming clear that fuzzing input would be a worthwhile venture. We’ll likely turn up some DoS issues, possibly some unmanaged code issues as well. Since we have a decent timeframe, we’ll be checking for the following issues, not all of which fuzzing is good for:

  • elevation of privilege (EoP)
  • repurposing attacks
  • cross-site scripting (yes, even web services in some cases)
  • information disclosure
  • session replay
  • SQL Injection
  • DTD attacks
  • XML validation
  • script injection
  • repudiation
  • denial of service
  • buffer overrun

Fuzzing will help with some of these, so at this point the answer is yes, let’s do it. We’ll also be doing some code review, which is great for identifying issues such as DoS, XML validation, and DTD attacks quickly. And we’ll be studying the specs and architecture along the way to keep a clear understanding of the system and help identify repurposing attacks, which will be tested for confirmation.

Ok let’s go!

Internet Explorer whitespace-as-comment hack to bypass input filters

January 11th, 2007 by

When testing for XSS (cross-site scripting) issues, you often need to bypass filters and perform different sorts of encodings and other trickery. To be a good tester you also need to know how the browsers you’re concerned with behave differently. In Internet Explorer 6.0 there’s a behavior that’s allowed seemingly impassible input validation filters to be bypassed. Note that the issue is not the browser’s fault, it’s the fault of an improperly designed input validation mechanism on the server. Okay to illustrate the point.

You’re testing a web app that has an input field. Some script tags are allowed but <img src=”something”> is not. By replacing the whitespace with a comment, your code is accepted. When returned to the browser, IE 6.x, the comment is interpreted as whitespace and the code is executed fine. Test it out:

//Start HTML
<html>
<body>
<img/*comment*/src=”javascript:alert(’img tag’)”>
</body>
</html>
//End HTML

This trick can be useful for more than just bypassing filters…

IIS 6.0 %uNNNN unicode notation in the URL

January 10th, 2007 by

I do a lot of web app pen testing. Character encoding is always an important part of many input validation test cases. Some people don’t realize that IIS takes straight unicode notation in the URL by default. So you can pass in unicode characters just by typing the proper notation in ASCII on the URL. For example the following URL’s encode an “s”, a double quote, the Cyrillic small letter “о” which looks a lot like an “o”.

http://somesite.iis/query=unicode-character-%u0073
http://somesite.iis/query=unicode-character-%u0022
http://somesite.iis/query=unicode-character-%u043E

This is controlled by the following registry key and is enabled by default:

HKLM\System\CurrentControlSet\Services\HTTP\Parameters\PercentUAllowed

A Boolean value. If non-zero, Http.sys accepts the %uNNNN notation in request URLs.