How to Prevent SQL Injection Attacks?

After its arrival to the cyber security landscape, SQL injection has continued to be one of the topmost cyber security concerns. As a hacking technique, it is known for its devastating capabilities and the havoc it can cause for institutions of any size and type. Moreover, the frequency of such attacks grew exponentially by around 44% in two years (from 2017 to 2019).

Not to mention, this technique has been used in activities ranging from personal data theft during the US presidential elections to high-profile security breaches at Sony, Microsoft, Yahoo, and even CIA.

Here, we have compiled a list of tools that aid in the detection of SQL injection attacks and also a few essential steps which must be taken to prevent such attacks.

But before moving forward, let's see how injection attacks can impact your business and whether or not you are vulnerable to them.

 

Is Your Business Vulnerable to SQL Injection Attack?

SQL, or Structured Query Language as it is commonly called, is the preliminary language used for manipulating the most widely used relational databases like Oracle, Microsoft SQL Server, and MySQL. These databases can be referred to as the basic building blocks of the modern-day web apps and content management systems.

The threat actors who wish to compromise your security systems through SQL injection attacks are after the sensitive data stored in your databases. The content, behavior of applications & websites are controlled as well as curated through these database servers.

So, if your servers hold any form of sensitive data, which is usually the case, you are vulnerable to SQL injection attacks.

If hackers, by any means, gain access to your critical databases, the results could be catastrophic. In a severe event like SQL injection login bypass attack, the threat actors could gain unprecedented control over the entire system and access and modify critical business or customer data.

The result of an SQL injection attack could range from disruption of website or application content to breach of sensitive user information. If you understand the role databases play in the back-end, you surely would realize how devastating it could be if a hacker executes a simple SQL injection command like DROP TABLE!

After understanding the potential consequences of SQL injection attacks, it becomes imperative to think of ways to prevent them. The primary step when it comes to avoiding an SQL injection attack is to determine the elements of your system, which are potentially vulnerable to it.

 

Tools to Detect SQL Injection

The best way to test your defense is to check it with your weapons. However, given the complexity of SQL, the task won't be as easy as it sounds. It is generally a complicated task to create a code snippet and inject it into a query to compromise a relational database.

On the other hand, this seemingly difficult task could be made easy by deploying some specialized tools. These automated SQL injection attack tools could replicate real attack scenarios and help you test your system in immense detail.

Let's take a look at some of the most commonly used tools to detect and prevent SQL injection:

 

1) SQLmap: One of the most frequently used tools for identifying and exploiting SQL injection flaws, Sqlmap, is an open-source pen-testing tool that provides extensive security to database servers. Apart from several other functionalities, the most exciting feature of Sqlmap is its powerful detection engine, which quickly detects injection flaws in the system. Experts also recognize a GUI version of SQLmap, known as TyrantSQL, as a promising automated tool.

 

2) Havij: Developed by Iranian cyber experts, Havi instantly determines the database details of the target system by quickly getting through its security layers. Using the acquired database knowledge, Havij later builds complex queries to dive deeper into the detailed database characteristics. Without much knowledge of SQL, security professionals can extract tables, fields, and even bigger chunks of data from the target database using Havij.

The error fixing feature in the tool helps you correct some of the identified vulnerabilities as well. Available in both open-source and licensed versions, Havij is famously known for its functionality across the data security market.

 

3) BSQL Hacker: Designed especially for blind SQLi attacks, BSQL hacker is a well-to-do injection tool. With GUI and console support, this tool supports most of the injection points, including HTTP, cookies, and query strings. This tool supports Oracle, MySQL, and MSSQL as well.

 

4) SQLninja: This tool works for web applications that are based on SQL Server. After discovering injection flaws, this tool efficiently automated the process of exploitation and extracts all the necessary information from the database. By allowing remote access to the database servers, SQLninja allows the overall security assessment of the web application in question.

Other prominent SQL injection tools include JSQL, Safe3 SQL Injector, and SQLSus.

One crucial aspect worth noticing here is that these tools not only enable security experts to assess their systems but also supplement threat actors with an arsenal of SQL injection techniques. And for these reasons, you should test your applications with these mentioned tools beforehand and fix the suggested vulnerabilities before someone else could exploit them.

 

Implement the right security practices

 

How to Prevent SQL Injection attacks?

It doesn't matter how frequent SQL injection attacks are or how much they can harm organizations and their customers. There certainly are ways that can help prevent SQL injection attacks. The solutions might not be full-proof, but they could put sufficient barriers in place for hackers if they attempt an SQL injection attack.

 

                   How to prevent SQL Injection attacks

 

You can embed the Infographic below in your website/blog using the HTML code below

<p><strong>Please include attribution to www.appknox.com with this graphic.</strong><br /><br /><a href='https://www.appknox.com/blog/how-to-prevent-sql-injection-attacks'><img src='' alt='How to prevent SQL Injection attacks' 540px border='0' /></a></p>

Here are some guidelines on how you can drastically reduce the risk and impact of SQL injection attacks.

1. Filter Data Wherever You Can

According to a security report, 9 out of 10 local file inclusion attacks are results of input validation failures. That is why it's better to use input validation while receiving user-submitted data. You can't trust what the user intends to do, and user input validation via appropriate functions would filter out any unnecessary characters like 'in SQL queries from the user input data.

It is also advised to filter data by context. You should only allow those characters and numbers which are valid in case of email addresses and only those digits which are allowed in phone numbers and so on.

2. Don't rely on Dynamic SQL Queries

Creating and using SQL queries from user input data is not advisable. It is better to utilize stored, or parameterized queries and prepared statements as even the best data cleaning procedures could have flaws in them. However, there must be a balance between the stored procedures and others, as in many cases, even they might fail to prevent SQL injection attacks.

3. Update, Patch, and Repeat

New SQL injection vulnerabilities keep getting discovered and exploited by hackers regularly. That is why it becomes essential to continuously check for updates and apply patches as soon as possible. You can also rely on a patch management system to take care of your worries.

4. Use a Reliable Web Application Firewall

Malicious data or unusual server requests can be efficiently filtered out by using trusted firewalls. Most of the well-known firewalls consist of an evolving set of rules to provide the best possible security protection. They can provide some underlying security even against the newly discovered threats before a patch is available for them.

One such commonly used firewall is ModSecurity, which is available for a variety of web servers, including Apache and Nginx. Its ever-evolving set of data security rules are best known for filtering dangerous server requests. Its ability to nullify SQL injection attacks has made it a favorite amongst other similar choices.

5. Grant Only Essential Privileges

It's not necessary to always connect to your database using accounts with admin-level privileges. It should be done only under compelling circumstances. Having a limited access account can limit the horizons for attackers if they somehow gain access to your database servers. Suppose an attacker gains access to the code behind your login page. If he gets only limited access to the database, then the breach wouldn't be as damaging as it could potentially be.

6. Use Cryptography Often

In a world this shrewd, it's better to keep your secrets as classified as possible. Using proper encryption and hashing for passwords is always considered as a safe practice, and it also saves your databases from getting breached during SQL injection attacks.

7. Disclose Only Necessary Information

Even error messages can reveal a great deal of vital information related to the database. This might help hackers in gaining useful insights into database architecture. That is why care must be taken before disclosing any added information anywhere over your platform. Using verbose error messages which reveal nothing about the concerned database might help the cause.

8. Monitor SQL Statements Regularly

In order to avoid injection attacks, it is necessary to assess SQL statements from applications connected to the same databases regularly. This helps in filtering unwanted statements and other critical vulnerabilities. Techniques like behavioral analysis and monitoring tools that rely on machine learning can prove to be useful.

Related topic- Biggest Threat to Application Security: SQL Injection Attacks

 

An Example of Business Logic Exploitation using SQL Injection

Imagine a developer needs to show the account numbers and balances for the current user’s id as provided in a URL. They might write (in Java):

String accountBalance

 

Under normal operation, the user with ID 984 might be logged in, and visit the URL:

https://samplebankingwebsite/show_balances?user_id=984

This means that accountBalanceQuery would end up being:

SELECT

This is passed to the database, and the accounts and balances for user 984 are returned, and rows are added to the page to show them.

The attacker could change the parameter “user_id” to be interpreted as:

0 or 1

And this results in accountBalanceQuery being:

Select accountNumber

When this query is passed to the database, it will return all the account numbers and balances it has stored, and rows are added to the page to show them. The attacker now knows every user’s account numbers and balances.

Fixing SQL Injection where Business logic exploitation is performed

You could easily repair this vulnerability by using a prepared statement to create a parameterized query as below:

Fixing SQL Injection

 

If an attacker attempts to supply a value that’s not a simple integer, then statement.setInt() will throw a SQLException error rather than permitting the query to complete.

Imagine a developer implements a login form, and writes (in Java):

User LoginQuery-1

 

Normally, a user would provide a username (say “alice”) and password, and the first query executed would be:

Select user id-1

 

The database returns alice’s user ID and password hash, alice’s password is hashed compared, and then the database gets the list of groups to which alice belongs.

However, if an attacker has alice’s password (maybe the attacker is alice!), they could make alice into an admin. They’d login using the following as a username (newlines added for ease of reading):

 

Insert into

 

This means the query passed to the database would be:

Passwrd hash

 

Note that the single-quote character in the input results in the remainder of the input being interpreted as part of the SQL statement, rather than part of the value. alice will now belong to the group “Administrator.” Note that the attacker can change alice’s group without completing the login process in this scenario; that means an attacker that hasn’t guessed alice’s password could perhaps delete accounts, reset passwords, and the like.

The developer could easily repair this vulnerability by using a prepared statement to create a parameterized query as below:

Parameterized query-1

 

This query will return no results when the 'user' parameter contains a SQL Injection attack, since the parameter's value is sanitized by the PreparedStatement.

Final Thoughts

Despite the grueling outcomes, organizations still don't realize the gravity of SQL injection attacks. It's high time that business owners understand this risk move forward with prevention techniques. The message is simple and clear - if your business relies on a SQL database system, you have to take every possible step to stay safe from the threat of SQL injection. Abiding by a few simple steps will not only safeguard your customers but also save your business.

Appknox SAST can accurately identify SQL injection vulnerabilities and other flaws in your application and its third-party library components , and tell your developers exactly where and how to repair them. All without ever looking at the source code and further the issues can be pushed to jira.

Appknox plugins with Popular CI/CD tools to test for security issues on each build like Azure, Github ,Gitlab , Jenkins, bitbucket.

 

Appknox plugin

 

Our 360 degree-application security platform helps you manage your application security program, track progress, and educate your developers on avoiding and repairing SQL injection and other security flaws.

Appknox Free security consultation

 

Published on Apr 24, 2020
Written by Nishaanth Guna

Questions?

Chat With Us

Using Other Product?

Switch to Appknox

2 Weeks Free Trial!

Get Started Now