If you have read our previous posts, in two posts we talk bot the security issues of websites and web apps. For all too many companies, it’s not until after a security breach has occurred that web security best practices become a priority. During my years working as an IT Security professional, I have seen time and time again how obscure the world of web development security issues can be to so many programmers.
Now a day, SQL Injection represents a serious threat to Internet security for various dynamic Web applications residing on the Internet. These web applications drive many vital processes in various web-based businesses. As the use of the Internet for various online services grows, security threats on the Web are also increasing. There is a universal need for all dynamic web applications and this universal need is the need to store, retrieve or manipulate information from a database. Most systems that manage databases and their requirements, such as MySQL Server and PostgreSQL, use SQL as the language. The flexibility of SQL makes it a powerful language. It allows its users to ask what he/she wants without disclosing any information on how the data will be recovered. However, the extensive use of SQL databases has attracted the attention of hackers. They take advantage of poorly coded web applications to attack databases. They introduce an apparent SQL query, via unauthorized user input, into the legitimate request statement. In this article, we have tried to present a complete review of all the different types of SQL injection attacks present, as well as the detection of such attacks and the preventive measures used. We highlighted their strengths and weaknesses. Such a classification would help other researchers to choose the right technique for further studies.
SECURITY IS THE MAIN PARMAMETRE
An effective approach to web security threats must, by definition, be proactive and defensive. Toward that end, this post is aimed at sparking a security mindset, hopefully injecting the reader with a healthy dose of paranoia.
In particular, this guide focuses on 10 common and significant web security pitfalls to be aware of, including recommendations on how they can be mitigated. The focus is on the Top 10 Web Vulnerabilities identified by the Open Web Application Security Project (OWASP), an international, non-profit organization whose goal is to improve software security across the globe.
MOST COMMON WEBSITE SECURITY VULNERABILITIES
From the biggest data breaches and cyber-attacks of the past decade, it is quite clear that marginal and careless mistakes and lapses in website security have turned out to be dangerous. Even big players have faced heavy losses, not just monetarily but in terms of customers, trust, brand image, and goodwill as a result of the attacks.
We have compiled the list of 10 most dangerous website security mistakes that you must avoid.
1–SQL INJECTIONS (INJECTION FLAWS)
2- CROSS SITE SCRIPTING (XSS)
3. BROKEN AUTHENTICATION & SESSION MANAGEMENT
4. INSECURE DIRECT OBJECT REFERENCES
5. SECURITY MISCONFIGURATION
6. CROSS-SITE REQUEST FORGERY (CSRF)
7- SENSITIVE DATA EXPOSER
8- MISSING FUNCTION LEVEL ACCESS CONTROL
9- USING COMPONENTS WITH KNOWN VULNERABILITIES
10- Invalidated redirects and forwards
IRREGULAR OR NO WEBSITE SECURITY SCANS. The importance of regular website security scanning cannot be stressed enough. It is only through regular scanning that we can find vulnerabilities and gaps that exist, and accordingly, fix them. Organizations often make the cardinal error of not scanning their websites every day and after major changes to the business policies, systems, etc
What is SQL Injection Attacks
The OWASP Top 10 lists Injection and Cross-Site Scripting (XSS) as the most common security risks to web applications. Indeed, they go hand in hand because XSS attacks are contingent on a successful Injection attack. While this is the most obvious partnership, Injection is not just limited to enabling XSS.
The injection is an entire class of attacks that rely on injecting data into a web application to facilitate the execution or interpretation of malicious data unexpectedly. Examples of attacks within this class include Cross-Site Scripting (XSS), SQL Injection, Header Injection, Log Injection, and Full Path Disclosure. I’m scratching the surface here.
This class of attacks is every programmer’s bogeyman. They are the most common and successful attacks on the internet due to their numerous types, large attack surface, and the complexity sometimes needed to protect against them. All applications need data from somewhere to function. Cross-Site Scripting and UI Redress are, in particular, so common that I’ve dedicated the next chapter to them and these are usually categorized separately from Injection Attacks as their class given their significance.
OWASP uses the following definition for Injection Attacks:
Injection flaws, such as SQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing unauthorized data.
By the way, Injection flaws result from a classic failure to filter untrusted input. It can happen when you pass unfiltered data to the SQL server (SQL injection), to the browser (XSS – we’ had been talked about this before), to the LDAP server (LDAP injection), or anywhere else. The problem here is that the attacker can inject commands to these entities, resulting in loss of data and hijacking clients’ browsers.
Anything that your application receives from untrusted sources must be filtered, preferably according to a whitelist. You should almost never use a blacklist, as getting that right is very hard and usually easy to bypass. Antivirus software products typically provide stellar examples of failing blacklists. Pattern matching does not work.
in the other definition,
SQL Injection operates by injecting data into a web application which is then used in SQL queries. The data usually comes from untrusted input such as a web form. However, it’s also possible that the data comes from another source including the database itself.
Programmers will often trust data from their database believing it to be completely safe without realizing that being safe for one particular usage does not mean it is safe for all other subsequent usages. Data from a database should be treated as untrusted unless proven otherwise, e.g. through validation processes.
If successful, an SQL Injection can manipulate the SQL query being targeted to perform a database operation not intended by the programmer.
Please consider the following query:
$db = new mysqli('localhost', 'username', 'password', 'storedb');
$result = $db->query(
'SELECT * FROM transactions WHERE user_id = ' . $_POST['user_id']
The above has several things wrong with it.
1- First of all, we haven’t validated the contents of the POST data to ensure it is a valid user_id.
2- Secondly, we are allowing an untrusted source to tell us which user_id to use – an attacker could set any valid user_id they wanted to. Perhaps the user_id was contained in a hidden form field that we believed safe because the webform would not let it be edited (forgetting that attackers can submit anything).
3- Thirdly, we have not escaped the user_id or passed it to the query as a bound parameter which also allows the attacker to inject arbitrary strings that can manipulate the SQL query given we failed to validate it in the first place.
The above three failings are remarkably common in web applications.
How to Protect Yourself Against SQL Injection Attacks
With user input channels being the main vector for SQL injection attacks, most of the defensive methods involve controlling and vetting user input for attack patterns.
Here are several measures that can ensure user input safety.
1-Never trust user input
The first rule of thumb about user input is “don’t trust and verify,” which effectively means all forms of the user input should be considered malicious unless proved otherwise. This accounts not only for simple input boxes such as text areas and text boxes but for everything else as well — such as hidden inputs, query string parameters, cookies, and file uploads.
Just because the browser’s user interface doesn’t allow the user to manipulate an input, it doesn’t mean that it can’t be tampered with. Simple tools such as Burp Suite enable users to capture HTTP requests and modify anything, including hidden form values, before submitting them to the server. And if you think yourself clever by Base64 encoding your data, it can easily be decoded, modified and re-encoded by malicious users.
2-Validate input strings on the server-side
Validation is the process of making sure the right type of input is provided by users and to neutralize any potential malicious commands that might be embedded in the input string. For instance, in PHP, you can use the mysql\_real\_escape\_string() to escape characters that might change the nature of the SQL command.
An altered version of the previously-mentioned login code would be as follows:
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql_command = "select * from users where username = '" . $username; $sql_command .= "' AND password = '" . $password . "'";
This simple modification would protect your code against the attack that was presented by adding an escape character (\) in front of the single quotes that were intentionally added by the malicious user.
A note on validation:
If you’ve added client-side validation functions, well done. But don’t rely on it as a defensive measure against SQL injection attacks. While client-side functions might make it a notch harder to send malicious input to your server, it can easily be circumvented with a few browser tweaks and tools such as the one just mentioned. Therefore, you need to complement it with server-side validation.
Some programming platforms, such as #ASP.NET, include built-in features that will automatically evaluate user input for malicious content on page postbacks. But they can be circumvented by hackers with enough nerves and subtlety, so you should nonetheless run user input through your security check procedures. You can never be too cautious.
3-Use command parameters
A better alternative to escaping would be to use command parameters. Command parameters are defined by adding placeholder names in SQL commands, which will later be replaced by user input. ASP.NET has a very intuitive and easy-to-use set of APIs for this purpose.
The following code, written in C#, shows how you can use the command parameters to protect your website against SQL injection:
SqlCommand cmd = new SqlCommand ("SELECT * FROM users WHERE username=@username AND password=@password",con);
SqlParameter username = new SqlParameter(); username.ParameterName = "@username"; username.value = txtUsername.Text; cmd.Parameters.Add(username);
SqlParameter password = new SqlParameter(); password.ParameterName = "@password"; password.value = txtPassword.Text; cmd.Parameters.Add(password);
you start by creating a
SqlCommand object and using the
@parameter_namethe paradigm in the command string where user input should be inserted.
You then create instances of
SqlParameter objects, in which you insert the user input, instead of directly concatenating it with the command string.
Finally, you add the
SqlParameter object to the
SqlCommand object’s Parameters collection, which will replace the parameters with the provided input. ADO.net takes care of the rest.
In PHP, the equivalent is prepared statements, which is a bit more involved than its ASP.net counterpart. You can explore it here.
4-Explicitly cast your input
This tip is for languages such as PHP, which are weakly typed, which means you do not usually define data types for variables, and the language automatically takes care of converting different data types between each other.
Explicit casts can act as a shortcut to escaping input where non-string types are involved. So, if you’re expecting the user to input an
int for the
age parameter, you can ensure the safety of the input with the following code in PHP:
$age = (int)$_POST['age'];
Take note that this snippet only validates the input’s type, not its range. So you’ll have to run other code to make sure the user doesn’t enter a negative age — or an unrealistic one such as 1300.
Also, another best practice is to avoid using single quotes in SQL commands where non-string input is involved. So instead of using the following code …
$sql_command = "select * from users where age = " . $age;
… it would be a bit safer to use the following one:
$sql_command = "select * from users where age = '" . $age . "'";
The good news is that protecting against injection is “simply” a matter of filtering your input properly and thinking about whether an input can be trusted. But the bad news is that all input needs to be properly filtered unless it can unquestionably be trusted (but the saying “never say never” does come to mind here).
In a system with 1,000 inputs, for example, successfully filtering 999 of them is not sufficient, as this still leaves one field that can serve as the Achilles heal to bring down your system. And you might think that putting an SQL query result into another query is a good idea, as the database is trusted, but if the perimeter is not, the input comes indirectly from guys with malintent. This is called Second Order SQL Injection in case you’re interested.
Since filtering is pretty hard to do right (like crypto), what I usually advise is to rely on your framework’s filtering functions: they are proven to work and are thoroughly scrutinized. If you do not use frameworks, you need to think hard about whether not using them makes sense in your server security context. 99% of the time it does not.
in the other word, SQL injection has been around for decades and will likely continue to top the vulnerability charts for years to come. It takes a few easy — but well-calculated — steps to protect yourself and your users against it, and it should be among your top priorities when auditing your source code for security holes.
The key to avoiding being the victim of the next huge SQL injection data breach is first, to control and validate user input, and second, to prepare yourself for the “when,” not the “if.”