Will this code actually work against SQL-injection? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: the ultimate clean/secure function
I found this code snippet here: http://snipplr.com/view/12853/clean-variables-from-sql-injections/
The author claims:
This little function helps to fight common security issue with SQL injections, it can sanitize any global variable like $POST, $GET, $_SERVER etc and escape unsafe characters.
Is this code safe?
function _clean($str){
return is_array($str) ? array_map('_clean', $str) : str_replace("\\", "\\\\"
, htmlspecialchars((get_magic_quotes_gpc() ? stripslashes($str) : $str)
, ENT_QUOTES));
}
//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);// and so on..
Please enlighten me whether this is safe, 'cause it looks jury-rigged to me.

Generic code cleaning functions are always a bad idea. They will break your data in one way or the other. Never use them; sanitize data right before it gets used, with the right sanitation method for the intended use.
Duplicate: PHP: the ultimate clean/secure function

Just use mysql_real_escape_string if you need to escape special characters for a mysql database. I'd figure other databases support similar functions too.
This snipped tries some silly replaces and may be pretty safe, but could just as well mess up your data too. Why reinvent the wheel?

Why wouldn't you just use the built-in escaping/parameterizing functionality for your database? I agree with it looking jury-rigged, go with the function built by the people who made the database library.

It's not safe (no addslashes or mysql_real_escape_string there), not optimal in performance too (get_magic_quotes_gpc being called for each variable).

Related

Is is bad practice to use array_walk with mysqli_real_escape_string?

So I have a function called "escape" that looks like this:
function escape($string){
$escaped_string = mysqli_real_escape_string($this->conn, $string);
return $escaped_string;
}
I before running a query I send a variable (originated from user input obviously) here so its escaped for security reasons.
Now I know its possible to use array_walk to apply an array of values to this function, but I just want to know if there is any reason why I shouldn't? I know it sounds like a daft question but it would be nice and easy to apply it to an array of user inputted values rather than each variable.
Normally if when making a function I will do it this way:
function whatever($user_input){
$user_input = $this->escape($user_input);
$this->query("SELECT dog from pets where owner = '$user_input'");
e.c.t.
}
But if I have a lot of user inputted data from a form for example id rather just pass an array into the function and use array_walk on the escape function to save myself the hassle. But again is there any particular reason (from a security point of view) why this is not a good idea?
YES, absolutely
The practice is the reincarnation of the infamous "magic quotes" feature, that once was a part of the language, but now thank goodness it is not.
Such an approach will do you no good but only a give a false feeling of security and spoil your data for no reason.
You must use prepared statements for all database interactions that involve PHP variables. This is the only 100% safe solution, and it makes the function in question obsolete.
Here I've got an example for the select query using prepared statements, https://phpdelusions.net/mysqli_examples/prepared_select
With a simple helper function it turns into much simpler and cleaner solution than that escaping-driven mess

Is this sufficient security for user input in PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
The ultimate clean/secure function
After reading up on PHP security I have the feeling that anything I code is always insecure. So to combat the security issues of user input I have created a function that allows me to escape and strip user input for any usage situation.
I would just like to know if this is in fact secure and if I could make it more secure. Also what kind of attacks would this prevent? From what I can tell XSS by using _GET, HTML input and MYSQL injection would have been prevented?
function _INPUT($name,$tag,$sql,$url)
{
if ($_SERVER['REQUEST_METHOD'] == 'GET')
$filter = ($_GET[$name]);//Assign GET to filter variable
if ($tag == true)//Remove all HTML, PHP and JAVASCRIPT tags
{
$filter = strip_tags($filter);
}
if ($sql == true)//If MYSQL escaping is enabled
{
$filter = mysql_real_escape_string($filter);
}
if ($url == true)//If URL encoding is enabled
{
$filter = urlencode($filter);
}
return $filter;
}
$output = _INPUT('name',true,true,true);
I will be using prepared statements for MYSQL too, although I need to read up on them more to fully understand how it prevents injection.
Thank you for your time.
Once again, there is no universal escape function that just magically makes things "secure".
See this: https://stackoverflow.com/a/7810880/362536
Different escape methods are used for different things. You can't just run a bunch of data through a bunch of functions that are supposed to be used in specific contexts. You are creating garbage data, and are no more secure than you were with the raw user data in the first place.
No,
For SQL Injection prevention, you really want to be using prepared statements. This is a safer way to do this, instead of escaping quotes. You also want to use htmlspecialchars() for escaping HTML tags, instead of just stripping them away, but that's up to you.
This is kind of an eternal question, and the answers vary across wanted usage: for prepared queries, I believe it’s 100 % safe to use its own variables system and let it handle the input. For HTML output, stripping tags may not always be what you want; moreover, it’s kind of safer to do a whitelist of what to allow in input than blacklist, because you know, hackers have fantasy. For URL output, your solution should be fine, but be aware that some other platforms may do a little different URL-encoding (see the difference between a string URL-encoded by Java standard libraries and iOS/Mac libraries, i.e.).

SQL Injection, Quotes and PHP

I'm quite confused now and would like to know, if you could clear things up for me.
After the lateste Anon/Lulsec attacks, i was questioning my php/mysql security.
So, i thought, how could I protect both, PHP and Mysql.
Question: Could anyone explain me, what's best practice to handle PHP and Mysql when it comes to quotes?
Especially in forms, I would need some kind of htmlspecialchars in order to protect the html, correct?
Can PHP be exploitet at all with a form? Is there any kind of protection needed?
Should I use real_escape_string just before a query? Would it be wrong/bad to use it already within PHP (see sanitize_post function)?
Currently i'm using the following function. The function "sanitizes" all $_POST and $_GET variables. Is this "safe"?
function sanitize_post($array) {
global $db;
if(is_array($array)) {
foreach($array as $key=>$value) {
if(is_array($array[$key])) {
$array[$key] = sanitize_post($array[$key]);
} elseif(is_string($array[$key])) {
$array[$key] = $db->real_escape_string(strtr(stripslashes(trim($array[$key])), array("'" => '', '"' => '')));
}
}
} elseif(is_string($array)) {
$array = $db->real_escape_string(strtr(stripslashes(trim($array)), array("'" => '', '"' => '')));
}
return $array;
}
I'm using PHP 5.3.5 with Mysql 5.1.54.
Thanks.
mysql_real_escape_string deserves your attention.
However direct queries are a quagmire and no longer considered safe practice. You should read up on PDO prepared statements and binding parameters which has a side benefit of quoting, escaping, etc. built-in.
BEST practice is always to use prepared statements. This makes SQL injection impossible. This is done with either PDO or mysqli. Forget about all the mysql_* functions. They are old and obsolete.
Question: Could anyone explain me, what's best practice to handle PHP
and Mysql when it comes to quotes?
That's easy: Use prepared statements, e. g. with PDO::prepare or mysqli_prepare.
There is nothing like "universal sanitization". Let's call it just quoting, because that's what its all about.
When quoting, you always quote text for some particular output, like:
string value for mysql query
like expression for mysql query
html code
json
mysql regular expression
php regular expression
For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (always assure it is switched off!!!).
So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)
mysql_real_escape_string(addcslashes($str, "%_"))
htmlspecialchars($str)
json_encode() - only for utf8! I use my function for iso-8859-2
mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times!
preg_quote()
Don't waste the effort using mysql_real_escape_string() or anything like that. Just use prepared statements with PDO and SQL injection is impossible.
I usually use the PHP functions stripslashes and strip_tags on the variables as they come in via $_POST (or $_GET, depending on what you use) and mysql_real_escape_string during the query. (I'm not sure if this is "right" but it's worked for me so far.) You can also use PHP's built in validate filters to check things like email addresses, url's, data types, etc. PDO is supposedly decent at preventing SQL injection but I haven't had any experience with it yet.
The basic workflow should be
$data = $_POST['somefield which will go into the database'];
... do data validation ...
if (everything ok) {
$escaped_data = escape_function($data);
$sql = " ... query here with $escaped_data ... ";
do_query($sql);
}
Basically, data that's been escaped for database insertion should ONLY be used for database insertion. There's no point in pre-processing everything and overwriting all data with db-escaped values, when only 2 or 3 of 50(say) values actually go anywhere near the db.
Ditto for htmlspecialchars. Don't send data through htmlspecialchars unless it's headed for an HTML-type display.
Don't store data in the DB formatted for one particular purpose, because if you ever need the data in a different form for some other purpose, you have to undo the escaping. Always store raw/unformatted data in the db. And note: the escaping done with mysql_real_escape_string() and company does not actually get stored in the db. It's there only to make sure the data gets into the database SAFELY. What's actually stored in the db is the raw unescaped/unquoted data. Once it's in the database, it's "safe".
e.g. consider the escaping functions as handcuffs on a prisoner being transferred. While the prisoner is inside either jail, cuffs are not needed.

mysql_real_escape_string alternative for SQL Server [duplicate]

This question already has answers here:
How to escape strings in SQL Server using PHP?
(14 answers)
Closed 7 years ago.
Am wondering what is the equivalent in PHP for SQL Server escaping of strings?
Nice question, I don't know but you could use PDO::quote() with the PDO_DBLIB driver.
EDIT: Seems like this guy got it from StackOverflow:
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
Another option:
function mssql_escape($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
The best alternative is to use parameterised queries, then you don't have to escape strings.
If you still want to put the query together yourself, the proper way to escape a string literal for SQL Server (T-SQL) is to replace each apostrophe (') in the string with two apostrophes.
The short answer is: use whatever mechanism your connection libraries provide, it really has nothing to do with the database. If you're using ADO, you have parameterized queries, if you're using something else (I know nothing about PHP) then use whatever that library offers.
Rolling your own is probably a bad idea, because you're very likely to get something wrong, e.g. handling comment delimiters correctly.

Best way to sanitise POST/GET variables from a form/URL? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Best way to stop SQL Injection in PHP
I am creating a website using PHP that makes use of a MySQL database and handles forms and variables from the URL. The variables are being using to dynamically construct SQL query strings. So i need a robust solution to make sure nobody is trying a SQL injection, etc.. A friend of mine has said that really i should only use stored procedures to access the database but that's not really feasible because the host i'm using doesn't allow these.
Here is the code i'm using (it's part of a class to wrap DB commands):
...
public function Sanitize($Variable)
{
if(is_resource($this->ServerConnection))
{
$Variable = str_replace(";", "", $Variable);
if(get_magic_quotes_gpc())
{
if(ini_get('magic_quotes_sybase'))
{
$Variable = str_replace("''", "'", $Variable);
}
else
{
$Variable = stripslashes($Variable);
}
}
return mysql_real_escape_string($Variable, $this->ServerConnection);
}
else
{
$this->PrintError("The Sanitize function is not available as there is no server connection.");
}
}
...
Is this function robust enough? Should i be doing anything else?
Might be worth reading this post.
What is the best way of ...
There is no best way. It depends on the context.
.. sanitising POST/GET variables from ..
It is a flawed mode of thinking that data are good or bad. Data is just data. It's the context in which it's used that makes it malicious or not. Some words may be bad if you execute them unadorned on a database server. Some words are bad if you display them to minors. It's about context.

Categories