Saturday, December 5, 2009

Appendix B • An Introduction to Web Application Security Figure

A Typical SQL Query

This is a common way of building queries—by concatenating the variable portions of the query with the static portions. With this example, the query is expecting a string from the browser, so it first builds the select statement with the initial leading single quote necessary. It then reads the post data from the request and appends the value specified in the "Search" parameter to the query. It finally appends the final trailing single quote it needs.

Let's look at the way various inputs affect this statement. Remember that the base query is:

Select patient_records from tblPatients where user_search='input

So if the data entered into the "Search" post data parameter in the request is:

123-22-4321

the query becomes:

Select patient_records from tblPatients where user_search=' 123-22-4321

Likewise, if the data entered is: Michael Balzary

the query becomes:

Select patient_records from tblPatients where user_search=' Michael Balzary'

However, a problem is encountered if the data entered is:

McSorley's

The single quote in the query will disrupt the quotes used in the query, changing the final statement to:

Select patient_records from tblPatients where user_search=' McSorley's

This will cause errors, since there is now a complete query and extra "junk" at the end.This in effect allows the input to "escape out" of the query. If the data entered were:

Light' or user_search='Dark

the query would now look like this:

Select patient_records from tblPatients where user_search=' Light' or user_search='Dark

The input here takes advantage of the fact that the single quote in the input is used to terminate the first string, meaning that everything following the first single quote becomes part of the query itself. The input is intentionally missing the final quote needed in 'Dark' because the original query statement will append that.

The Web application fails to validate the input for these reserved characters and keywords that were in the input, and by simply concatenating it to the query, the application changes the nature of the query itself.

It is this ability to modify the query that defines SQL injection. By modi­fying the query in careful, intentional ways, a hacker can access the complete back-end database and even bypass mechanisms in the application.

Examine this new query, designed to look up a username in a login mechanism:

Select username from Users where username=IM &request.form("userid") &

If the input for "userid" is:

1 or 'a'='a

the query is modified as in our previous example, but in a particularly crafty manner:

Select username from Users where username=' ' or 'a'='a'

Now the query searches the database for a username where the username is either blank or where the letter a is equal to the letter a. This statement is always true; the letter a is equal to the letter a, and the database will return the first row of the table specified. In this case, it will return the first username to the applica­tion. If that input is pasted into the password field as well, the database will simply return the first username and password to the application, simply logging the user into the application, completely bypassing the authentication altogether.

In the case of integers, the injection is even easier. SQL only requires quotes around strings or characters, not numbers, so a back-end query that expects only numbers wouldn't have the single quotes wrapping the input. This means that no "escaping out" of the query with single quotes is necessary.

For example, the query:

SQL_Lookup = " select stores from tableLocations where tableLocations.zipcode=" & request.querystring("zip")

can be injected into by simply entering:

12345 or 1=1

to form the new query:

select stores from tableLocations where tableLocations.zipcode=12345 or 1=1

Simply modifying the WHERE clause with "and" and "or" isn't even half of what you can do with SQL injection. Unless your database security is particu­larly sectioned off, most of the time having SQL injection on even one param­eter on one page is essentially the same as allowing anyone to open a query tool directly against your database.

The extent of possible damage is limited only by the attacker's knowledge of structured query language and the attacker's intent. For instance, using the pre­vious query as an example, a hacker could simply enter:

12345; shutdown

The semicolon is a command separator, allowing multiple commands on line. In this case, two separate commands execute, the first of which is a SELECT query and the second of which very nicely and cleanly shuts down the database. This is being nice, however. To play for keeps, a hacker could start using data def­inition language to tamper with the database stores themselves. For instance, this:

12345; use master; drop database critical_db

would completely remove the specified database. Gone, over a single HTTP request over port 80, through your firewall, due to one small parameter hidden somewhere in the Web application. Even the physical files would be deleted.

Of course, destroying a database is usually far beyond the acceptable limits for any penetration test; even shutting it down typically is unacceptable. The real goal with SQL injection is to get to the data, and that's a piece of cake.

Enumerating Databases

Once the injection is discovered, the first step toward getting data is to enu­merate the database schema, so as to know what table and column names to specify in the attack query.The techniques used for this vary from database to database. For instance, with Microsoft Access, a complete brute-force approach is necessary. Some portions of the schema could be leaked via error messages, but for the most part you can only rely on the error messages to tell you that you have specified an incorrect table or column name and thus must perform some form of a dictionary or brute-force attack to guess the correct names.This prim­itive approach is necessary due to Access's limited functionality. High-end databases such as MS SQL Server and Oracle are extremely more robust and provide the DBA with system tables, functions, stored procedures, extended stored procedures, and more. Of course, this functionality is a two-edged sword and greatly facilities SQL injection attacks.

For instance, against a Microsoft SQL Server, querying the sysusers table of a database will reveal usernames for that database:

show_news.asp?story_id=0 union select name from sysusers

db_accessadmin
db_backupoperator
db_datareader
db_datawriter
db_ddladmin
db_denydatareader
db_denydatawriter
db_owner
db_securityadmin
dbo
guest
public


The work goes very quickly when the page returns all records in the set. Many times the page will only return one record, in which case you'll need to manually iterate through the rows to get them all. This can be easily accom­plished using Boolean operators.

Look at this example, where we retrieve all the user tables from the database. The Sysobjects table stores lists of all objects in the database, and we'll ask for all tables where the user type is U. This means it's a user table, or created by the DBA (presumably for the application), and not a system table automatically cre­ated by the server.

The query:

storyid=0 union select name from sysobjects where xtype='U'

returns:

card_auths

The next step is to get another single record, but a different record. We'll simply tell the database that we want the next higher one in the list. The query:

Storyid=0 union select name from sysobjects where xtype='U' and name> card_auths

returns:

customer_names

The query:

Storyid=0 union select name from sysobjects where xtype='U' and name> 'customer_names'

returns:

News_articles

Continuing with this technique, we arrive at the following table names:

■ Card_auths

■ Customer_names

■ News_articles

■ Web_users

Getting the column names for a particular table is just as easy. We query the Syscolumns table for the column name. Here, however, we need to specify the particular ID number that relates that table back to sysobjects. We could query for each ID number manually and write it down, or we could simply inject a slightly more complex query:

Storyid=0 union select name from syscolumns where id=(select id from sysobjects where name='card_auths')

This politely returns our first column in the card_auths table: card_auth_no. Next we iterate through, using the same technique as before.

storyid=0 union select name from syscolumns where id=(select id from sysobjects where name='card_auths') and name>'card_auth_no'

Actually grabbing data from the column follows the same methodology: get a row and use it to fetch the next, iterating through the records until you've satis­factorily scared your client:

storyid=0 union select card_no from card_auths

returns:

1234666633337890

storyid=0 union select card_no from card_auths where card_no >1234666633337890

returns:

1234678911114567

There are more techniques available for SQL injection, but they go beyond the scope of this book. New techniques include:

■ Evading single quote filters This is when the programmer knows to remove or replace single quotes. It was formerly thought that this step would remove the possibility of SQL injection against strings, although typing input would prevent it against integer values. There is a technique using a SQL function that will still allow the insertion of string values into the database.

■ Blind SQL injection This is an advanced technique for performing injections against pages that have completely handled and suppressed all error messages. With no error messages available, the hacker is essentially "groping around in the dark." With the right technique, however, the attacker can actually go about it in a methodological manner. It's defi­nitely a time-consuming effort, but it works when it's done correctly.

■ At least two completely automated tools for performing SQL injection One is commercial and the other is freeware/loosely licensed.

Summary

The full spectrum of Web application vulnerabilities is very broad indeed and is really just recently getting the attention it deserves. Although the security issues of operating systems and other commercial software are well known, just as many (if not more) issues are prevalent through Web applications in use on the Internet and internally to organizations. Without properly secured Web applications, the security of the Web server or network is irrelevant to the Web site security as the application itself becomes an extension of the perimeter.

The material covered in this appendix represents the basics. Any penetration tester, application developer, or security engineer is encouraged to further his or her education and skills in Web application security through the various papers, sites, and products available to them.

References

White papers:

■ Cross-site scripting:

■ Cross-Site Scripting, by Kevin Spett, www.spidynamics.com/whitepa-pers/SPIcross-sitescripting.pdf

■ The Cross-Site-Scripting FAQ on CGI Security, www.cgisecurity.com/articles/

■ SQL injection—all three of these are excellent papers written by some of the sharpest minds in computer security:

■ Web Application Disassembly with ODBC Error Messages, by David Litchfield, www.nextgenss.com/papers/webappdis.doc

■ Advanced SQL Injection in SQL Server Applications, by Chris Anly, http://www.nextgenss.com/papers/advanced_sql_injection.pdf

■ Blind SQL Injection, by Kevin Spett, www.spidynamics.com/ support/whitepapers/Blind_SQLInjection.pdf

■ Web sites:

■ The Open Web Application Security Project (OWASP), www.owasp.org, hosts an annual conference and local chapters on

Web application security. The site offers many excellent papers as well as some tools.

■ CGI Security, www.cgisecurity.com, offers papers, articles, links, and more by Bob Auger

■ Security Focus, www.securittyfocus.com, the CNN of the InfoSec world.

■ E-mail:

■ Web Application Security on Security Focus, webappsec@security-focus.com, moderated, moderate traffic.This is the de facto OWASP list and deals only with Web application security.

Solutions Fast Track

Defining Web Application Security

0 Web application security deals with securing the actual application being served on a Web site, not the Web server, network, or operating system.

0 Web application security deals with your own software. It doesn't mean Trojans, viruses, spam, or Web filtering.These are all application-level issues that are important to life on the Net but have nothing to do with Web application security.

0 Web application security is a necessary complement to your efforts to secure your servers and networks. Without a secure application, the security in these other areas is undermined.

The Uniqueness of Web Application Security

0 Network and operating systems security typically deals with "known" vulnerabilities.

0 Known vulnerabilities can benefit from a homogenous environment.

0 Most Web applications are custom developed so their vulnerabilities are unique to that application; they are not public, not "known."

0 The lack of security in Web applications can be generally contributed to the lack of security awareness in the Web development industry and lack of appropriate security testing.

Web Application Vulnerabilities

0 Web hacking is an easy discipline and generally requires few tools.

0 Traditional perimeter security is generally ineffective against Web application exploits.

0 Web application vulnerabilities can exist in almost any facet of the

application, from the logical construction of authentication mechanisms and session management down to individual function calls.

Constraints of Search Engine Hacking

0 Search engines crawl only a portion of what's available to a hacker

0 Search engine hacking finds targets of opportunity, but don't rely on it as a security assessment of your application.

0 You would be able to find anything exposed to Google just by crawling; however, the majority of Web application vulnerabilities require actively exercising the application.

Information and Vulnerabilities in Content

0 Just by crawling or looking for common files, you can find a significant amount of information in a Web application. Some of this information could reveal vulnerabilities, but a great deal more information found via crawling will assist you in testing the logic of the code.

0 Files such as robots.txt, FTP logs, and Web traffic reports will guide you to undisclosed portions of the site.

0 Comments, error messages, system documentation, and other such forms of content are all sources of significant information for Web application testing. We've seen throughout this book how this data can be retrieved with search engines.

0 Examine the client-side "programming" that many developers lean on. Hidden form fields, This is old school, but many developers still don't realize that anything client-sided can be abused.

Solution Playing with Packets

0 Serious Web application testing requires the ability to work at the packet level.

0 Sniffers will expose the raw packet for viewing, but they don't allow modification.

0 Local proxies intercept the traffic from your browser to the Web

application and let you see the raw traffic as well as modify raw requests. More sophisticated proxies allow modification of the server response for testing browser behavior as well.

Solution Code Vulnerabilities in Web Applications

0 Vulnerabilities related to the code are by far the most serious Web application vulnerabilities.

0 Client-side attacks such as cross-site scripting attack the users of a Web application to gain their access privileges. They usually require some sort of phishing scheme.

0 Session management issues can allow a hacker to impersonate another user.

0 SQL injection is an extremely serious vulnerability that essentially provides a hacker with direct access to your database by "fooling" the Web application into running a different database query than expected.

0 Web application security is a major threat. The industry hasn't addressed it until recently, but millions of Web applications exist.

0 The Web application is an extension of your perimeter. If it isn't secure, neither is your perimeter.

0 Web application security has been receiving a great deal of attention lately. Learn as much The following Frequently Asked Questions, answered by the authors of this book, are designed to both measure your understanding of the concepts presented in this chapter and to assist you with real-life implementation of these concepts. To have your questions about this chapter answered by the author, browse to www.syngress.com/solutions and click on the "Ask the Author" form. You will also gain access to thousands of other FAQs at ITFAQnet.com.

Q: What level of security does Secure Sockets Layer (SSL) provide against Web application attacks?

A: Almost none. SSL provides two functions, the first of which is that it authen­ticates a domain name to an entity.That is, it certifies that www.bigbank.com actually belongs to Big Bank. Second, SSL creates a "secure" encrypted tunnel to the server so that all communication back and forth is highly encrypted and not subject to "eavesdropping." When properly implemented, SSL is very effective at that. However, SSL provides absolutely no assurances regarding the messages sent across that tunnel; it merely ensures that they cannot be read by a third party. In the context of Web hacking, it simply means that the attack packets are protected from sniffing as they travel to and from the server. Since many intrusion detection systems do not have the ability to read SSL-encrypted packets, this also means that your hacks get tunneled through any monitoring before executing against the server (a nice side benefit). All the high-end Web application security products available will function just as easily over HTTPS as HTTP. If yours doesn't, trade it in for something newer. Note that SSL isn't infallible, particularly if an attacker can arrange him- or herself as a man in the middle (MITM). One large sector we work with frequently has a terrible habit of using self-issued cer­tificates, but they never push their root certificates down to their browsers. This means that their users are in the habit of "clicking through" SSL error messages; creating a ripe situation for a MITM to issue a fake cert instead.

Q: What is the most secure language to develop in?

A: We are asked this all the time, and it's a controversial question. We don't

believe that any particular language is intrinsically more secure than another, though it is capabilities for security than others do. Syngress publishes a great reference: The Programmer's Ultimate Security Desk Reference, by James Foster.

Q: What are some of the worst Web hacks you've ever seen or heard of?

A: We've gotten databases, source code, and admin access in under 5 minutes before, but this was all low-hanging fruit—no great hacking on our behalf required.The worst hack we can think of in the news is one we read about in a Security Focus article written in September 2003 by Kevin Poulsen. It was a Web application that had lots of complete credit applications in cleartext that were in an unauthenticated portion of the Web site. As though that weren't bad enough, according to the article they were discovered because the filename was in an HTML comment.The official from the company that Poulsen interviewed really responded to it poorly and as a result was quoted in Business 2.0 magazine in a very unflattering manner. More recently, an online banking application in the United Kingdom "upgraded" its authenti­cation mechanism to be more secure, until it was discovered that it allowed access with just a userid—no password necessary.

Q: What's the best way to learn more about Web application security?

A: Learn more about Web applications.You have to understand how Web appli­cations work to develop any measure of expertise in Web app sec. In fact, the best minds in any realm of IT sec are all strong coders. Also, make sure that you learn the full spectrum of threats. Don't get tunnel vision on something like SQL injection just because it's cool—start from the top and drill down into details from there.

Q: Will my existing scanner find Web vulnerabilities?

A: Probably not. There are very few actual Web assessment scanners out there, and they are extremely specialized tools. If you have one, you'll know.The majority of scanners on the market today are general "network" scanners that are very focused on known vulnerabilities and the basics, such as open ports or risky services. For working entirely manually, a number of tools are avail­able either freely or very inexpensively. The only automated tools worth looking at are the Q: Are Web application hacks really invisible to IDS and firewalls?

A: For the most part, yes. There are certain hacks that are sure to set off a net­work IDS, such as a directory traversal attack. This existed as a daemon issue for so long—and has such as unique signature—that almost all NIDS will detect it.That said, however, we've done complete assessments through a variety of network IDS before and rarely get detected.The few times we've been detected, our customer saw a mere fraction of the actual attacks per­formed. Likewise, we've done assessments on Web applications actually run­ning on servers with host IDS on them, with equal results: lots of vulnerabilities, no alerts, since they tend to be more process and memory ori­ented. Web hacks execute within existing processes—the Web daemon and the database daemon—so no new processes should be launched unless the Web hacker attempts a full root kit.

Q: Is Web application security more important than network security?

A: That's your call. We'd call a buffer overflow on a service exposed to the DMZ pretty serious, but at the same time, if we can get to your database from our wireless PDAs while sitting on a train, that's pretty bad, too. So far there hasn't been a Web application-based worm, but such a thing is undoubtedly coming.

Q: Will securing my database help prevent SQL injection?

A: Securing your database will greatly mitigate SQL injection hacks. By parti­tioning access and restricting capabilities via standard hardening techniques (such as removing unnecessary procedures), you will greatly reduce (or com­pletely negate) what can be done with SQL injection. Beware, though— don't forget to harden the Web application code as well or you could find other vulnerabilities slipping through.

Q: Is it true that Web services are more secure than Web applications?

A: Absolutely not. Remember that although the presentation protocol has

changed (there is now a SOAP envelope,) it's essentially the exact same back­end code that would be used in a Web application, and thus it's susceptible to the exact same mistakes. The best Web application scanners will audit Web services in addition to Web applications.

1 As reported by Netcraft.com in the September 2004 Web Server Survey, http://news.netcraft.com/archives/web_server_survey.html.

No comments:

Post a Comment