How to Prevent SQL Injection Attacks

   

First discovered in 1998, SQL injections (SQLi) are still a devastatingly effective attack technique and remain a top database security priority.

SQL, or Structured Query Language, is the command-and-control language for relational databases such as Microsoft SQL Server, Oracle, IBM DB2 and MySQL. In modern web development, relational databases are a critical resource on the back end of web applications and content management systems written in PHP, .NET, Java EE, Hibernate, SQLite, or other scripting languages. 

Given most websites are built on data in a database server, a malicious SQL injection can be lethal. Attackers can access sensitive information, modify web content, and in catastrophic cases, delete your data. 

This article looks at how your organization can detect vulnerabilities and steps you can take to prevent SQL injection attacks. 

See our picks for top database security tools to help protect your company from SQL injection attacks.

 

Are you vulnerable to a SQL injection attack?

The first step in preventing a SQL injection attack is establishing which, if any, applications are vulnerable. The truth is, any website that interacts with an SQL database is at risk. We dive into the types of automatic detection for SQL injection vulnerabilities, what detection tools do, and vendors specializing in detecting such attacks.  

Self-Imposed Attacks & Detection Types

For detecting SQL injection vulnerabilities, industry advice is personally launching attacks against your application or website. SQL and its variants can be tricky, but attackers know all too well how to construct code snippets that can compromise a database. With automatic detection tools available, testing for vulnerabilities couldn’t be easier.

Almost a decade ago, the US-CERT published Practical Identification of SQL Injection Vulnerabilities to help web administrators fight SQL injection attacks. Their research outlines the types of detection methods to test an application’s responses to specially crafted queries. They include:

SQLi TypeDescription
In-bandThe most popular attack type, in-band SQL injections uses the same communication channel and come in two forms:

Error-based: by testing what queries receive error messages, attackers can craft targeted SQL injections based on the database structure. 

Union-based: by employing the UNION SQL operator, attackers can combine SELECT statements and send results to the GUI. 

InferentialCommonly referred to as “blind SQL injection attacks”, an actor can send payloads reconstructing the structure of the database. The two types of inferential SQLi attacks are:

Boolean-based: by sending SQL queries that force the application to return different results of TRUE or FALSE, attackers can infer if specific payloads return legitimate results. 

Time-based: similar to the latter, this method sends SQL queries asking the database to wait a specific number of seconds before responding. 

In both instances, inferential SQL injection attack methods are quite difficult considering attackers must enumerate data character by character. 

Out-of-bandThe least common of SQL injection attacks, the out-of-band method relies on the database server to make DNS or HTTP requests delivering data to an attacker. 

 

 

 

Testing For SQL Injection Vulnerabilities

There are several free or commercial penetration tools for your organization to determine your SQL injection vulnerability position.

Typically, these tools start by probing your site to determine what type of database is in use. With that knowledge, the program can build queries to examine the characteristics of the database. With little SQL expertise required from the end-user, the detection tool can potentially extract fields, tables, and sometimes even full data dumps from a target.

Perhaps most importantly, many tools offered include an error-fixing feature that can help remove some of the vulnerabilities discovered. Because many powerful SQL injection tools are available open-source, your organization must test your applications before strangers do. 

Also Read: Best Penetration Testing Software for 2021

 

Utilizing An SQLi Detection Tool 

Several cybersecurity vendors and open source developers offer automatic SQL injection tools to identify potential vulnerabilities. For open-source detection tools, SQLMap and jSQL continue to be two of the most popular, with others including:  

 Also Read: With So Many Eyeballs, Is Open Source Security Better?

Steps to prevent SQL injection attacks

Though SQL injection attacks are still the most dangerous threat to web administrators, the good news is that there are plenty website owners can do to mitigate the danger.  

Here are 18 steps you can take to significantly reduce the risk of falling victim to a SQL injection attack:

1. Validate User Inputs

A common first step to preventing SQL injection attacks is validating user inputs. First, identify the essential SQL statements and establish a whitelist for all valid SQL statements, leaving unvalidated statements out of the query. This process is known as input validation or query redesign. 

Additionally, you should configure inputs for user data by context. For example, input fields for email addresses can be filtered to allow only the characters in an email address, such as a required “@” character. Similarly, phone numbers and social security numbers should only be filtered to allow the specific number of digits for each.  

While this action alone won’t stop SQLi attackers, it is an added barrier to a common fact-finding tactic for SQL injection attacks. 

Also Read: IBM AppScan Takes Aim at Input Validation 

2. Sanitize Data By Limiting Special Characters

Another component of safeguarding against SQL injection attacks is mitigating inadequate data sanitization. Because SQLi attackers can use unique character sequences to take advantage of a database, sanitizing data not to allow string concatenation is critical. 

One way of doing this is configuring user inputs to a function such as MySQL’s mysql_real_escape_string(). Doing this can ensure that any dangerous characters such as a single quote ‘ is not passed to a SQL query as instructions. A primary method of avoiding these unauthenticated queries is the use of prepared statements. 

Also Read: Apple White Hat Hack Shows Value of Pen Testers 

3. Enforce Prepared Statements And Parameterization

Sadly, input validation and data sanitization aren’t fix-alls. It’s critical organizations also use prepared statements with parameterized queries, also known as variable binding, for writing all database queries. By defining all SQL code involved with queries, or parameterization, you can distinguish between user input and code.  

While dynamic SQL as a coding technique can offer more flexible application development, it can also mean SQLi vulnerabilities as accepted code instructions. By sticking with standard SQL, the database will treat malicious SQL statements inputted like data and not as a potential command.  

4. Use Stored Procedures In The Database

Similar to parameterization, using stored procedures also requires variable binding. Unlike the prepared statements approach to mitigating SQLi, stored procedures reside in the database and are called from the web application. Stored procedures are also not immune to vulnerabilities if dynamic SQL generation is used.  

Organizations like OWASP say only one of the parameterized approaches is necessary, but neither method is enough for optimal security. Crafting parameterized queries should be done in conjunction with our other recommendations. 

Also Read: Are Your Databases Secure? Think Again  

5. Actively Manage Patches And Updates

Vulnerabilities in applications and databases that are exploitable using SQL injection are regularly discovered and publicly identified. Like so many cybersecurity threats, it’s vital organizations stay in tune with the most recent news and apply patches and updates as soon as practical. For SQLi purposes, this means keeping all web application software components, including database server software, frameworks, libraries, plug-ins, and web server software, up to date. 

If your organization struggles to consistently patch and update programs, a patch management solution might be worth the investment. 

6. Raise Virtual Or Physical Firewalls

We strongly recommend using a software or appliance-based web application firewall (WAF) to help filter out malicious data.  

Firewalls today, including NGFW and FWaaS offerings, have both a comprehensive set of default rules and the ease to change configurations as needed. If a patch or update has yet to be released, WAFs can be handy.  

A popular example is the free, open-source module ModSecurity, available for Apache, Microsoft IIS, and nginx web servers. ModSecurity provides a sophisticated and ever-evolving set of rules to filter potentially dangerous web requests. Its SQL injection defenses can catch most attempts to sneak SQL through web channels. 

Also Read: Firewalls as a Service (FWaaS): The Future of Network Firewalls? 

7. Harden Your OS And Applications

This step goes beyond mitigating SQL injection attacks in ensuring your entire physical and virtual framework is working intentionally. With the big news of supply chain compromises in 2020, many are looking to NIST and other industry-standard security checklists to harden operating systems and applications.  

Adopting application vendor security guidelines can enhance an organization’s defensive posture and help identify and disable unnecessary applications and servers. 

Also Read: Guarding Against Solorigate TTPs 

8. Reduce Your Attack Surface

In cybersecurity, an attack surface refers to the array of potential entry points for attackers. So in the context of SQLi attacks, this means disposing of any database functionalities that you don’t need or further safeguarding them. 

One such example is the xp_cmdshell extended stored procedure in the Microsoft SQL Server. This procedure can spawn a Windows command shell and pass a string for execution. Because the Windows process generated by xp_cmdshell has the same security privileges as the SQL Server service account, the attacker can cause severe damage.  

9. Establish Appropriate Privileges And Strict Access 

Given the power SQL database holds for an organization, it’s imperative to enforce least privilege access policies with strict rules. If a website only requires the use of SELECT statements for a database, there’s no reason it should have additional INSERT, UPDATE, or DELETE privileges.   

Further, your database should only be accessed with admin-level privileges when necessary, nevermind granting others access. Using a limited access account is far safer for general activity and ultimately limits an attacker’s access if the less-privileged credential is compromised. 

Read Also: Top Privileged Access Management (PAM) Software  

10. Limit Read-Access 

Connected to the principle of least privilege for SQL injection protection is configuring read-access to the database. If your organization only requires active users employing read-access, it’s undoubtedly easier to adopt. Nevertheless, this added step is imperative for stopping attackers from altering stored information.  

11. Encryption: Keep Your Secrets Secret

It’s best to assume internet-connected applications are not secure. Therefore encryption and hashing passwords, confidential data, and connection strings are of the utmost importance.  

Encryption is almost universally employed as a data protection technique today and for a good reason. Without appropriate encryption and hashing policies, sensitive information could be in plain sight for an intruder. While only a part of the security checklist, Microsoft notes encryption, “transforms the problem of protecting data into a problem of protecting cryptographic keys.” 

Also Read: Best Encryption Tools & Software for 2021 

12. Deny Extended URLs

Another tactic by SQLi attackers is sending excessively long URLs causing the server to fail at logging the complete request. In 2013, eSecurityPlanet reported on how attackers exploited Foxit by sending users long URLs that would trigger a stack-based buffer overflow. 

Microsoft IIS, as another example, is built to process requests over 4096 bytes long. However, the web server software fails to place the contents of the request in the log files. Attackers can then go undetected while performing queries. To avoid this, set a limit of 2048 bytes for URLs. 

13. Don’t Divulge More Than Necessary In Error Messages

SQL injection attackers can learn a great deal about database architecture from error messages, ensuring that they display minimal information. Use of the “RemoteOnly” customErrors mode (or equivalent) can display verbose error messages on the local machine while ensuring that an external attacker gets nothing more than the fact that his or her actions resulted in an unhandled error. This step is critical in safeguarding the organization’s internal database structure, table names, or account names. 

Also Read: How to Bake Better Security into Applications 

14. No Shared Databases Or User Accounts

Shared databases by multiple websites or applications can be a recipe for disaster. And the same is true for user accounts that have access to various web applications. This shared access might provide flexibility for the managing organization or administrator, but it also unnecessarily poses a more significant risk. 

Ideally, any linked servers have minimal access to the target server and can only access the mission-critical data. Linked servers should have distinct logins from any process on the target server. 

Also Read: Cloud Bucket Vulnerability Management in 2021 

15. Enforce Best Practices For Account And Password Policies

While it might go without saying, organizations must follow the best account and password policies for foolproof security. Default and built-in passwords should be changed upon receipt and before usage, with regularly scheduled password updates. Suitable passwords in length and character complexity are essential for all SQL server administrator, user, and machine accounts.  

16. Continuous Monitoring Of SQL Statements

Organizations or third-party vendors should continually monitor all SQL statements of database-connected applications for an application, including documenting all database accounts, prepared statements, and stored procedures. With visibility into how SQL statements function, it’s much easier to identify rogue SQL statements and vulnerabilities. In this continued review, admins can delete and disable unnecessary accounts, prepared statements, and stored procedures.  

Monitoring tools that utilize machine learning and behavioral analysis like PAM and SIEM can be excellent add-ons to your network security. 

Also Read: Best SIEM Tools & Software for 2021  

17. Perform Regular Auditing And Penetration Testing

Regular audits of your database and application security are becoming increasingly necessary, including auditing logs for suspicious activity, group and role memberships privileges, and variable binding terms.  

Just as crucial as auditing for malicious behavior is conducting penetration tests to see how your defenses respond to an array of potential attacks, including SQLi. Most penetrating testing companies can find threats such as cross-site scripting, retired software, unpatched vulnerabilities, injections, and insecure passwords. 

Also Read: Automating Security Risk Assessments for Better Protection 

18. Code Development & Buying Better Software

In the vast market of software solutions, there’s certainly a hierarchy of solutions. While enterprise organizations can cover the cost of expensive third-party solutions and might even develop the software further in-house, smaller organizations rightfully work with less or consider free, open-source tools.  

Though, to a great extent, vendor code writers are ultimately responsible for flaws in custom applications for a client. Organizations considering vendors must be keen on this and ensure the contract terms reflect this code review duty.

Also Read: Securing Web Application Code at the Source  

Stopping SQL injections recap

Much like the spirit of zero trust security, mitigating SQL injection attacks means leaning into the fear that all user-submitted data could be malicious. Instead of giving attacks any leverage over SQL vulnerabilities, we encourage you to consider our recommendations and make a plan to review your SQL security posture.  

While first database security steps like input validation, sanitization, prepared statements, and stored procedures are essential, they are the floor. To maximize protection against SQLi attacks, organizations need to also consider solutions like:  

0 Comments

disawar satta king