A friend of me posted a code about how to p开发者_如何转开发revent xss attack using DOM.
What do you think about this code ? Can we optimize it ?
<?php
function parseDoc(DOMDocument $codeHtml){
$forbiddenTag=array('script');
$forbiddenAttr=array('onmouseover','onmouseup','onclick');
foreach($forbiddenTag as $tag){
$liste=$codeHtml->getElementsByTagName($tag);
foreach($liste as $element){
$codeHtml->removeChild($element);
}
}
stripAttr($codeHtml,$forbiddenAttr);
}
function stripAttr(DOMNode $root, array $forbiddenAttr){
foreach($rootl->childNodes as $child){
foreach($forbiddenAttr as $attr){
if($child->hasAttribute($attr)) $child->removeAttribute($attr);
}.
if($child->hasChildNodes())strippAttr($child,$forbiddenAttr);
}
}
This is not the correct way to combat XSS.
You're using a blacklist that will eternally fail to catch all ways to include scripts. For example, you're not catching the onload
attribute or javascript:
links. Instead, always use DOM methods to construct text nodes and attribute values, and you will be safe by default. If you want to have users allow formatted text, use a whitelist of allowed elements, attributes, and attribute values.
精彩评论