How To: Prevent Cross-Site Scripting in ASP.NET

来源:互联网 发布:php虚拟空间 编辑:程序博客网 时间:2024/05/22 00:42

这篇文章讨论了,如何在ASP.Net防止Cross-Site Scipting攻击。有些地方还是值得借鉴的。

 

http://msdn.microsoft.com/en-us/library/ms998274.aspx

 

两条基本原则:

1)限制输入

2)加密输出

主要步骤:

  • Step 1. Check that ASP.NET request validation is enabled.
  • Step 2. Review ASP.NET code that generates HTML output.
  • Step 3. Determine whether HTML output includes input parameters.
  • Step 4. Review potentially dangerous HTML tags and attributes.
  • Step 5. Evaluate countermeasures.

1)加密 HTML 输出(Response.Write),用HttpUtility.HtmlEncode/Decode。把一些特殊的字符进行安全的转换。

转换原则如下:

  • The less-than character (< ) is converted to &lt; .

  • The greater-than character (> ) is converted to &gt ; .

  • The ampersand character (& ) is converted to &amp ; .

  • The double-quote character (" ) is converted to &quot ; .

  • Any ASCII code character whose code is greater-than or equal to 0x80 is converted to &#<number> , where <number> is the ASCII character value.

例如:Response.Write(HttpUtility.HtmlEncode(Request.Form["name"]));

2)加密URL输出(Response.Redirect),用HttpUtility.URLEncode/Decode。比如:

< 和 > 分别被编码为 %3c 和 %3e。

例如:Response.Redirect( HttpUtility.UrlEncode(urlString));

3)过滤用户的输入

A.在Page的Attribute添加ValidationRequest=False,禁止Asp.NET的输入验证机制。

B.当要输出到HTML叶面时,把用户输入的内容用Html.Encode加密,避免恶意脚本执行。比如:<script>alert("attacking!")</script>

C.使用StringBuilder,调用Replace来Remove HTML Element的输出。比如支持<b>,<i>。

<%@ Page Language="C#" ValidateRequest="false" %>

<script runat="server">

void submitBtn_Click(object sender, EventArgs e)

{ // Encode the string input

StringBuilder sb = new StringBuilder( HttpUtility.HtmlEncode(htmlInputTxt.Text));

// Selectively allow <b> and <i>

sb.Replace("&lt;b&gt;", "<b>");

sb.Replace("&lt;/b&gt;", " ");

sb.Replace("&lt;i&gt;", "<i>");

sb.Replace("&lt;/i&gt;", "");

Response.Write(sb.ToString()); }

</script>

4.Use the innerText Property Instead of innerHTML

// Using InnerText renders the content safe–no need to HtmlEncode

Welcome1.InnerText = "Hello, " + User.Identity.Name;

// Using InnerHtml requires the use of HtmlEncode to make it safe

Welcome2.InnerHtml = "Hello, " + Server.HtmlEncode(User.Identity.Name);


 

原创粉丝点击