3

I would love to know which best methods/tips do we have to use to prevent and make difficult a xss attack ?

I know there are :

What's about users who need to complete a database? What kind of mistakes usually can do a new developer?

Thank you

hakre
  • 193,403
  • 52
  • 435
  • 836
Zeroth
  • 83
  • 1
  • 8
  • possible duplicate of [What are the best practices for avoiding xss attacks in a PHP site](http://stackoverflow.com/questions/71328/what-are-the-best-practices-for-avoiding-xss-attacks-in-a-php-site) – JJJ Aug 24 '11 at 15:23

3 Answers3

1

Rule number one: never trust user input.

Your suggestions are great, I would add these two:

  • addslashes()
  • mysql_real_escape_string() (assuming you are using MySQL, there are functions for other vendors too)

I always suggest to filter user input before you do any work with it. Just in case you forget it later.

Tautvidas S
  • 196
  • 2
  • 6
  • Thank you. theses functions ar not specific to mysql ? – Zeroth Aug 24 '11 at 23:16
  • addslashes is not, but mysql_real_escape_string is (but as I mentioned other DB vendors have similar functions too, e.g. pg_escape_string, sqlite_escape_string and others) – Tautvidas S Aug 25 '11 at 08:54
1

Which method is most efficient depends on your requirements. If you need to allow some HTML from users, you probably want HTML purifier.

If however you will never accept HTML from users, you need to apply contextual encoding. You can have XSS, without the user injecting a new tag. The attack string can alter an existing tag. Typical example:

<input type="text" name="email" value="<?php echo $email; ?>">

In this example, if $email is

" autofocus onfocus="alert(1)

The javascript in the onfocus eventhandler will fire.

The escaping you need to use, depends on the context. Are we in javascript, or in HTML or in an HTML attribute or in CSS? See the https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet for more info on how to encode.

Erlend
  • 4,336
  • 22
  • 25
0

I would use the following:

$variable = trim(strip_tags(stripslashes($_POST['variablename'])));

OR

// Clean up the input values 
foreach($_POST as $key => $value) {  
    $_POST[$key] = stripslashes($_POST[$key]); 

    $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key])); 
}

Both works great in respective to HTML/PHP.

Si8
  • 9,141
  • 22
  • 109
  • 221