[英]How to encode value to put in iframe src attribute to prevent XSS in ASP.NET MVC
Using ASP.NET MVC, I have an url that takes a querystring param called path, which can be a url within my site. 使用ASP.NET MVC,我有一个网址,该网址带有一个名为path的查询字符串参数,该参数可以是我网站中的一个网址。 I found a XSS vulnerability and I cannot figure out how to encode the path value correctly to prevent XSS (but not do a lot of code to whitelist acceptable urls)
我发现了一个XSS漏洞,但无法弄清楚如何正确编码路径值以防止XSS(但没有做很多代码将可接受的URL列入白名单)
So the url that the user visits is: 因此,用户访问的网址是:
/iFrame?path=mypage.aspx
The XSS can be seen like this: XSS可以这样看:
/iFrame?path=javascript:alert%281%29
The HTML for the iFrame that uses the path querystring value is: 使用路径querystring值的iFrame的HTML为:
<iframe src="@Model.Source"></iframe>
I've also tried: 我也尝试过:
Both of those methods still display the javascript alert box. 这两种方法仍会显示javascript警报框。
Is there a built in encoder for ASP.NET MVC that will encode it so that the src will not execute javascript? 是否有用于ASP.NET MVC的内置编码器,它将对其进行编码,以使src无法执行javascript? Or do I need to do a some whitelisting or other methods to protect against it?
还是我需要做一些白名单或其他方法来防止这种情况?
I'd recommend reading Preventing Open Redirection Attacks (C#) which talks about using the IsLocalUrl() method from the ASP.NET MVC 3 UrlHelper class: 我建议阅读ASP.NET MVC 3 UrlHelper类中的“ 防止开放重定向攻击(C#)” ,其中涉及使用IsLocalUrl()方法:
public bool IsLocalUrl(string url) {
return System.Web.WebPages.RequestExtensions.IsUrlLocalToHost(
RequestContext.HttpContext.Request, url);
}
IsUrlLocalToHost() method from the System.Web.WebPages RequestExtensions class: System.Web.WebPages RequestExtensions类中的IsUrlLocalToHost()方法:
public static bool IsUrlLocalToHost(this HttpRequestBase request, string url)
{
return !url.IsEmpty() &&
((url[0] == '/' && (url.Length == 1 ||
(url[1] != '/' && url[1] != '\\'))) || // "/" or "/foo" but not "//" or "/\"
(url.Length > 1 &&
url[0] == '~' && url[1] == '/')); // "~/" or "~/foo"
}
You need to parse the URL and whitelist the protocol. 您需要解析URL并将协议列入白名单。
Call Uri.TryParse()
, and reject any URL for which that returns false, or has a protocol other than HTTP or HTTPS. 调用
Uri.TryParse()
,并拒绝任何返回false或具有HTTP或HTTPS以外的协议的URL。
You also need to decide whether to allow relative URLs. 您还需要确定是否允许相对URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.