Sanitize $data & $item function - php

I'm trying to make sanitize function to keep rest of the code simple.
Since I'm using MYSQLi I wonder if the following code is correct?
function sanitize ($data){
global $db_connect;
return htmlentities(strip_tags($db_connect->real_escape_string($data)));
}
function array_sanitize ($item) {
global $db_connect;
$item = htmlentities(strip_tags($db_connect->real_escape_string($item)));
}

I see two reasons why you sanitize the string:
Prevent from SQL injections
You should use prepared statements instead of using real_escape_string() to prevent from SQL injections. The Mysqli Extension supports prepared statements. They are most secure and easy to use. Use them.
Prevent from XSS attacks
To prevent from XSS attacks htmlentities() and strip_tags() may help. You should also make sure, that the functions handling the input charset correctly.
You should also read this document from OWASP

Related

Prevent SQL injection and XSS attacks

Will this function below be able to prevent XSS attacks and sql injections ?
require_once('security.class.php');
function secure_data($data) {
$data = mysql_real_escape_string($data);
$filtered_data = filter_var($data, FILTER_SANITIZE_STRING);
$secure_class = new security_class();
$clean_data = $secure_class->xss_clean($filtered_data);
return $clean_data;
}
The security class is from codeigniter.
You shouldn't be trying to "brute force" security like this - layering all of these different filters/escapes one after another on every piece of data is silly and may actually make the escaping not work as intended.
This is because the kinds of characters that are added for one kind of escaping may be removed by another. You may also end up with over-escaping.
Instead, you should use the escaping function that is specifiy for what you are actually trying to do:
Before you put values into a SQL query, run them through mysqli_real_escape_string() (or better yet, use prepared statements via MySQLi/PDO).
Before you echo values out to a HTML response, run them through HTML escaping and/or XSS cleaning.
Etc.

How to properly check user input in php?

I have a function that checks user input and wanted to know if it prevents against all attacks of this sort. Also, if I wanted to include this function on each page that needed it could I put it in a php page of its own then 'include()' it into them pages where it's required. Thanks.
function secure_data($value)
{
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
if (function_exists("mysql_real_escape_string" )) {
$value = mysql_real_escape_string($value);
} else {
$value = addslashes($value);
}
return $value;
}
Since you're using quotes, I'm assuming that your main question is how to protect against SQL injections, if I'm not mistaken. (Note: securing against SQL-injection is something else then securing against for example Cross Site Scripting!); and will not guarantee you a secure application.
The best solution for SQL injection is not to use this function, but to use prepared statements with either mysqli or PDO.
(See: How can I prevent SQL injection in PHP? )
Other interesting links:
Background information on sql injection:
https://www.owasp.org/index.php/SQL_Injection
Other validation:
http://www.faqs.org/docs/gazette/superglobals.html
Input validation from OWASP:
https://www.owasp.org/index.php/Input_Validation

Is this safe enough for SQL injection

I just read about SQL injection and found this function on the blog i was reading
I am wondering if it is safe for SQL injection.. say if i pass do remove_mq($_POST) to it, could i be using $_POST["var"] inside a query without a problem?
function remove_mq($array){
foreach($array as $key => $value){
if(is_array($value)){
$array[$key] = remove_mq($value);
}
else{
$array[$key] = addslashes($value);
}
}
return $array;
}
No. Addslashes is not the proper function to escape for a query. You need to use mysql_real_escape_string
Besides that, you should not perform SQL escaping before actually using a value in a query. Assume you have something like <input name="foo" value="$_POST[foo]" - then you need it htmlspecialchars()-escaped and not addslashes(etc.)-escaped
Besides that, the best solution would be using PDO with prepared statements since you separate SQL queries from params so you do not need any escaping at all.
Best practice nowadays is prepared queries.
Example:
$stmt = $pdo->prepare('SELECT username FROM users WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$result = $stmt->fetchAll();
This code is totally secure
Well, all the answers above missing the point.
addslashes() is good enough as long as your data encoding is either utf-8 or any single-byte one.
but the whole approach, despite of the function used, is utterly wrong
Doing massive escaping over $_POST makes no sense and doesn't guarantee full protection.
No addslashes nor mysql_real_escape_string do any actual protection. It does as little as string delimiters escaping. So, you have to use this function:
only on strings
only on strings actually going into query.
all other required manipulations are described in the link in the comments
and some info for ones who feel extremely educated in the matter:
your beloved PDO, when used out of the box, do use the same defamed addslashes
Nope - just use the built in function for it! mysql_real_escape_string() is always going to be more reliable than any function you can write yourself.
Here's an article explaining why you should use mysql_real_escape_string over addslashes.
Of course, the best approach is to use prepared queries. Here's some information on them.

How to prevent XSS attack in my function?

I am creating a function for my $_POST inputs to prevent SQL Injection BEFORE adding the values into database. I use it on login/register and when a user needs to post an article. As far as I know, this does not secure it from XSS.
Should I create a different function when I output data or edit this?
Thank you.
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
Try using prepared statements. They are designed to automatically escape things. They should also keep your queries cleaner in the source code.
http://www.ultramegatech.com/blog/2009/07/using-mysql-prepared-statements-in-php/
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/book.pdo.php
You talk about XSS and then SQL injection...
SQL
Use mysql_real_escape_string() or better still bind params with a library such as PDO.
If magic_quotes is a possibility, use...
function sqlEscape($str) {
if (get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
Regarding your example, why do you need to use trim() to make data safe? Also, why use the error supressor on trim()?
XSS
Use htmlspecialchars($str, ENT_QUOTES) to prevent HTML special characters from having special meaning.
I use the following, which works just fine to prevent injections:
function clean($str) {
$value = mysql_escape_string(stripslashes(htmlspecialchars($str)));
return $value;
}
You shouldn't save values as encoded HTML to your database. Do that when outputting them, not when saving them (saving encoded HTML makes it harder to search in it, makes their size bigger, makes it harder to use them in formats other than HTML and generally just wrong - your database should store the actual text, not the text formatted to be displayed in a specific way).
Also, as Quamis said, you should probably look at PDO or some other DBAL that lets you use prepared statements instead of escaping it manually.

A PHP function to prevent SQL Injections and XSS

I am tring to make my PHP as secure as possible, and the two main things I am trying to avoid are
mySQL Injections
Cross-Side Scripting (XSS)
This is the script I got against mySQL Injections:
function make_safe($variable) {
$variable = mysql_real_escape_string(trim($variable));
return $variable; }
http://www.addedbytes.com/writing-secure-php/writing-secure-php-1/
Against XSS, I found this:
$username = strip_tags($_POST['username']);
Now I want to unite the two into a single function. Would this be the best way to do so? :
function make_safe($variable) {
$variable = strip_tags(mysql_real_escape_string(trim($variable)));
return $variable; }
Or does the mysql_real_escape_string already prevent XSS? And lastly, is there anything else that I could add into this function to prevent other forms of hacking?
mysql_real_escape_string() doesn't prevent XSS. It will only make impossible to do SQL injections.
To fight XSS, you need to use htmlspecialchars() or strip_tags(). 1st will convert special chars like < to < that will show up as <, but won't be executed. 2nd just strip all tags out.
I don't recommend to make special function to do it or even make one function to do it all, but your given example would work. I assume.
This function:
function make_safe($variable)
{
$variable = strip_tags(mysql_real_escape_string(trim($variable)));
return $variable;
}
Will not work
SQL injection and XSS are two different beasts. Because they each require different escaping you need to use each escape function strip_tags and mysql_real_escape_string separatly.
Joining them up will defeat the security of each.
Use the standard mysql_real_escape_string() when inputting data into the database.
Use strip_tags() when querying stuff out of the database before outputting them to the screen.
Why combining the two function is dangerous
From the horses mouth: http://php.net/manual/en/function.strip-tags.php
Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.
So by inputting malformed html into a database field a smart attacker can use your naive implementation to defeat mysql_real_escape_string() in your combo.
What you should really be looking into is using prepared statements and PDO to both provide an abstraction layer against your database as well as completely eradicate SQL injection attacks.
As for XSS, just make sure to never trust user input. Either run strip_tags or htmlentities when you store the data, or when you output it (not both as this will mess with your output), and you'll be all right.

Categories