SQL injection
Encyclopedia
A SQL injection is often used to attack the security of a website by inputting SQL statements in a web form to get a badly designed website in order to dump the database content to the attacker. SQL injection is a code injection
Code injection
Code injection is the exploitation of a computer bug that is caused by processing invalid data. Code injection can be used by an attacker to introduce code into a computer program to change the course of execution. The results of a code injection attack can be disastrous...

 technique that exploits a security vulnerability in a website's software. The vulnerability happens when user input is either incorrectly filtered for string literal
String literal
A string literal is the representation of a string value within the source code of a computer program. There are numerous alternate notations for specifying string literals, and the exact notation depends on the individual programming language in question...

 escape characters embedded in SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....

 statements or user input is not strongly typed
Strongly-typed programming language
In computer science and computer programming, a type system is said to feature strong typing when it specifies one or more restrictions on how operations involving values of different data types can be intermixed...

 and unexpectedly executed. SQL commands are thus injected from the web form into the database
Database
A database is an organized collection of data for one or more purposes, usually in digital form. The data are typically organized to model relevant aspects of reality , in a way that supports processes requiring this information...

 of an application
Application software
Application software, also known as an application or an "app", is computer software designed to help the user to perform specific tasks. Examples include enterprise software, accounting software, office suites, graphics software and media players. Many application programs deal principally with...

 (like queries) to change the database content or dump the database information like credit card or passwords to the attacker. SQL injection is mostly known as an attack vector for websites but can be used to attack any type of SQL database.

Using well designed query language interpreters can prevent SQL injections. In the wild, it has been noted that applications experience, on average, 71 attempts an hour. When under direct attack, some applications occasionally came under aggressive attacks and at their peak, were attacked 800-1300 times per hour.

Forms of vulnerability

SQL Injection Attack (SQLIA) is considered one of the top 10 web application vulnerabilities of 2010 by the Open Web Application Security Project. The attacking vector contains five main sub-classes depending on the technical aspects of the attack's deployment:
  • Classic SQLIA
  • Inference SQL Injection
  • Intracting with SQL Injection
  • DBMS specific SQLIA
  • Compounded SQLIA


Some security researchers propose that Classic SQLIA is outdated though many web applications are not hardened against them. Inference SQLIA is still a threat, because of its dynamic and flexible deployment as an attacking scenario. The DBMS specific SQLIA should be considered as supportive regardless of the utilization of Classic or Inference SQLIA. Compounded SQLIA is a new term derived from research on SQL Injection Attacking Vector in combination with other different web application attacks as:
  • SQL Injection + Insufficient authentication
  • SQL Injection + DDos attacks
  • SQL Injection + DNS Hijacking
  • SQL Injection + XSS


The Storm Worm
Storm Worm
The Storm Worm is a backdoor Trojan horse that affects computers using Microsoft operating systems, discovered on January 17, 2007...

 is one representation of Compounded SQLIA.
A complete overview of the SQL Injection classification is presented in the next figure, Krassen Deltchev in 2010:
This Classification represents the state of SQLIA, respecting its evolution till 2010; further refinement is underway. m/2007/01/social-engineering-and-malware.html |title=Dancho Danchev's Blog

Incorrectly filtered escape characters

This form of SQL injection occurs when user input is not filtered for escape characters and is then passed into an SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....

 statement. This results in the potential manipulation of the statements performed on the database by the end-user of the application.

The following line of code illustrates this vulnerability

statement = "SELECT * FROM users WHERE name = '" + userName + "';"

This SQL code is designed to pull up the records of the specified username from its table of users. However, if the "userName" variable is crafted in a specific way by a malicious user, the SQL statement may do more than the code author intended. For example, setting the "userName" variable as

' or '1'='1

Or using comments to even block the rest of the query (there are three types of SQL comments):
' or '1'='1' -- '
' or '1'='1' ({ '
' or '1'='1' /* '


renders one of the following SQL statements by the parent language:

SELECT * FROM users WHERE name = or '1'='1';
SELECT * FROM users WHERE name = or '1'='1' -- ';

If this code were to be used in an authentication procedure then this example could be used to force the selection of a valid username because the evaluation of '1'='1' is always true.

The following value of "userName" in the statement below would cause the deletion of the "users" table as well as the selection of all data from the "userinfo" table (in essence revealing the information of every user), using an API that allows multiple statements:

a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't'


This input renders the final SQL statement as follows:

SELECT * FROM users WHERE name = 'a';DROP TABLE users; SELECT * FROM userinfo WHERE 't' = 't';

While most SQL server implementations allow multiple statements to be executed with one call in this way, some SQL APIs such as PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

's mysql_query; function do not allow this for security reasons. This prevents attackers from injecting entirely separate queries, but doesn't stop them from modifying queries.

Incorrect type handling

This form of SQL injection occurs when a user supplied field is not strongly typed or is not checked for type
Data type
In computer programming, a data type is a classification identifying one of various types of data, such as floating-point, integer, or Boolean, that determines the possible values for that type; the operations that can be done on values of that type; the meaning of the data; and the way values of...

 constraints. This could take place when a numeric field is to be used in a SQL statement, but the programmer makes no checks to validate that the user supplied input is numeric. For example:
statement := "SELECT * FROM userinfo WHERE id = " + a_variable + ";"

It is clear from this statement that the author intended a_variable to be a number correlating to the "id" field. However, if it is in fact a string
String (computer science)
In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet....

 then the end-user
End-user
Economics and commerce define an end user as the person who uses a product. The end user or consumer may differ from the person who purchases the product...

 may manipulate the statement as they choose, thereby bypassing the need for escape characters. For example, setting a_variable to

1;DROP TABLE users


will drop (delete) the "users" table from the database, since the SQL would be rendered as follows:

SELECT * FROM userinfo WHERE id=1;DROP TABLE users;

Blind SQL injection

Blind SQL Injection is used when a web application is vulnerable to an SQL injection but the results of the injection are not visible to the attacker. The page with the vulnerability may not be one that displays data but will display differently depending on the results of a logical statement injected into the legitimate SQL statement called for that page.
This type of attack can become time-intensive because a new statement must be crafted for each bit recovered. There are several tools that can automate these attacks once the location of the vulnerability and the target information has been established.

Conditional responses

One type of blind SQL injection forces the database to evaluate a logical statement on an ordinary application screen.
SELECT booktitle FROM booklist WHERE bookId = 'OOk14cd' AND '1'='1';
will result in a normal page while
SELECT booktitle FROM booklist WHERE bookId = 'OOk14cd' AND '1'='2';
will likely give a different result if the page is vulnerable to a SQL injection.
An injection like this may suggest to the attacker that a blind SQL injection is possible, leaving the attacker to devise statements that evaluate to true or false depending on the contents of another column or table outside of the SELECT statement's column list.

SELECT 1/0 FROM users WHERE username='ooo';

Parameterized statements

With most development platforms, parameterized statements can be used that work with parameters (sometimes called placeholders or bind variables) instead of embedding user input in the statement. In many cases, the SQL statement is fixed, and each parameter is a scalar, not a table. The user input is then assigned (bound) to a parameter.

Enforcement at the coding level

Using object-relational mapping
Object-relational mapping
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language...

 libraries avoids the need to write SQL code. The ORM library in effect will generate parameterized SQL statements from object-oriented code.

Escaping

A straightforward, though error-prone, way to prevent injections is to escape characters that have a special meaning in SQL. The manual for an SQL DBMS explains which characters have a special meaning, which allows creating a comprehensive blacklist
Blacklist (computing)
In computing, a blacklist or block list is a basic access control mechanism that allows everyone access, except for the members of the black list . The opposite is a whitelist, which means allow nobody, except members of the white list...

 of characters that need translation. For instance, every occurrence of a single quote (') in a parameter must be replaced by two single quotes () to form a valid SQL string literal. For example, in PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 it is usual to escape parameters using the function mysql_real_escape_string; before sending the SQL query:

$query = sprintf("SELECT * FROM `Users` WHERE UserName='%s' AND Password='%s'",
mysql_real_escape_string($Username),
mysql_real_escape_string($Password));
mysql_query($query);

This function, i.e. mysql_real_escape_string, calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
This function must always (with few exceptions) be used to make data safe before sending a query to MySQL
MySQL
MySQL officially, but also commonly "My Sequel") is a relational database management system that runs as a server providing multi-user access to a number of databases. It is named after developer Michael Widenius' daughter, My...

.

There are other functions for many database types in PHP such as pg_escape_string for PostgreSQL
PostgreSQL
PostgreSQL, often simply Postgres, is an object-relational database management system available for many platforms including Linux, FreeBSD, Solaris, MS Windows and Mac OS X. It is released under the PostgreSQL License, which is an MIT-style license, and is thus free and open source software...

. There is, however, one function that works for escaping characters, and used especially for injection in the databases that do not have escaping functions in PHP. This function is: addslashes(string $str ). It returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Routinely passing escaped strings to SQL is error prone because it is easy to forget to escape a given string. Creating a transparent layer to secure the input can reduce this error-proneness, if not entirely eliminate it.

Known real-world examples

  • On November 1, 2005, a teenage hacker used SQL injection to break into the site of a Taiwanese information security magazine from the Tech Target group and steal customers' information.
  • On January 13, 2006, Russian computer criminals broke into a Rhode Island government web site and allegedly stole credit card data from individuals who have done business online with state agencies.
  • On March 29, 2006, a hacker discovered an SQL injection flaw in an official Indian government tourism site.
  • On March 2, 2007, a hacker discovered an SQL injection flaw in the knorr.de login page.
  • On June 29, 2007, a computer criminal defaced the Microsoft U.K. website using SQL injection. U.K. website The Register quoted a Microsoft spokesperson acknowledging the problem.
  • In January 2008, tens of thousands of PCs were infected by an automated SQL injection attack that exploited a vulnerability in application code that uses Microsoft SQL Server
    Microsoft SQL Server
    Microsoft SQL Server is a relational database server, developed by Microsoft: It is a software product whose primary function is to store and retrieve data as requested by other software applications, be it those on the same computer or those running on another computer across a network...

     as the database store.
  • In July 2008, Kaspersky's Malaysian site was hacked by a Turkish hacker going by the handle of "m0sted", who claimed to have used an SQL injection.
  • On April 13, 2008, the Sexual and Violent Offender Registry
    Sex offender registration
    Sex offender registration is a system in various states designed to allow government authorities to keep track of the residence and activities of sex offenders, including those who have completed their criminal sentences. In some jurisdictions , information in the registry is made available to the...

     of Oklahoma
    Oklahoma
    Oklahoma is a state located in the South Central region of the United States of America. With an estimated 3,751,351 residents as of the 2010 census and a land area of 68,667 square miles , Oklahoma is the 28th most populous and 20th-largest state...

     shut down its website for 'routine maintenance' after being informed that 10,597 Social Security number
    Social Security number
    In the United States, a Social Security number is a nine-digit number issued to U.S. citizens, permanent residents, and temporary residents under section 205 of the Social Security Act, codified as . The number is issued to an individual by the Social Security Administration, an independent...

    s belonging to sex offender
    Sex offender
    A sex offender is a person who has committed a sex crime. What constitutes a sex crime differs by culture and by legal jurisdiction. Most jurisdictions compile their laws into sections such as traffic, assault, sexual, etc. The majority of convicted sex offenders have convictions for crimes of a...

    s had been downloaded via an SQL injection attack
  • In May 2008, a server farm inside China used automated queries to Google's search engine to identify SQL server
    Microsoft SQL Server
    Microsoft SQL Server is a relational database server, developed by Microsoft: It is a software product whose primary function is to store and retrieve data as requested by other software applications, be it those on the same computer or those running on another computer across a network...

     websites which were vulnerable to the attack of an automated SQL injection tool.
  • In 2008, at least April through August, a sweep of attacks began exploiting the SQL injection vulnerabilities of Microsoft's IIS web server
    Internet Information Services
    Internet Information Services – formerly called Internet Information Server – is a web server application and set of feature extension modules created by Microsoft for use with Microsoft Windows. It is the most used web server after Apache HTTP Server. IIS 7.5 supports HTTP, HTTPS,...

     and SQL Server database server
    Microsoft SQL Server
    Microsoft SQL Server is a relational database server, developed by Microsoft: It is a software product whose primary function is to store and retrieve data as requested by other software applications, be it those on the same computer or those running on another computer across a network...

    . The attack does not require guessing the name of a table or column, and corrupts all text columns in all tables in a single request. A HTML string that references a malware JavaScript file is appended to each value. When that database value is later displayed to a website visitor, the script attempts several approaches at gaining control over a visitor's system. The number of exploited web pages is estimated at 500,000.
  • On August 17, 2009, the United States Justice Department charged an American citizen Albert Gonzalez
    Albert Gonzalez
    Albert Gonzalez is a computer hacker and computer criminal who is accused of masterminding the combined credit card theft and subsequent reselling of more than 170 million card and ATM numbers from 2005 through 2007—the biggest such fraud in history.Gonzalez and his accomplices used SQL injection...

     and two unnamed Russians with the theft of 130 million credit card numbers using an SQL injection attack. In reportedly "the biggest case of identity theft in American history", the man stole cards from a number of corporate victims after researching their payment processing systems. Among the companies hit were credit card processor Heartland Payment Systems
    Heartland Payment Systems
    Heartland Payment Systems, Inc. provides debit, prepaid, and credit card processing, online payments, check processing, payroll services and a growing line of industry solutions for small to mid-sized merchants. Heartland Payment Systems is currently the fifth largest credit card processor in the...

    , convenience store chain 7-Eleven
    7-Eleven
    7-Eleven is part of an international chain of convenience stores, operating under Seven-Eleven Japan Co. Ltd, which in turn is owned by Seven & I Holdings Co...

    , and supermarket chain Hannaford Brothers.
  • In December 2009, an attacker breached a RockYou
    RockYou
    RockYou is a developer of social games and advertising solutions for social media. RockYou is focused on the development of social game titles, including Gourmet Ranch and the Zoo World franchise...

     plaintext database containing the unencrypted usernames and passwords of about 32 million users using an SQL injection attack.
  • On July 2010, a South American security researcher who goes by the handle Ch Russo obtained sensitive user information from popular BitTorrent site The Pirate Bay. He gained access to the site's administrative control panel and exploited a SQL injection vulnerability that enabled him to collect user account information, including IP addresses, MD5 password hashes and records of which torrents individual users have uploaded.
  • On July 24–26, 2010, attackers from within Japan and China used an SQL injection to gain access to customers' credit card data from Neo Beat, an Osaka
    Osaka
    is a city in the Kansai region of Japan's main island of Honshu, a designated city under the Local Autonomy Law, the capital city of Osaka Prefecture and also the biggest part of Keihanshin area, which is represented by three major cities of Japan, Kyoto, Osaka and Kobe...

    -based company that runs a large online supermarket site. The attack also affected seven business partners including supermarket chains Izumiya Co, Maruetsu Inc and Ryukyu Jusco Co. The theft of data affected a reported 12,191 customers. As of August 14, 2010 it was reported that there have been more than 300 cases of credit card information being used by third parties to purchase goods and services in China.
  • On September 19 during the 2010 Swedish general election
    Swedish general election, 2010
    A general election to the Riksdag, parliament of Sweden, was held on . The main contenders of the election were the governing centre-right coalition the Alliance and the oppositional centre-left Red-Greens coalition A general election to the Riksdag, parliament of Sweden, was held on . The main...

     a voter attempted a code injection by hand writing SQL commands as part of a write in vote.
  • On 8 November 2010 the British Royal Navy
    Royal Navy
    The Royal Navy is the naval warfare service branch of the British Armed Forces. Founded in the 16th century, it is the oldest service branch and is known as the Senior Service...

     website was compromised by TinKode using SQL injection.
  • On 5 February 2011 HBGary
    HBGary
    HBGary is a technology security company. Two distinct but affiliated firms carry the name: HBGary Federal, which sells its products to the US Federal Government, and HB Gary, Inc. Its other clients include information assurance companies, computer emergency response teams, and computer forensic...

    , a technology security firm, was broken into by Anonymous
    Anonymous (group)
    Anonymous is an international hacking group, spread through the Internet, initiating active civil disobedience, while attempting to maintain anonymity. Originating in 2003 on the imageboard 4chan, the term refers to the concept of many online community users simultaneously existing as an anarchic,...

     using a SQL injection in their CMS-driven website
  • On March 27, 2011 mysql.com, the official homepage for MySQL
    MySQL
    MySQL officially, but also commonly "My Sequel") is a relational database management system that runs as a server providing multi-user access to a number of databases. It is named after developer Michael Widenius' daughter, My...

    , was compromised by TinKode using SQL blind injection
  • On April 11, 2011, Barracuda Networks was compromised using an SQL injection flaw. Email addresses and usernames of employees were among the information obtained
  • Over a period of 4 hours on Wednesday April 27, 2011 an automated SQL injection attack occurred on Broadband Reports website that was able to extract 8% of the username/password pairs: 8,000 random accounts of the 9,000 active and 90,000 old or inactive accounts.
  • On June 1, 2011, "hacktivists" of the group Lulzsec
    LulzSec
    Lulz Security, commonly abbreviated as LulzSec, is a computer hacker group that claims responsibility for several high profile attacks, including the compromise of user accounts from Sony Pictures in 2011. The group also claimed responsibility for taking the CIA website offline...

     were accused of using SQLI to steal coupons, download keys, and passwords that were stored in plaintext on Sony's website, accessing the personal information of a million users.
  • In June, 2011, PBS was hacked, mostly likely through use of SQL injection. The full process used by hackers to execute SQL injections was described in this Imperva blog.
  • On June 27, 2011, Lady Gaga's website was hacked by a group of US cyber attackers called SwagSec and thousands of her fans’ personal details were stolen from her website. The hackers took a content database dump from www.ladygaga.co.uk and a section of email, first name, and last name records were accessed. According to an Imperva blog about the incident, a SQL injection vulnerability for her website was recently posted on a hacker forum website, where a user revealed the vulnerability to the rest of the hacker community. While no financial records were compromised, the blog implies that Lady Gaga fans are most likely receiving fraudulent email messages offering exclusive Lady Gaga merchandise, but instead contain malware.
  • In August, 2011, Hacker Steals User Records From Nokia Developer Site using "SQL injection"
  • In September, 2011, Turkish Hackers accessed NetNames DNS records and changed entries redirecting users (of Betfair (Online Gambling), The Telegraph, The Register, The National Geographic, UPS, Acer, Vodafone.com) to a site set up by them, and then taking responsibility for this action publishing it on Zone-H
    Zone-H
    Zone-H is an archive of defaced websites. Once a defaced website is submitted to Zone-H, it is mirrored on the Zone-H servers, it is then moderated by the Zone-H staff to check if the defacement was fake....

     .
  • In October, 2011, Malaysian Hacker, Phiber Optik managed to extract data from www.canon.com.cn by exploiting a vulnerability he came across. He himself reported the vulnerability to the company within minutes and claiming to have used SQL Injection.

See also

  • Cross-site scripting
    Cross-site scripting
    Cross-site scripting is a type of computer security vulnerability typically found in Web applications that enables attackers to inject client-side script into Web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same...

  • Metasploit Project
    Metasploit Project
    The Metasploit Project is an open-source computer security project which provides information about security vulnerabilities and aids in penetration testing and IDS signature development....

  • w3af
    W3af
    w3af is an open-source web application security scanner. The project provides a vulnerability scanner and exploitation tool for Web applications...


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK