PHP Htmlspecialchars does not protect against XSS injection from front-end innerHTML

Source: Internet
Author: User
Do not in JS directly with the innerHTML output without JS filter User Content,
Even if the content has been filtered by server-side PHP htmlspecialchars or htmlpurifier.
For example, the following code, the page will alert popup string/xss/, because JS will convert the Unicode characters in the variable \u003c and \u003e into <和> Output.

//
$XSS = ' \u003cimg src=1 onerror=alert (/xss/) \u003e ';
Xss
$XSS = ' \u003ca Href=javascript:alert (String.fromCharCode (88,83,83)) \u003exss\u003c/a\u003e ';
Header (' Content-type:text/html;charset=utf-8 ');
?>



$ (#xss). Append (XSS) and $ ("#xss"). HTML (XSS) output is HTML.

Workaround:
http://segmentfault.com/q/1010000004067521
You're right, after all, it's a lot of time to add AJAX-loaded data to the page with innerHTML.
It is worth noting that the innerhtml nature is also the output HTML,
So we can use JS like PHP htmlspecialchars before the output.
Replace the special character (&, ", ',<,>) with the HTML entity (&" ' <>).
or simply use InnerText (IE) and Textcontent (Firefox), which is jquery's text (), to output text content.
Firefox does not support IE's innertext, but supports textcontent.
Two implementations found on the StackOverflow:
function Htmlspecialchars (str) {
Return str
. replace (/&/g, "&")
. Replace (/. replace (/>/g, ">")
. replace (/"/g," "" ")
. replace (/'/g, "'");
}
function Htmlspecialchars (str) {
var map = {
' & ': ' & ',
' < ': ' < ',
' > ': ' > ',
'"': '"',
"'": '''
};
Return str.replace (/[&<> "']/g, function (k) {return map[k];});
}
Where g indicates the meaning of global substitution, which is to replace all matching contents in the string.

However, JS imitates PHP Htmlspecialchars is a one-size-fits-all approach, the data will lose HTML features.
ask, for the front end Ajax (Pjax) came over the HTML data how do we filter the XSS output ?
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.