Protecting my html forms from injection - php

I have a text box on my site that allows the use of html formatting to allow the users to make the text more presentable.
I use this code to protect most inputs to my db.
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
What i don't want it to do is remove html elements like <p> and <strong>
is there a better way to protect the inputs in text areas?

I only use mysql_real_escape_string() when inserting data to my DB and remove Tags like <script> (and some others) after pulling it from the DB. I think there are a few regexes out there.

The first line of defense against injections is using prepared statements. If you use prepared statements for your queries then it really doesn't matter what the user puts into your form because you have already separated code from data. The database will see any code that a user injects as just data rather than code. So not only do you get the benefit of protecting yourself from injection, but your code is actually cleaner and more thought out as well.

Related

Prevent XSS and SQL injection in chat [duplicate]

Is this code secure to prevent XSS attacks ??
<?php
$string = "<b>hello world!</b>";
echo "without filtering:".$string;
echo "<br>";
$filtered = htmlspecialchars($string); // insert into database filtered
echo "After filtering:".$filtered;
echo "<br>";
$de_filtering = htmlspecialchars_decode($filtered); //retrieve from database and display
echo "After de-filtering:".$de_filtering;
?>
You should not encode HTML-Specialchars when inserting into database, that way data is manipulated (and maybe different when editing the dataset). You should rather encode them when displaying it.
But yes, htmlspecialchars() is enough to prevent XSS as long as you don't forget to use it. The way YOU use it however is as secure as before. XSS is prevented through the encoded version, the database does not care about it.
No, XSS is independent of the database. To avoid SQL-injection, you want to escape using something like mysql_real_escape_string or use prepared statements, but to avoid XSS you need to escape when outputting to HTML.
And there are a couple of gotchas there as well. Take a look at the OWASP XSS prevention cheat sheet. It explains how to escape for different context.
htmlspecialchars/htmlentities will protect you if you are outputting untrusted data between tags, but will not protect you if you are outputting it in say a javascript event handler like this:
<button onclick="confirm('do you want to delete <?php echo htmlspecialhars($untrusted_data) ?>')">
This is because you are escaping for HTML and not javascript.
Nope - you're filtering the data before putting it into the database (which is unnecessary), but cancelling out the filter when outputting the data.
Store the data in the database unfiltered, and escape it when outputting:
echo htmlspecialchars($unfiltered_data_from_database);

PHP - String Clean

I'm starting a comment system for my website. The problem is I want to use an HTML editor, but is not fully necessary.
My problem is with the security. How to secure the user input that I save in database? Because I show that input on my website and I want to prevent XSS, SQL Injection and other things like that. But I still want my users to be able to write any characters.
For example, daniweb uses and HTML EDITOR (wysiwyg .
I also tried
function bstring( $value )
{
$value = htmlentities( $value, ENT_QUOTES );
$value = strip_tags( $value );
$value = mysql_real_escape_string( $value );
return (string)$value;
}
If you use mysqli
you can use this:
$mysqli->real_escape_string($value);
It
Escapes special characters in a string for use in an SQL statement
If you want to allow the user to input HTML tags but disallow him to use certain tags like Scripts, you should just implement some form of whitelisting for tags.
$allowed_tags = "<b><i><br>"; // Some safe examples
$value = strip_tags( $value, $allowed_tags );
Allways know when and why to use which filter:
mysql_real_escape_string - Protects your SQL against injection - Allways needed if no connector with proper parameter binding is used
strip_tags - Removes unwanted tags from unsafe output you show on your page. Can be used to counter XSS attacks - See above
htmlspecialchars - Encode html tags so that they will no longer work. Protects agains XSS but also removes HTML functionality - You dont want this as you actually want users to use HTML tags
htmlentities doesnt provides security
you need to strip the html using replace
following a list what tags you want to forbid and what tags you want to allow
function bstring($str){
//forbid your tags here
$forbidden_tags = array('script', 'body', 'html');
for($i = 0; $i < count($forbidden_tags); $i++){
$tag = '%<'.$forbidden_tags[$i].'.*?</'.$forbidden_tags[$i].'>%i';
$result = preg_replace($tag, 'NOT ALLOWED', $str);
}
return $result;
}
You can use Doctrine: http://en.wikipedia.org/wiki/Doctrine_%28PHP%29
One of Doctrine's key features is the option to write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL). Actual SQL queries are generated by Doctrine only (that would protect from SQL Injection and other things like that).
official site: http://www.doctrine-project.org/
read this about security: http://www.doctrine-project.org/2014/02/21/security_in_doctrine.html

Disallow characters in text field

Should I disallow characters like ",',>,<,\ ... to be typed in an upload forms text field? The text will be send through PHP to a blog.
I heared that some characters might cause trouble and could be used to "hack / harm" servers. Which characters should be restricted?
Thanks for your input.
Michael
There is no need to restrict anything. The problem is that you have to sanitize all user input; for this specific type of data (possible HTML) it is necessary and enough to use htmlspecialchars on all user-provided data before displaying it as part of your page.
For example, if your form has a textarea named post-body, you should receive the user input (e.g. with $_REQUEST['post-body']) and save it to your database as-is (warning: use mysql_real_escape_string or PDO to protect yourself from SQL injection at this stage!). When the time comes to display it, you would retrieve it from the database and print it with something like
echo htmlspecialchars($postBody);
See this question for some more background on data sanitization.
Users data should be sanitized by htmlspecialchars function each time when you output users data, to avoid XSS-attacks.
Also, to work with users data in sql-queries, use PDO and prepared statements or mysql_real_escape_string function to avoid SQL-injection. Example.
<? $string = str_replace("\\\"", "\"", $string);
$string = htmlspecialchars($string);
$string = preg_replace( "/\r\n|\n|\r/", "<br>", $string ); ?>
<input type = "text" name = "string" id = "string" value = "<?=$string?>">

Best ways to sanitize user submitted content? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: the ultimate clean/secure function
I am working on an experimental social networking site in PHP. So, there will be a lot of user submitted data sent to the database.
I had coded a custom block script a while back, that would just block certain characters or keywords from being submitted. This worked, but it had it's list of problems.
I heard addslashes and mysql_real_escape_string will do this, but I don't want to do anything until I get some solid advice.
I tried addslashes, and it will add slashes to can't, don't, etc. I don't want that.
I just want my database to be safe from xss, html, php, and javascript attacks. Any advice?
prepared statements from PDO
filter_var() functions
htmlspecialchars()
For people who don't know PHP or find documentation about functions:
prepared statements - will provide protection against SQL injections ( but not against extreme stupidity )
filter_var() - will let you make sure that data really us an URL or email address , etc.
htmlspecialchars() - converts characters like < , > and & into html entities, thus, protecting against XSS.
I really fail to see the need for explanation here.
You should HTML escape any content before outputting it back to the user. Then when it's ever outputted back it'll be safe. Use htmlspecialchars for PHP. See What are the best practices for avoiding xss attacks in a PHP site for more information and read OWASP XSS (Cross Site Scripting) Prevention Cheat Sheet.
All good answers so far, I would just like to add that you should make sure that the input data comes in the desired encoding - you should also normalize the different types of new line feeds or strip control characters altogether, I end up using the following function a lot:
function Filter($string, $control = true)
{
$string = iconv('UTF-8', 'UTF-8//IGNORE', $string);
if ($control === true)
{
return preg_replace('~\p{C}+~u', '', $string);
}
return preg_replace(array('~\r[\n]?~', '~[^\P{C}\t\n]+~u'), array("\n", ''), $string);
}
It will remove all invalid UTF-8 data from the string and normalize new lines. All control chars (except tab (\t) and new lines (\n)) are striped, and if $control == true these are stripped too.
PS: This is not very useful from a security standpoint of view but is helps avoiding GIGO.
For HTML type input use HTMLPurifier or similar to filter out unwanted markup.
Validate form fields before storing the data
Use prepared statements with PDO or MySQLi when writing to the database. This will take care of the SQL escaping for you, provided you bind your parameters correctly.
Escape the output coming out of the DB before displaying it unless it can be considered safe.

secure form data for mysql

I have been using:
if ($_POST['Comments']!=""){
$comments = mysql_real_escape_string($_POST['Comments']);
}else{
$comments = "";
}
ever since a user added and apostraphy to their data and it broke my sql statement. I thought this also secured the data at the same time. But just now I got a submission and in the comment field in the database I see:
/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r/r
seohelp
And the email I get when someone submits had the text with the links actually working.
I thought mysql_real_escape_string() was supposed to get rid of all that?
Any suggestions? I was thinking of doing a function that does all the string cleaning for me in a few different steps. But if there is a way to secure in just one step that would be great.
mysql_real_escape_string() only protects* you against SQL Injection, not against Cross-Site Scripting (XSS).
* mysql_real_escape_string() doesn't behave properly when used in conjunction with SET NAMES because it is unaware of the charset being used. Use mysql_set_charset() instead.
In order to protect yourself against XSS, you must also use htmlentities() or htmlspecialchars() either at insert time (before mysql_real_escape_string()) or at display time.
$escaped = htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
If you want to allow some HTML content, use HTML Purifier with a whitelist of elements and attributes you want to allow.

Categories