SQL Injection: How-To Attack And How-To Prevent

All About SQL Injection Attack

SQL Injection Attack
SQL Injection

SQL injection is a technique often used to attack databases through a website. This is done by including portions of SQL statements in a web form entry field in an attempt to get the website to pass a newly formed rogue SQL command to the database (e.g. dump the database contents to the attacker). A SQL Injection attack is a form of attack that comes from user input that has not been checked to see that it is valid. The objective is to fool the database system into running malicious code that will reveal sensitive information or otherwise compromise the server. The vulnerability happens when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed.

Types Of SQL Injection

There are two main types of attacks. First-order attacks are when the attacker receives the desired result immediately, either by direct response from the application they are interacting with or some other response mechanism, such as email. Second-order attacks are when the attacker injects some data that will reside in the database, but the payload will not be immediately activated. I will discuss each in more detail later in this article.

SQL injections top plenty of lists as the most prevalent means of attacking front-end Web applications and back-end databases to compromise data.

Reports On SQL Injection Attacks Around the World

According to recent published reports in Darkreading.com, analysis of the Web Hacking Incidents Database (WHID) shows SQL injections as the top attack vector, making up 19 percent of all security breaches examined by WHID. Similarly, in the “Breach Report for 2010” (PDF) released by 7Safe earlier this month, a whopping 60 percent of all breach incidents examined involved SQL injections.

“One of the reasons we’re seeing such an increase in SQL injections is actually sort of what we’ve dubbed the ‘industrialization’ of hacking,” says Brian Contos, chief security strategist for Imperva. “It’s this notion of smart SQL injections leveraging things like Google searches, automation through bots, and various other technologies to carry out sophisticated, automated attacks.”

How To Protect Against SQL Injection Attacks?

Here are some steps by which you can secure your website from SQL injection attacks:

1). Data Sanitization

Websites must filter all user input. Ideally, user data should be filtered for context. For example, e-mail addresses should be filtered to allow only the characters allowed in an e-mail address, phone numbers should be filtered to allow only the characters allowed in a phone number, and so on. According to Christopher of freelancer.com, you have to check and sanitize any user input you use. Rule number one for programmers is never trust the user. If you’ve got a select box with numbers from 1-100, make sure the form data the user sent is actually a number! (Note: is_numeric checks for any numerical value, including floats etc. You will still want to cast it to the target type).

The PHP code will look like this:

if(!is_numeric($_POST[‘fav_num’])) die(‘Please choose a number.’);

// Or simply cast it into a number

$fav_num = (int)$_POST[‘fav_num’]; 

A misconception among most of the programmers is that they think data sanitization means using addslashes() (which is used to escape quotes), but in reality this may not be the solution to the problem. It is advised for MYSQL, you should use the mysql real escape string function to by 100% secure.

2). Using A Firewall

It is also considered of high priority to use a web application firewall. A Firewall (Web App Firewall) detects attacks by filtering all incoming HTTP and HTTPS traffic through configurable network and application layer controls. The basic idea of a web app firewall is based on ModSecurity, an industry standard and trusted rule set that detects and prevent common exploitation techniques such as SQL Injection and Cross Site Scripting (XSS). WAF runs across Akamai’s distributed EdgePlatform, performing its inspections before Akamai serves each request. Users can easily configure the firewall, alerts and actions, as well as IP blacklists and whitelists.

3). Creating Multiple Database User Accounts

Create multiple database user accounts with the minimum levels of privilege for their usage environment. For example, the source code of a login page should query the database using an account limited only to the relevant credentials table. This way, a breach through this channel cannot be leveraged to compromise the entire database. According to developer at easysoft, Some of the most harmful attacks shown in the SQL injection examples are avoidable by using careful database permissions. For example, the example that drops the user table would not succeed if the database user the application was using did not have drop permission. You should always run your application using a database user with the minimum permissions it needs to perform its functions. It is doubtful that many applications need to drop tables and possible that they only need select access and no update/delete access. The most important rule is not to give database user permissions that it does not require. It is not a solution to SQL injection, but is good practice that makes your application less vulnerable to attacks.

4).Avoid Constructing SQL Queries With User Input in Them

You should avoid constructing SQL queries with user input in them. When even Comprehensive data sanitization can be tricked away, the most sensible thing to do is to use SQL variable that are bind with prepared statements or stored parameters. It is much safer rather than constructing full queries, which is lot time consuming and considerable hard.  If you never concatenate user input with SQL fragments to construct a query, then you will never be vulnerable to SQL injection attacks. To further reduce the risk of SQL injection, be sure to remove any technical information from client-delivered error messages. Error messages often reveal technical details that can enable an attacker to reveal vulnerable entry points. This includes any custom messages your application generates as well as IIS-generated errors. You can implement this by disabling detailed error messages in IIS and by creating non-technical custom error pages.

5). GPC, 3 ways of authentication.

G- GET, P – POST and C – Cookie.

Hackers, often use GET method to inject their “union+select+” queries or POST method from one server to another, if authentication has javascript filtering using their OR 1=1 method and the last but not the least, cookies. Cookies are used by very few hackers, however with the use of session cookies, their successful attempts are limited to minimum.
addslashes() is one of the function that a developer can use if !(get_magic_quotes_gpc). But, adding this line can be troublesome in most cases, where amount of variables are really high, it may make the code look sluggish to have mysql_real_escape_string() in every variable passed. To get rid of all these:
Go to your php.ini file and set:

magic_quotes_gpc = On

magic_quotes_gpc is by default set to Off for optimal performance of the server.

However, if you are using a shared/paid hosting and do not have access to php.ini file then add the following to your .htaccess file.

php_flag magic_quotes_gpc on

If you are following these simple steps then I can assure you that your website will be 99% safe from hackers. (There is nothing like full security. Who knows what might come up in a 19 year old geek junkie mind?)

Author: Naveen Thakur

 If you wish to write articles for Whitec0de Magazine, then Click Here.