简体   繁体   中英

How to prevent XSS in search forms?

I'm trying to prevent XSS in my search forms. I've added this to escape HTML characters but this doesn't work. Any ideas?

 $input = htmlspecialchars($input, ENT_QUOTES); 

This is the search form I have

<form action="search.php" method="get">
    <input type="text" name="q" value="search" />
    <input type="submit" value="send" />
</form>

You need to use the function htmlspecialchars() whenever you want to output something to the browser that came from the user input.The most important thing is sanitize the input given by the user.

You can use filter_var() too.

The Source

XSS usually refers to when someone is able to insert HTML into your page, which can happen when you output user input without encoding it first. To prevent that, use htmlspecialchars() when you output user input. I sometimes define two functions like this:

function he($s) {
    return htmlspecialchars($s, ENT_QUOTES, "UTF-8");
}
function eh($s) {
    echo he($s);
}

Then, when you want to echo user input, do this:

eh($user_input);

instead of this:

echo $user_input;

According to OWASP :

... HTML entity encoding doesn't work if you're putting untrusted data inside a tag anywhere, or an event handler attribute like onmouseover, or inside CSS, or in a URL. So even if you use an HTML entity encoding method everywhere, you are still most likely vulnerable to XSS. You MUST use the escape syntax for the part of the HTML document you're putting untrusted data into.

According to this answer :

What you should do, to avoid problems is quite simple: Whenever you embed a string within foreign code, you must escape it, according to the rules of that language.

Read the seven rules by OWASP:

  • RULE #0 - Never Insert Untrusted Data Except in Allowed Locations
  • RULE #1 - HTML Escape Before Inserting Untrusted Data into HTML Element Content
  • RULE #2 - Attribute Escape Before Inserting Untrusted Data into HTML Common Attributes
  • RULE #3 - JavaScript Escape Before Inserting Untrusted Data into JavaScript Data Values
  • RULE #4 - CSS Escape And Strictly Validate Before Inserting Untrusted Data into HTML Style Property Values
  • RULE #5 - URL Escape Before Inserting Untrusted Data into HTML URL Parameter Values
  • RULE #6 - Sanitize HTML Markup with a Library Designed for the Job
  • RULE #7 - Prevent DOM-based XSS

XSS prevention is not an easy subject. The ressources on the Open Web Application Security Project ( OWASP ) website are a good starting point.

echo htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); is a safe and effective way to stop all XSS attacks on a UTF-8 encoded web page, but doesn't allow any HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM