MVC 安全性 : 重定向

来源:互联网 发布:centos ssh连接其他ip 编辑:程序博客网 时间:2024/06/06 00:28

 开放重定向:在mvc login controller 中,登陆会返回一个returnUrl.


下面列举一个案例:

下面的链接中dinner 少一个n, 恶意用户通过邮件或其他形式,让用户点击了如下的链接.

http://www.googledinner.com/Account/LogOn?returnUrl=http://www.googlediner.com/Account/LogOn

然后用户重定向到了伪造的页面,伪造页面和真实的页面几乎一模一样,用户很难察觉,然后用户输入密码,这时候伪造页面记录了用户的信息和密码,重定向到了真实的页面。用户以为密码输错了再输入一次就登陆到了真实的页面。

上面的案列,在用户不知道的情况下,盗窃了用户的密码!


1.在mvc1和mvc2中并没用验证returnUrl参数的正确性。在MVC3和MVC4中添加了

(Url.IsLocalUrl(returnUrl)


所以在mvc1和mvc2中需要自己添加如下代码:

//Note: This has been copied from the System.Web.WebPages RequestExtensions classprivate bool IsLocalUrl(string url){if (string.IsNullOrEmpty(url)){return false;}Uri absoluteUri;if (Uri.TryCreate(url, UriKind.Absolute, out absoluteUri)){return String.Equals(this.Request.Url.Host,absoluteUri.Host, StringComparison.OrdinalIgnoreCase);}else{bool isLocal = !url.IsEmpty() &&((url[0] == '/' && (url.Length == 1 ||(url[1] != '/' && url[1] != '\\'))) ||(url.Length > 1 && url[0] == '~' && url[1] == '/'));return isLocal;}}[HttpPost]public ActionResult LogOn(LogOnModel model, string returnUrl){if (ModelState.IsValid){if (Membership.ValidateUser(model.UserName, model.Password)){FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);if (Url.IsLocalUrl(returnUrl)){return Redirect(returnUrl);}Understanding the Security Vectors in a Web Application x 181else{return RedirectToAction("Index", "Home");}}else{ModelState.AddModelError("","The user name or password provided is incorrect.");}}// If we got this far, something failed, redisplay formreturn View(model);}



而且需要记录下日志信息:

如果是重定向url 有问题可以用免费的ELMAN日志库检记录下来,安全异常,并显示给用户安全性页面

        private ActionResult RedirectToLocal(string returnUrl)        {            if (Url.IsLocalUrl(returnUrl))            {                return Redirect(returnUrl);            }            else            {                Elmah.ErrorSignal.FromCurrentContext().Raise(new System.Security.SecurityException(string.Format("Open redirect to {0} detected.", returnUrl)));                // rediect to security warning page.                return RedirectToAction("SecurityWarning", "Home");            }        }

原创粉丝点击