paint-brush
Top 5 Ways To Prevent SQL Injectionsby@ellarich
937 reads
937 reads

Top 5 Ways To Prevent SQL Injections

by Hacking LoopsApril 11th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Injecting malicious SQL script into a database is what we named SQL injection. An attacker can obtain user information, even admin login credentials, via a SQL attack. An insecure database spits out all the information just by this simple command. The crime is serious. If the codebase is not secure, testing functions are live on the real-world database, inputs aren't satanized adequately. We are going to discuss in-depth details and ways to prevent SQL injections throughout the article.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Top 5 Ways To Prevent SQL Injections
Hacking Loops HackerNoon profile picture

SQL stands for Structured Query Language. SQL is used to communicate directly with the database. It is pronounced as "ess-que-el" or "see-que-el". For managing databases, it is the standard language set by the American National Standards Institute (ANSI). What do we do with SQL? Like our web page depends on HTML, CSS, JavaScript to function: SQL is used to modify, update, implement changes to the database. 

SQL Server, Microsoft Access, Informix, Oracle, Sybase are a few database management systems that work with SQL. Commanding a database doesn't need complex scripting. Most of the scripts are hardcoded beforehand and pushed as rules with the database management system (DBMS). We use simple commands such as "Update", "Select", "Insert", "Delete", "From", "Like", "Where" etc. followed by question marks (?) for regular interactions with the database. 

What is SQL injection?

We know what SQL is, and attacking with the same knowledge or misleading the tools to gain an unfair advantage would be something that we can call an SQL attack. Injecting malicious SQL script into a database is what we named SQL injection. 

The attack is quite common and has been executed for a very long time. An attacker can obtain user information, even admin login credentials, via a SQL attack. It leads to a sitewide control, and the attacker would have the ability to do whatever purpose the data is accessed for. The crime is serious. If the codebase is not secure, testing functions are live on the real-world database, inputs aren't satanized adequately, then a web server is prone to SQL injection. There are plenty of other weaknesses that a web application may have. Talking with a database uses command as we know, and it is almost plain English. It's not a feature that made SQL injections more viable, but this is the way, and it has existed for many years. We are going to discuss in-depth details and ways to prevent SQL injections throughout the article. 


This simple command line on the database is used to find a specific item. The general user perspective can be the search bar where the "keyword" is being used. It looks exactly like the image, depending on the IDE used from an injector or a database manager prospect.


Here, we modified the code a bit to check what our server responds to the query. We changed the keyword inside the single quote marks to see how our server or target responds. And a part of our syntax became grey. 

We can find out the type of database management system used in this particular server. And there are plenty of ways to do so. Our grey indication puts out that the server used MySQL. An insecure database spits out all the information just by this simple command. 


Tempering with the delay function can quickly reveal which DBMS has been used. In the code above, after the keyword, we put a delay function. On MySQL, the delay function is "SLEEP." So, we put the delay function for a few seconds. After the 10 second interval we specified, the server sends out information. And this is how we can determine the type of SQL server used. MySQL uses the "SLEEP" function, and Oracle uses DBMS_SESSION.SLEEP or DBMS_LOCK.SLEEP. Yes, it is pretty normal to find out certain aspects easily just by its delay or time management behavior.

SQL injection evolution

Understanding how we gradually managed to find loopholes developed solely for our good is a slight brainteaser. We have databases that store information. Or the website that is hosted on a remote server. If we want to access it, we use credentials and request data. The same way we insert data into the webserver. Like product info, price update, stock numbers, and more. We gradually improved our technical knowledge, and at the same time, technology evolved. Hackers request data from the database. And this data is not permissible to access by an outsider. While the invention is pretty incredible, the attacker misuses the data and tries to implement changes on the input terms that give out different results. But we have indeed come a long way since the 19070s, where IBM researchers developed and used SQL for the first time. 

Top 5 ways to prevent SQL injections

There are many ways to temper with the SQL database; there are more ways to make sure that these don't go unnoticed. We are going to point out the most UpToDate ways to prevent SQL injections. 

1. Prepared Statement

Experienced developers don't leave this one unchecked, as preparing statements is one of the primary and most important rules to prevent SQL injections. Parameterized queries are sometimes referred to as prepared statements. Prepared statements work with a variable bind. Variable bind and dynamic queries work hand in hand. But they are simpler to write and eventually implement in the database. What a prepared statement does to a database is that it defines SQL query before passing parameters. As a result, the query becomes subtle and not changeable by attackers. 


Here are some of the different types of Prepared statements by different programming languages. Parameterizing queries makes it hard for an attacker to insert a query. We have previously stated the commands used in the SQL injection. Each language has its way to use parameterizing quarries. 


As we can see, PHP variables are already set just like every other function in a code. Every assignation of variables like username, user id, password, email function has already been declared in our script. What we need to do now is, rule the specific variables to work on the given roles. 


Compared to SQL execution, prepared statements talk directly with the database to have advantages like reduced parsing time and cuts away SQL injection vulnerability. It takes single parameters while working with it rather than the whole query. 


Here is another statement that falls under the prepared statement and parameterized queries. It is a safe way to proceed with coding the SQL database. Parameterized statements are one of the vital parts of protection against SQL injections.

2. Input Validation

Input validation is one of the primary defenses that work with SQL injection prevention methods on the front line. In simple words, whatever input is there, the validation process dissects if the input type is allowed or not. And even what kind of user has permission to use this type of inputs. Inputs are integers (whole number, both positive and negative), plain text (simple words), floats (numbers with decimal points). Outside of that parameter or a specifically structured function gets skipped, and that works as input validation. 

OWASP input validation or OWASP WebGoat is a simplified platform that teaches the general practice of input validation. There is a considerable number of input fields other than we mentioned above. File or document uploader, modern websites that work with AI has different sorts of input fields. These are values predefined by buttons or inputs with multiple-choice options. Input validation only accepts input that is predefined hence removes misuse of the database. A rule of thumb for input validation is whitelisting regular expressions rather than blacklisting. Validation includes general user information like name, age, or zip code, etc. There should be a set of fixed cases. 


In this PHP snippet, we mentioned a worldly example of actual code. "Mode" here defines the basic theme of an interface. The input takes in user data and transforms the website accordingly. Here, modes are "Light" and "Dark." It is widespread among most web applications today. This input should be defined beforehand of which setting to change and how it impacts the database. Rather than that, it shouldn't have the power to change any other functions. This one is radio button input. Similar goes for the blank space inputs. What our goal is to define functions as precisely as possible. 

3. Escaping

Whenever we request data from a database, it looks for the easiest and the "fastest" way to analyze the query. The complication is how we defined the query, what we want to access and how the SQL server handles the execution. One of the significant ways an attacker can perform an SQL injection is by utilizing this common mistake. Escaping all character functions may make the system a bit choppy, but hey, we didn't choose SQL management for the fastest solution there is. Instead, we decided on SQL for being user-friendly, secure, and accurate with our data. A simple escaping method is adding a single quote followed by an escape character ('\). 


For Database Management System (DBMS), we recommend escaping user-defined characters. What differentiates between the escaping and non-escaping part is, it doesn't confuse outside data with the admin command. If prepared statements work correctly, escaping every character is not necessary. It's an important note not to mention. Because parameterized characters already contain some escape of characters. 

4. Firewall & Administrative Privilege

A standard method to gain sensitive information via SQL injection is capturing the admin account itself. The administrator account holds all the right to delete, modify and insert data. Also, it can add an outsider with enough privilege to do as much as the admin account because it has the root access. Our recommendation is not to use an administrative account in the database. Other accounts with fair privileges as the administrator account hold similar threats. Each application should have its database for the safety of the whole web application. When creating accounts with more minor features, don't take away the privilege ticks; instead, give ticks that are solely important for the task. This way, it would be easy to monitor and maintain a steady and secure system. 

Firewalls are also vital to protect against SQL injections because they guard the database and the system even in the absence of human contact—predefined rules and procedures set by the standard SQL injection method help the firewall stay updated. Web Application Firewall (WAF) monitors traffic and, most importantly, puts a barrier that works as a shield against low-level threats. It is easy to add policies and rules that bypass the firewall without prompting a false alarm. An excellent firewall solution is PTSecurity. They also roll out regular updates on what's new in the firewall department. The firewall generally blocks out SQL injections, cookie capture, parameter tampering and gives real-time analytic of the traffic data. 

5. Union & Password Hash

Union keys are pretty important when it comes to SQL injection prevention methods. Summing up two or more queries in a single result is the work of the union key. These queries belong to the union row. Suppose A U B is a function. A has a set of {1,2,3} & B consists of {4,5}. If we use the general union formula, then it becomes {1,2,3,4,5}. This general principle can combine with more rows to give out the desired result, like in row 5, column 8. Yes, with this kind of accuracy, the union works. We can implement multiple queries in one union. 


On the other hand, to access a database, we need a password. The more secure the password, the harder it is to crack for an attacker. Simple passwords can be cracked concisely by brute-forcing, phishing, keylogging, and more ways. Though they need to be changed periodically, most of its definition depends on strength. Hashing password is kind of like encrypting. 


Various ways we can hash passwords, sh256, caching are some of the better ways. These are some of the primary ways to protect against SQL injections.

Safe database management, placing dummy functions such as "dual" for testing purposes should be removed. Testing kits are for making things easy before live implementation. Also, server pinging should be off; it can be used as a DDoS attack rather than a SQL injection. But it benefits both simultaneously. 

Conclusion 

Certain aspects of protection against SQL injection welcome the safe practice of doing stuff. These can be maintaining awareness, employ verified mechanisms, automation blocking, and more. An attacker can quickly push multiple SQL injection sequences in a python script that runs very fast and cramp up more data than you think in a single sitting. Those codes are available in GitHub for testing and learning purposes only. These run tests only on permitted applications as a penetration tester or learning on your own VM. 

Allowing the most minorly privileged roles and listing inputs for validations would strongly argue against unethical injection. Also, this goes without saying, scanning for vulnerabilities alongside bug fixes is a typical task to stay protected against SQL injections. But the points we mentioned earlier in bold are the most important and primary ones. Using only the required applications to handle a task such as WAF can easily protect against SQL injections.