Does execute($input_parameter) protect from sql injections just like bindParam/bindValue?
If the answer is yes, bindParam()/bindValue()/execute() are invulnerable to any sql-inject attack? Or I need to take measures to prevent such attacks?.
Thanks for help!.
As far as execute($input_parameters) being as safe as separate bindParam/bindValue/execute steps, the answer would appear to be basically, yes.
However, you might still need to take further measures depending on how you constructed the query string that you pass to your PDO::prepare call. It is not always possible to parameter-ize everything in the prepared query string. For example, you can't use a parameter for a table or column name. If you allow user data or any external data into that query string you must still sanitize that data before passing the string to prepare.
Refer to these stackoverflow questions for more details:
how safe are PDO prepared statements
Are PDO prepared statements sufficient to prevent SQL injection?
In general you should be filtering all input data anyway, so if you wanted to be extra safe you could sanitize any input data that is destined for SQL-type stuff using the filters appropriate for your needs, or even writing a FILTER_CALLBACK custom function if you wish.
In the case of table or column names coming from user-provided data, a common validation technique is to check the values against arrays of allowable names.
Hope this helps. Good luck. Stay safe! ;)
Yes, it does the same thing. I cannot say that it is invulnerable, because the underlying SQL engine could itself be vulnerable. But that really isn't in your hands anymore.
So for all practical reasons, yes, its safe.
EDIT: Look at the PHP Documentation (1st and second example). One is with bindParam() and the other uses execute().
Related
Does execute($input_parameter) protect from sql injections just like bindParam/bindValue?
If the answer is yes, bindParam()/bindValue()/execute() are invulnerable to any sql-inject attack? Or I need to take measures to prevent such attacks?.
Thanks for help!.
As far as execute($input_parameters) being as safe as separate bindParam/bindValue/execute steps, the answer would appear to be basically, yes.
However, you might still need to take further measures depending on how you constructed the query string that you pass to your PDO::prepare call. It is not always possible to parameter-ize everything in the prepared query string. For example, you can't use a parameter for a table or column name. If you allow user data or any external data into that query string you must still sanitize that data before passing the string to prepare.
Refer to these stackoverflow questions for more details:
how safe are PDO prepared statements
Are PDO prepared statements sufficient to prevent SQL injection?
In general you should be filtering all input data anyway, so if you wanted to be extra safe you could sanitize any input data that is destined for SQL-type stuff using the filters appropriate for your needs, or even writing a FILTER_CALLBACK custom function if you wish.
In the case of table or column names coming from user-provided data, a common validation technique is to check the values against arrays of allowable names.
Hope this helps. Good luck. Stay safe! ;)
Yes, it does the same thing. I cannot say that it is invulnerable, because the underlying SQL engine could itself be vulnerable. But that really isn't in your hands anymore.
So for all practical reasons, yes, its safe.
EDIT: Look at the PHP Documentation (1st and second example). One is with bindParam() and the other uses execute().
I am a tyro in web security and have been researching on it for two days. According to OWSAP, SQL Injection and XSS attacks are the most common over the internet and at the minimal must be handled by every programmer.
So whatever I understood to protect them is the following (you are requested to correct it or add if I am wrong):
Use PDO and prepared statements to prevent SQL Injection
PDO and prepared statements are sufficient to prevent (first-order) SQL Injection and we do not need to do any escaping on input data as the driver handles that.
BUT this may lead you prone to second order SQL injection (see this for more) where a data like ' OR '1'=' may get stored into the database after passing through the PDO and prepared statements as they store raw data and to prevent this makes me feel to rather escape the string first and hence
use $pdo->quote($string) before passing it to prepared statement for storage
But since I also want protection against XSS attack I should use htmlentities() as well (or htmlspecialchars() for minimal case) .I should do this at the output but I may prefer to use at the input side if my output is targeted for HTML only
To summarize,my steps would be
$string ='raw input from user';
$escaped_string=$pdo->quote(htmlentities($string));
$pdo->execute('query to store $escaped_string into the database');
while ouputting
simply echo the stored field from the database.
I want to know whether my approach is secure or not?
If your code is open to second-order attacks, you're not using prepared queries correctly, and do not fundamentally understand what you are doing.
The point of escaping data in a query is to disambiguate the data from the command. The point of using parameters in queries is to fundamentally separate the data from the command. Both of these have absolutely nothing to do with how data is stored in the database.
Every query you do should use parameters for arbitrary data being used within them. If you do not do this, you might as well have no protection at all and will undoubtedly have errors in your application. Always use parameterized queries (and actually use those parameters) for arbitrary data, even if it came from your own database. Who cares where it came from... if you cannot predict what the data is, you know it isn't usable directly in a query.
On XSS attacks... you can prevent some of these by properly escaping data for use in an HTML context if you are outputting HTML pages. This allows you to use arbitrary strings in the context of HTML where the text is preserved. This escapes the data for HTML, meaning that the text won't be parsed as HTML tags. You should only do this escaping on output... not before, or you mangle your data early and make it unusable for other purposes.
BUT this may lead you prone to second order SQL injection
This may, actually, not. There is no such thing like "second order SQL injection". There is just SQL injection only. To prevent it you have to use parameterized queries. As simple as that.
To summarize, your steps would be
$string ='whatever string';
$pdo->prepare('any query that uses ? placeholder for any data');
$pdo->execute([$string]);
while ouputting make your template to do html escaping for any value by default, or apply any other format if told explicitly - i.e. make it raw for the html formatted texts.
This is standard procedure if you can not avoid getting raw input from user, if at all possible avoid using raw input from user. For example:
Best to use stored procedures for these types of things.
<?php
if(isset($_POST['submit'])) {
if($_GET['sort'] == 'alphad') {
$sort = 'alphad'; //not = $_GET['sort']
//Your query
}
}
?>
I'm wondering what's the best way to celar input data before inserting it into a mysql database.
There are a lot of function: trim, addslashes, mysql_real_escape_string and so on.
At this moment i'm using this simple function:
function filter($var){
$data = preg_replace('/[^a-zA-Z0-9]/','',$var);
$data = trim(addslashes($data));
return $data;
}
What's the best way to do it? Thanks
to be on the safe side, when dealing with mysql, mysql_real_escape_string() -- always use this. always.
Using mysql_real_escape_string() is enough for security reasons. Another way to do it is using prepared statements.
But you should check what information in what type you want in your database. There are several functions and language constructs you could use: Typecasts, filter_*() functions, int_val(), abs(), trim(), and a whole lot more.
I suggest you take a look at prepared statements that pretty much protect you against all form of 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).
The best thing is to do multiple things:
Validate data
Clean data
escape date
The validation is to check whether the data you've got makes any sense. For instance if you expect a birth date you check whether the format is correct and maybe even whether the date amkes sense. This not only has security benefits but also prevents some (not all) errors of wrong data. The tools there depend on the case, regular expression (preg_match) are often a good choice.
Cleaning data is often not really needed, but nice, for instance if a user types in some value use trim() to split of some whitespaces, which might be mistakes from copy and paste or such. This has no security benefit but improves the overall quality of your data. Which is good.
Both of these things should be done early in your script. While "early" depends on your achitecture. Sometimes it makes sense to clean first an validate then or doing it at once (preg_replace)
Then when sending data of to a database or putting it in HTML or any of these things oyu have to escape it accordingly to the system you are using. You should do that for all data, even when you verfied the format beforehand to be on the safe side. When talking to mysql these are the real_escape_string functions for instance, for HTML it is htmlentities() or htmlspecialchars(). with databases it is also a good idea too look into prepared statements, either PDO->prepare + execute() or mysqli->prepare() +execute()
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.