I think you are attacking it from the wrong angle by trying to encode all posted data.
(我认为您通过尝试对所有发布的数据进行编码而从错误的角度进行了攻击。)
Note that a " <
" could also come from other outside sources, like a database field, a configuration, a file, a feed and so on.
(请注意,“ <
”也可能来自其他外部来源,例如数据库字段,配置,文件,提要等。)
Furthermore, " <
" is not inherently dangerous.
(此外,“ <
”并不是天生的危险。)
It's only dangerous in a specific context: when writing strings that haven't been encoded to HTML output (because of XSS). (这仅在特定情况下是危险的:在编写尚未编码为HTML输出的字符串时(由于XSS)。)
In other contexts different sub-strings are dangerous, for example, if you write an user-provided URL into a link, the sub-string " javascript:
" may be dangerous.
(在其他情况下,不同的子字符串很危险,例如,如果您将用户提供的URL写入链接,则子字符串“ javascript:
”可能很危险。)
The single quote character on the other hand is dangerous when interpolating strings in SQL queries, but perfectly safe if it is a part of a name submitted from a form or read from a database field. (另一方面,在SQL查询中插入字符串时,单引号字符很危险,但是如果它是从表单提交的名称或从数据库字段读取的名称的一部分,则单引号是完全安全的。)
The bottom line is: you can't filter random input for dangerous characters, because any character may be dangerous under the right circumstances.
(最重要的是:您不能过滤危险字符的随机输入,因为在适当的情况下任何字符都可能是危险的。)
You should encode at the point where some specific characters may become dangerous because they cross into a different sub-language where they have special meaning. (您应该在某些特定字符可能会变得危险的地方进行编码,因为它们会跨入具有特殊含义的不同子语言。)
When you write a string to HTML, you should encode characters that have special meaning in HTML, using Server.HtmlEncode. (在将字符串写入HTML时,应使用Server.HtmlEncode对在HTML中具有特殊含义的字符进行编码。)
If you pass a string to a dynamic SQL statement, you should encode different characters (or better, let the framework do it for you by using prepared statements or the like).. (如果将字符串传递给动态SQL语句,则应该对不同的字符进行编码(或者更好的方法是,让框架通过使用准备好的语句等为您完成此操作)。)
When you are sure you HTML-encode everywhere you pass strings to HTML, then set validateRequest="false"
in the <%@ Page ... %>
directive in your .aspx
file(s).
(当确定将HTML字符串传递给HTML的所有地方都经过HTML编码后,请在.aspx
文件的<%@ Page ... %>
指令中设置validateRequest="false"
。)
In .NET 4 you may need to do a little more.
(在.NET 4中,您可能需要做更多的事情。)
Sometimes it's necessary to also add <httpRuntime requestValidationMode="2.0" />
to web.config ( reference ). (有时,还必须将<httpRuntime requestValidationMode="2.0" />
到web.config( 参考 )。)