检查是否在生成的数据中打印JavaScript?
时间:2020-03-06 14:57:22 来源:igfitidea点击:
在我的php Web应用程序中,假设我想加倍努力,除了帮派破坏者和对输入内容进行消毒的态度外,我还想确保在插入html的字符串中没有输出JavaScript。模板。
有没有一种标准的方法来确保我不在生成的html内容中放入JavaScript?
解决方案
不完全是一种标准方式;因为如果我们正在做的话:<img src =" $ {path}">
和$ {path}
扩展为
`http://p0wned.com/jpg.jpg" /> <script src =" p0wned.com/js.js" />
无论如何,我喜欢这个正则表达式:
#from http://www.perlmonks.org/?node_id=161281 sub untag { local $_ = $_[0] || $_; # ALGORITHM: # find < , # comment <!-- ... -->, # or comment <? ... ?> , # or one of the start tags which require correspond # end tag plus all to end tag # or if \s or =" # then skip to next " # else [^>] # > s{ < # open tag (?: # open group (A) (!--) | # comment (1) or (\?) | # another comment (2) or (?i: # open group (B) for /i ( TITLE | # one of start tags SCRIPT | # for which APPLET | # must be skipped OBJECT | # all content STYLE # to correspond ) # end tag (3) ) | # close group (B), or ([!/A-Za-z]) # one of these chars, remember in (4) ) # close group (A) (?(4) # if previous case is (4) (?: # open group (C) (?! # and next is not : (D) [\s=] # \s or "=" ["`'] # with open quotes ) # close (D) [^>] | # and not close tag or [\s=] # \s or "=" with `[^`]*` | # something in quotes ` or [\s=] # \s or "=" with '[^']*' | # something in quotes ' or [\s=] # \s or "=" with "[^"]*" # something in quotes " )* # repeat (C) 0 or more times | # else (if previous case is not (4)) .*? # minimum of any chars ) # end if previous char is (4) (?(1) # if comment (1) (?<=--) # wait for "--" ) # end if comment (1) (?(2) # if another comment (2) (?<=\?) # wait for "?" ) # end if another comment (2) (?(3) # if one of tags-containers (3) </ # wait for end (?i:) # of this tag (?:\s[^>]*)? # skip junk to ">" ) # end if (3) > # tag closed }{}gsx; # STRIP THIS TAG return $_ ? $_ : ""; }
如果我们不反对外部依赖关系,那么HTML Purifier库对于大多数XSS攻击都是一个很好的过滤器。
在PHP中,我将从strip_tags开始。像这样:
$output = strip_tags($input);
如果我想在用户输入中允许一些标签,则可以将它们包括在内,如下所示:
$output = strip_tags($input, '<code><em><strong>');
我认为不可能找到这样的javascript代码。
我们必须将数据通过某种类型的解释器传递,以尝试查找有效的js语句。这将占用大量处理器资源,并且可能会根据文本的性质而产生许多误报。
实体转义元字符可能是进一步保护应用程序免受过滤器可能错过的攻击的最佳方法。如果将Javascript作为常规文本加载,则无法运行。