开发者

Todo list methods to prevent xss attack, which are the most efficient?

开发者 https://www.devze.com 2023-03-30 04:23 出处:网络
I开发者_JAVA技巧 would love to know which best methods/tips do we have to use to prevent and make difficult a xss attack ?

I开发者_JAVA技巧 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 :

  • use htmlspecialchars()
  • use sanitize filters
  • use strip_tags()
  • use filter_input_array()
  • disallow everything not needing
  • http://htmlpurifier.org/
  • read this http://www.addedbytes.com/writing-secure-php/

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

Thank you


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号