Can someone give me a little help with this? i have three PHP SQL querys, and i have to protect from SQL Injection. I am searching on google but i think is too hard for me, because it's combinated with PHP and i dont know munch about PHP and lees about SQL
if someone can give me the code protected I'll be grateful
the code:
$q=mysql_query("SELECT * FROM user where email= '".$_REQUEST['email']."'",$link );
$q=mysql_query("UPDATE user SET mobilePhone='".$_REQUEST['mobilePhone']."', fullName='".$_REQUEST['fullName']."' WHERE email='".$_REQUEST['email']."'",$link );
$q=mysql_query("UPDATE user SET mobilePhone='".$_REQUEST['mobilePhone']."' , fullName='".$_REQUEST['fullName']."', password='".$_REQUEST['password']."' WHERE email='".$_REQUEST['email']."'",$link );
Well, the simple way would be to wrap each of the $_REQUEST vars in mysql_real_escape_string()...
$q=mysql_query("SELECT * FROM user
where email= '".mysql_real_escape_string($_REQUEST['email'])."'",$link );
The better way would be to use prepared queries. There are plenty of tutorials available on how to do it, so I'll leave that to you...
The least you can do to prevent SQL injection is to use mysql_real_escape_string function before any variables that go into your queries.
The best you can do is to use prepared statements to avoid SQL injection.
The parameters to prepared statements
don't need to be quoted; the driver
automatically handles this. If an
application exclusively uses prepared
statements, the developer can be sure
that no SQL injection will occur
(however, if other portions of the
query are being built up with
unescaped input, SQL injection is
still possible).
Suggestion:
To be further on safer side, you should always use proper array eg $_POST or $_GET instead of $_REQUEST for security reasons.
Take a look at PHP's mysql_real_escape_string
Related
I am using FluentPDO to handle my database queries.
Upon looking at it's code, it doesn't seem to use any form of escaping. I understand PDO solves a lot of security issues by itself, but it's not immune to them.
As I understand, it is immune to SQL injection as long as we use the prepared statements syntax featured at it's homepage:
$query = $fpdo->from('article')
->where('published_at > ?', $date) // HERE!!
->orderBy('published_at DESC')
->limit(5);
How about escaping variables to prevent second order SQL injection? Would simply using addslashes() suffice? Would it be redundant?
How should I handle security with this library?
Thanks!
FluentPDO passes all parameters through the "execute" method of PDO, for example:
$connection = new PDO(...);
$pdo = connection->prepare($sql);
$pdo->execute($params);
That's why FluentPDO already prepares Queries to avoid SQL Injection.
About sanitizing, read more.
Some nice quotes:
Do not try to prevent SQL injection by sanitizing input data.
Instead, do not allow data to be used in creating your SQL code. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection.
or (read more about validating filters)
PHP has the new nice filter_input functions now, that for instance liberate you from finding 'the ultimate e-mail regex' now that there is a built-in FILTER_VALIDATE_EMAIL type
Is this considered completely safe?
$stmt = $dbhandler->prepare("update sometable set somefield=:somestring");
$stmt->bindParam(":somestring",$_REQUEST["hack_me_please"],PDO::PARAM_STR);
$stmt->execute();
And if not, what could make it safer? I'm assuming there are unknown vulnerabilities in PDO/MySQL/PHP that may be exploited in the future so I'm wondering if there is anything reasonable I can do make my queries safer, or is it out of my hands with prepared statements.
If it is this easy, why is SQL injection still a thing? Shouldn't it have gone the way of polio?
No, it's not necessary to sanitize inputs when using prepared statement to protect sql injections but you may do it if you want for any other reason.
If it is this easy, why is SQL injection still a thing? Shouldn't it have gone the way of polio?
it's easy for those who knows about it, nothing is easy unless you know it. I believe sql injection doesn't happen a lot nowadays.
Your example is completely safe because it passes the user input parameters separate from the query string. The reason sql injection still exists is because a lot of users still use the deprecated mysql_* api/driver and are unaware of the alternatives. Also, even using pdo or mysqli you can still pass user input directly into the query string instead of binding it separately.
I plan to prevent SQL injections by using the the $variable and route it to a function that will scan the $variable for any sql commands or any attempts of injections. I will also make a list of common sql commands that people would use inject so it would be detected.
Note: I previously asked a similar question but this time I have a theory I managed to think ;)
The simplest and secure way to prevent SQL injection is to use mysql_real_escape_string() on any untrusted data (eg: $_GET or $_POST). It will escape any special characters so the query will be safe.
If you use mysqli, see http://www.php.net/manual/en/mysqli.real-escape-string.php
More about SQL injection and how can you protect yourself against it: http://www.php.net/manual/en/security.database.sql-injection.php
So, your plan it's not the best way to do it. It unnecessarly complicates things.
No. Blacklisting will inevitably give false positives and almost certainly give false negatives.
Use bound parameters and let the database deal with it for you.
How would I go about storing potential SQL injection attacks in a database?
Assume first that I have detected a potential attack, and have the offending attack string in a variable and would like to add it to a table containing a log of suspicious events.
What would I need to do to safely insert these strings into a database so that no errors would be produced?
I have a feeling that it will be something along the lines of htmlspecialchars and mysql_real_escape_string... but I wanted to throw it out there to see if anybody else had any ideas!
One thought was to store the attack as an encoded base64 value, but that seems a bit hackish...
FYI, I am writing the application in PHP :)
Any responses would be greatly appreciated!
Always use parameterized queries. If you are using parameters, you don't need to rely on escaping strings and your query will always do exactly what you intend.
e.g.:
$statement = $db->prepare('INSERT INTO table_name (field_name1, field_name2) VALUES (:value, :value2)');
$statement->execute(array(':value' => $value, ':value2' => $value2));
See documentation for PDO prepare here:
http://www.php.net/manual/en/pdo.prepare.php
Use mysqli prepared statements to store the queries, it's the safest method to avoid sql injection. If you're going to display them via a web interface and concerned about XSS/CSRF attacks, use htmlspecialchars() before displaying them.
The same way you are storing any other data.
There is nothing special in storing SQL injection attacks, whatever you call it.
Like Steve Mayne said ... please use php PDO connection with prepared statements. It's the safes right now . Don't user mysql_connect() and subfunctions anymore because it's old and you cannot fully benefit of new mysql / sql / etc .. funcitons .
All I would do is run it though a simple encryption.
Then when you want to show the suspected sql, you would just decrypt it.
This should insure the suspected sql statement does not get executed on your db.
Is mysql_real_escape_string sufficient for cleaning user input in most situations?
::EDIT::
I'm thinking mostly in terms of preventing SQL injection but I ultimately want to know if I can trust user data after I apply mysql_real_escape_string or if I should take extra measures to clean the data before I pass it around the application and databases.
I see where cleaning for HTML chars is important but I wouldn't consider it necessary for trusting user input.
T
mysql_real_escape_string is not sufficient in all situations but it is definitely very good friend. The better solution is using Prepared Statements
//example from http://php.net/manual/en/pdo.prepared-statements.php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
Also, not to forget HTMLPurifier that can be used to discard any invalid/suspicious characters.
...........
Edit:
Based on the comments below, I need to post this link (I should have done before sorry for creating confusion)
mysql_real_escape_string() versus Prepared Statements
Quoting:
mysql_real_escape_string() prone to
the same kind of issues affecting
addslashes().
Chris Shiflett (Security Expert)
The answer to your question is No. mysql_real_escape_string() is not suitable for all user input and mysql_real_escape_string() does not stop all sql injection. addslashes() is another popular function to use in php, and it has the same problem.
vulnerable code:
mysql_query("select * from user where id=".mysql_real_escape_string($_GET[id]));
poc exploit:
http://localhost/sql_test.php?id=1 or sleep(500)
The patch is to use quote marks around id:
mysql_query("select * from user where id='".mysql_real_escape_string($_GET[id])."'");
Really the best approach is to use parametrized queries which a number of people ahve pointed out. Pdo works well, adodb is another popular library for php.
If you do use mysql_real_escape_string is should only be used for sql injection, and nothing else. Vulnerabilities are highly dependent on how the data is being used. One should apply security measures on a function by function basis. And yes, XSS is a VERY SERIOUS PROBLEM. Not filtering for html is a serious mistake that a hacker will use to pw3n you. Please read the xss faq.
To the database, yes. You'll want to consider adequately escaping / encoding data for output as well.
You should also consider validating the input against what you expect it to be.
Have you considered using prepared statements? PHP offers numerous ways to interact with your database. Most of which are better than the mysql_* functions.
PDO, MDB2 and the MySQL Improved should get you started.
What situations?
For SQL queries, it's great. (Prepared statements are better - I vote PDO for this - but the function escapes just fine.) For HTML and the like, it is not the tool for the job - try a generic htmlspecialchars or a more precise tool like HTML Purifier.
To address the edit: The only other layer you could add is data valdation, e.g. confirm that if you are putting an integer into the database, and you are expecting a positive integer, you return an error to the user on attempting to put in a negative integer. As far as data integrity is concerned, mysql_real_escape_string is the best you have for escaping (though, again, prepared statements are a cleaner system that avoids escaping entirely).
mysql_real_escape_string() is useful for preventing SQL injection attacks only. It won't help you with preventing cross site scripting attacks. For that, you should use htmlspecialchars() just before outputting data that was originally collected from user input.
There are two ways, one is to use prepared statements (as mentioned in other answers), but that will slow down your app, because you now have to send two requests to the Database, instead of one. If you can live with the reduced performance, then go for it; Prepared Statements makes your code prettier and easier to deal with.
If you chose to use mysql_real_escape_string, then make sure that you escape all the strings that are untrusted. An (mysql_real_escape_string) escaped string is SQL Injection secure. If you don't escape all the strings, then you are not secure. You should really combine mysql_real_escape_string with input validation; checking that a variable you expect to hold a number really is a number and within the expected range. Remember, never trust the user.
There are different types of "cleaning".
mysql_real_escape_string is sufficient for database data, but will still be evaluated by the browser upon display if it is HTML.
To remove HTML from user input, you can use strip_tags.
I would suggest you look into using PDO instead of regular MySQL stuff, as it supports prepared statements right out of the box, and those handle the escaping of invalid data for you.
You can try both, as in
function clean_input($instr) {
// Note that PHP performs addslashes() on GET/POST data.
// Avoid double escaping by checking the setting before doing this.
if(get_magic_quotes_gpc()) {
$str = stripslashes($instr);
}
return mysql_real_escape_string(strip_tags(trim($instr)));
}
The best way to go would be to use Prepared Statements
I thought I'd add that PHP 5.2+ has input filter functions that can sanitize user input in a variety of ways.
Here's the manual entry as well as a blog post [by Matt Butcher] about why they're great.