protecting against malicious sql injection - mysql

I have a bunch of perl CGIs that take params and use their values in various DBI mySql queries.
Is there any way that a malicious user can do harm (or steal data) from my system if I don't allow any user submitted values that contain the words select, insert, delete, or update to be used as parameters and as long as I wrap all the varchar user provided values in single quotes?
I realize this question is very similar to others asked, but the others all seem to point to various PHP solutions, and I'm not using PHP, so, please forgive the redundancy, or point me to an associated question that answers this specific question.

The correct way to handle this in Perl use to use placeholders in all your SQL queries. Passing user-supplied data via DBI placeholders will ensure that everything is properly quoted. (That doesn't guarantee that it's secure, of course, but it will prevent SQL injection.)

Use parameterized queries. Then the user input is not part of the command at all, which is the only reliable way to know the command won't be modified.

Related

are stored procedures really secure against sql injections

I need to convince someone that he needs to sanitize the user input in addition to the user of stored procedures. well I know I sound crazy but I do not feel comfortable enough with store procedures only. My first reason is that I am able to cause errors in the stored procedure but because of the fact that the application itself handles errors such that error messages are coded it is difficult for outside to understand the what there are. but I still think that this is not secure.
Does any one has a suggestion ? or am I wrong to doubt stored procedures?
No it's not safe on it's own. You can also do in a stored procedure something like this:
SET #sql = 'Select * from products where name like ''' +#spinput+''' ';
exec(#sql);
With the wrong value in #spinput you can inject code.
However you can write stored procedures that are safe against sql injection.
Even if you use proper parameters, you can still mess with the database. You could insert a script that goes in as a parameter, but when it's displayed on a web page starts doing something it shouldn't. Use parameters to ensure your database is used as intended, but also sanitize the output later - never trust user-entered data.
Using stored procedures normally protects against SQL injection, but is not the only solution to prevent SQL injections, and it doesn't protect against all forms of SQL injection.
It's not the stored procedure itself that makes the big difference, but parameterised queries, which is the most common way to call a stored procedure. By putting the values used by the query in parameters, you let the database library handle them instead of having to escape them correctly yourself.
It's possible to write code that is safe against SQL injections without using parameterised queries, but it's difficult. You have to know exactly what characters you need to escape in a string for the specific database that you are using, and if you get it wrong you are pretty much as unprotected as if you didn't know about SQL injections at all.
If you use parameterised queries, then the step of sending the values into the database is safe from SQL injection, but the query itself might not be. If the query generates and executes SQL code itself, you have the same problem with escaping strings correctly. It's however not so usual to create SQL code in the SQL code, and if you do it you are very aware of that you are doing it.

mySQL: Stored procedures are more secure than queries?

I have a website using mySQL database and I want to do common tasks like add users, modify their info, etc. I can do it perfectly with regular queries. Im using prepared statements to increment security.
Should I use stored procedures to increment the security or the results will be the same? I though that may be using stored procedures I can restrict the direct interaction that a possible attacker could have with the real query. I'm wrong?
I guess it would depend on what language youre using. Using a prepared statement with a sql string that contains all of the sql to be executed, or using a prepared statement with a sql string that executes a stored procedure are going to be about equivalent in most languages. The language should take care of the security around the prepared statement. C# for example will validate the input, so sql injection vulnerabilities are greatly reduced unless your prepared statement is written so poorly that feeding it bad (but expected, ie, 1 vs 0) variables will dramatically change the result set. Other languages may not provide the same level of validation though, so there may be an advantage depending on exactly what your stored proc looks like.
Using a stored procedure is better for maintainability, but there are not many scenarios where its going to provide any sort of change in security level, assuming the program is properly designed to begin with. The only example i can think of off the top of my head would be a stored procedure that takes raw sql strings from user input, and then executes that sql against the db. This is actually less secure than using a prepared statement unless you went to great lengths to validate the acceptable input, in which case you better have a really good reason for using such a stored proc in the first place.
Basically, what I'm saying boils down to the fact that you're going to need to read the documentation for your language about prepared statements, and determine what vulnerabilities, if any, using prepared statements may have, and whether or not those can be eliminated in your specific scenario by switching to a prepared statement that calls out a stored procedure instead of executing a sql query directly.
The results would be the same (assuming that you set your stored procedure up right).
there appears to be a pretty good write up on it here. Though I would never suggest you try to escape user input yourself. (They mention this as option 3)

Mysql Database Attacks other than Sql Injection

I am using mysqli prepared statements and bound variables.
Then to prevent sql injection, am I need to do anything else(eg: data type validation, filtering, sanitize, string escape etc ) with user input ?
Is there any other way of attacking MySql database other than Sql Injection ?
To prevent SQL injection you have to format your query properly.
Every literal that have to be added to the query dynamically, have to be properly formatted.
Not only data literals like strings and numbers but all of them, including operators and identifiers.
The only proper way to make values formatted is prepared statements.
For the identifiers and operators you will need also filtering, to let only allowed ones into query.
Whatever user input should not be involved at all. It's destination, not source that matters.
Is there any other way of attacking MySql database other than Sql Injection ?
sure thing. But the topic is too broad to make you secured by means of a forum post. Better hire a DBA.

Which SQL inject methods aren't "destroyed" by mysql_real_escape_string();?

Is there a list of SQL injection methods which can't be protected with just using mysql_real_escape_string(); with utf8 encoding?
For integer, I'm using intval();
Is it secure enough?
For those who think I want to get "tutorial" to hack anyone: No, I won't. I just want to know how to make my applications more secure, and I want to know if they're secured 99% against hackers
If given a valid database connection, mysql_real_escape_string() is supposed to be safe for string data under all circumstances (with the rare exception described in this answer).
However, anything outside a string, it won't escape:
$id = mysql_real_escape_string($_GET["id"]);
mysql_query("SELECT * FROM table WHERE id = $id");
is still vulnerable, because you don't have to "break out" of a string to add an evil additional command.
There are not many sql injection methods. They are always due to input not being sanitized and escaped properly. So, While mysql_real_escape_string() will make any string safe to be included in a database query, you should follow the following avoidance techniques to protect your data and users from sql injection.
Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
Check if the given input has the expected data type.
If the application waits for numerical input, consider verifying data with is_numeric(), or silently change its type using settype()
Quote each non numeric user supplied value that is passed to the database with the database-specific string escape function. So mysql_real_escape_string() will make all strings safe to be included in an SQL query to a mysql database
You could also learn to use stored procedures and prepared statements which tend to be very safe but have other impacts
See also: PHP page on SQL injection
There are many things that may not get protected by standard methods (e.g. string escaping, int casting), also depending on the version of software you use. For example, utf-8 is quite an issue by itself, as a tiny example (among many) you should make sure the request is valid utf-8 (or convert it into utf-8). See an example.
As the undead bane of websites, I think that MySQL injection protection cannot be squeezed into a single SO answer, hence I'm including these links as general starting points.
http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
And also : Search for mysql injection utf8

Are dynamic mysql queries with sql escaping just as secure as prepared statements?

I have an application which would greatly benefit by using dynamic mysql queries in combination with mysql (mysqli) real escape string. If I ran all data received from the user through mysql real escape would it be just as secure as using mysql prepared statements?
Yes, but a qualified yes.
You need to properly escape 100% of the input. And you need to properly set character sets (If you're using the C API, you need to call the mysql_set_character_set() instead of SET NAMES). If you miss one tiny thing, you're vulnerable. So it's yes, as long as you do everything right...
And that's the reason a lot of people will recommend prepared queries. Not because they are any safer. But because they are more forgiving...
Definitely NO.
While question in the title is ambiguous and can be interpreted as "Are dynamic mysql queries with every it's part properly formatted..." and thus have a positive answer, the question in the body is not:
If I ran all data received from the user through mysql real escape would it be just as secure as using mysql prepared statements?
If you look to this question closer, you will understand that this is just a magic quotes incarnation! The very purpose of this disgraced, deprecated and removed feature is exactly to "run all user input through escape".
Everyone knows nowadays that magic quotes are bad. Why positive answer then?
Okay, it seems that it needs to be explained again, why bulk escaping is bad.
The root of the problem is a quite strong delusion, shared by almost every PHP user:
Everyone have a strange belief that escaping do something on "dangerous characters" (what are they?) making them "safe" (how?). Needless to say that it's but a complete rubbish.
The truth is:
Escaping do not "sanitize" anything.
Escaping has nothing to do with injections.
Escaping has nothing to do with user input.
Escaping is merely a string formatting and nothing else.
When you need it - you need it despite of injection possibility.
When you don't need it - it won't help against injection even a little.
Speaking of difference with prepared statements, there is at least one issue (which already mentioned many times under sql-injection tag):
a code like this
$clean = mysql_real_escape_string($_POST['some_dangerous_variable']);
$query = "SELECT * FROM someTable WHERE somevalue = $clean";
will help you NOT against injection.
Beause escaping is just a string formatting facility, not injection preventer by any means.
Go figure.
However, escaping have something in common with prepared statements:
Them both doesn't guarantee you from injection if
you are using it only against notorious "user input", not as a strict rule for the building ANY query, despite of data source.
in case you need to insert not data but identifier or a keyword.
To be safe in these circumstances, see my answer explaining FULL sql injection protection how-to
Long story short: you can consider yourself safe only if you make 2 essential corrections and one addition to your initial statement:
If I ran all data received from the user through mysql real escape and always enclose it in quotes (and, as ircmaxell mentioned, mysqli_set_charset() is used to make mysqli_real_escape string() actually do it's work (in such a rare occasion of using some odd encoding like GBK)) would it be just as secure as using mysql prepared statements?
Following these rules - yes, it would be as secure as native prepared statements.
I think #ircmaxell got it right on.
As a follow-up, be on the lookout for this kind of thing.
I used to do it all the time:
<?php
//sanitize the dangerous posted variable...
$clean = mysql_real_escape_string($_POST['some_dangerous_variable']);
//...and then forget to use it!
$query = "SELECT * FROM someTable WHERE somevalue = '{$_POST['some_dangerous_variable']}'";
?>
And when I say "used to do it", what I mean is that I eventually gave up and just started using prepared statements!