不受信任的 URL 字符串的 Safe Process.Start 实现 [英] Safe Process.Start implementation for untrusted URL strings

查看:31
本文介绍了不受信任的 URL 字符串的 Safe Process.Start 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在用户的默认浏览器中安全地打开网页.此网页的 URL 被视为不受信任"(将其视为使用此软件打开的文档中的链接,但该文档可能来自任何地方且其中的链接可能是恶意的)

My goal is to safely open a web page in a users default browser. The URL for this web page is considered "untrusted" (think of it as a link in a document opened with this software, but the document could be from anywhere and the links in it could be malicious)

我想避免有人将C:\Windows\malicious_code.exe"作为 URL 传递

I want to avoid someone passing "C:\Windows\malicious_code.exe" off as a URL

我目前的想法是做这样的事情:

My current thought is to do something like this:

Uri url = new Uri(urlString, UriKind.Absolute);
if( url.Scheme == Uri.UriSchemeHttp || url.Scheme == Uri.UriSchemeHttps )
{
   Process.Start(url.AbsoluteUri);
}

我是否忘记了我的 'urlString' 可能包含的任何其他内容使这变得危险(例如,一个新行字符将允许某人在 URL 或可能执行相关可执行文件之后偷偷启动第二个进程以 http 开头)?

Am I forgetting about anything else that my 'urlString' might contain that makes this dangerous (e.g. a new line character which would allow someone to sneak a second process to be started in after the URL or a possible execution of a relative executable starting with http)?

我很确定这两种情况都是由这个处理的(因为我不相信 Process.Start 允许您像在 BATCH 文件中那样启动两个进程,这应该只允许以 http: 开头的字符串:或https:并且是有效的网址)

I'm pretty sure both of those cases are handled by this (as I don't believe Process.Start allows you to start two processes as you would in a BATCH file and this should only allow strings starting with http: or https: and are valid urls)

在 C# 中是否有更好的方法来做到这一点?

Is there a better way to do this in C#?

推荐答案

你要检查的是url的scheme(即ftp://http://file:// 等)这里是一个方案列表:http://en.wikipedia.org/wiki/URI_scheme#Official_IANA-registered_schemes

What you want to check is the scheme of the url (i.e. ftp://, http://, file://, etc.) Here is a list of schemes: http://en.wikipedia.org/wiki/URI_scheme#Official_IANA-registered_schemes

要查找 URL 的方案,请使用:

To find the scheme of a URL, use:

Uri u = new Uri("C:\\Windows");
String scheme = (u.GetLeftPart(UriPartial.Scheme).ToString());

对我来说,上面的例子给出了 file://.只需使用上面的代码检查方案,然后拒绝您要过滤的方案.另外,用 try-catch 块包围解析,如果捕获到异常,则拒绝 URL;它无法解析,所以你不应该相信它.

For me, the above example gives file://. Just check the scheme, using the code above, and reject the ones you want to filter. Also, surround the parsing with a try-catch block and if an exception is caught, reject the URL; it can't be parsed so you shouldn't trust it.

如果您想要超偏执安全,您可以随时使用 URL 解析器解析 URL 并重建它,并在执行过程中验证每个部分.

If you want to ultra-paranoid-safe, you could always parse the URL using a URL parser and reconstruct it, validating each part as you go along.

这篇关于不受信任的 URL 字符串的 Safe Process.Start 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆