National CSIRT-CY | National Computer Security Incident Response Team of Cyprus

Η Εθνική Ομάδα Αντιμετώπισης Ηλεκτρονικών Επιθέσεων προβλέπει την αύξηση της ηλεκτρονικής ασφαλείας ενισχύοντας την προστασία του κυβερνοχώρου των Εθνικών Κρίσιμων Πληροφοριακών Υποδομών, των τραπεζών και των παροχών επικοινωνίας της Κυπριακής Δημοκρατίας.

What is SQL Injection and How to Prevent SQLi Attacks

05 April 2021

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.

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.

SQLi Type Description
In-band The 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.

Inferential Commonly 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-band The 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.

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.

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.

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.

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.

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.

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.

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.

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.”

12. Deny Extended URLs

Another tactic by SQLi attackers is sending excessively long URLs causing the server to fail at logging the complete request. I

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.

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.

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.

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.

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.

Stopping SQL injections Summary

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:

  • Privileged Access Management (PAM)
  • Penetration Testing
  • Security Information and Event Management (SIEM)
  • Next-Generation Firewall (NGFW)
  • Network Access Control (NAC)
  • Intrusion Detection and Prevention (IDPS)
  • Threat Intelligence
  • User and Entity Behavior Analytics (UEBA)

Working towards a trusted and cyber secure Europe

Protect your cyber hygiene

Cyber Europe 2022 [exercise]

Cyber threats require heightened defences

News
Απλές και καθημερινές συμβουλές ασφάλειας στον κυβερνοχώρο για τα παιδιά και τους γονείς Πώς να ελέγξετε αν το τηλέφωνό σας έχει παραβιαστεί; 5 σημάδια για να καταλάβετε Κυβερνοασφάλεια: Ένα ασφαλέστερο διαδίκτυο αρχίζει μαζί με την νέα σχολική χρονιά… Κενό ασφαλείας WinRAR χρησιμοποιείται σε επιθέσεις Zero-Day Μνημόνιο Συνεργασίας μεταξύ του Επιτρόπου Προστασίας Δεδομένων Προσωπικού Χαρακτήρα (ΕΠΔΠΧ) και του Επιτρόπου Επικοινωνιών (ΕΕ) Μνημόνιο Συναντίληψης και Συνεργασίας μεταξύ της Αρχής Ψηφιακής Ασφάλειας και του Κυπριακού Εμπορικού και Βιομηχανικού Επιμελητήριου Συναντήσεις Επιτρόπου Επικοινωνιών κ. Γιώργου Μιχαηλίδη στα γραφεία της ITU Ευρώπης στην Γενεύη. Ο Βοηθός Επίτροπος Επικοινωνιών κ. Πέτρος Γαλίδης στον Alpha Κύπρου Πώς να αποτρέψετε τις επιθέσεις Ransomware: Οι 10 καλύτερες πρακτικές για το 2023 Επίτροπος Επικοινωνιών, Γιώργος Μιχαηλίδης στο ΚΥΠΕ: Στις 700 αυξάνει τις κρίσιμες υποδομές η οδηγία NIS