Mathieu Pagé
Mathieu Pagé

Reputation: 11064

How can I make sure a url provided by the user is not a local path?

I'm writhing a web application (ASP.Net MVC, C#) that require the user to provide urls to RSS or Atom Feed that I then read with the following code :

var xmlRdr = XmlReader.Create(urlProvidedByUserAsString);
var syndicFeed = SyndicationFeed.Load(xmlRdr);

While debugging my application I accidentally passed /something/like/this as an url and I got an exception telling me that C:\something\like\this can't be opened.

It looks like a user could provide a local path and my application would try to read it.

How can I make this code safe? It probably is not sufficient to check for https:// or http:// at the begining of the url, since the user could still enter something like http://localhost/blah. Is there any other way, maybe with the uri class to check if an url is pointing to the web?

Edit: I think I also need to prevent the user from entering adresses that would point to other machines on my network like this example: http://192.168.0.6/ or http://AnotherMachineName/

Upvotes: 5

Views: 676

Answers (1)

Roman Sokk
Roman Sokk

Reputation: 175

Try:

new Uri(@"http://stackoverflow.com").IsLoopback
new Uri(@"http://localhost/").IsLoopback
new Uri(@"c:\windows\").IsLoopback

Upvotes: 1

Related Questions