简体   繁体   中英

Avoiding XSS when echoing POSTed HTML

I have a web page which needs to do the following:

  • dynamically create an HTML fragment using JavaScript
  • open a new window
  • display the HTML in the new window

My first approach used document.write to copy the HTML into the window. This works in most cases, but it causes problems with Internet Explorer when the original window has set document.domain . Plus document.write tends to be discouraged these days.

So my second approach was to put the HTML into a hidden form , set the form's target to the new window, and POST the form. This means I need a script on the server to respond to the form, by echoing the POSTed content.

But this is dangerous, since someone could make a request that includes <script> tags in the content. How can I avoid the potential XSS risk ? I guess I could filter out things like <script> , although that seems clumsy. If I were creating the HTML on the server, I could encrypt it, or add some token that can only be verified on the server. But I'm creating it on the client.

EDIT: Thanks for the filtering suggestions so far. I may choose to go this route, but I'm wondering: what if I don't want any restrictions on the HTML I create? Is there any way I can validate that the document was created by my page?

Try HTML Purifier .

Edit:

"Is there any way I can validate that the document was created by my page?"
Not unless you create another copy of the html server-side and compare. Anything in your script can be viewed by the user, although you can make it difficult for non-technical users. Anything that client-side Javascript can do, a malicious user can do on a Javascript console.

Even if you somehow verified that the request came from your script, a malicious user can modify your script using a Javascript console by inserting lines of code that produce a dangerous request. All GET and POST data must be treated as malicious.

Try PHPIDS .

PHPIDS (PHP-Intrusion Detection System) is a simple to use, well structured, fast and state-of-the-art security layer for your PHP based web application. The IDS neither strips, sanitizes nor filters any malicious input, it simply recognizes when an attacker tries to break your site and reacts in exactly the way you want it to. Based on a set of approved and heavily tested filter rules any attack is given a numerical impact rating which makes it easy to decide what kind of action should follow the hacking attempt. This could range from simple logging to sending out an emergency mail to the development team, displaying a warning message for the attacker or even ending the user's session.

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