We've got an interstitial page that warns people when they're leaving our site. The trouble is it takes querystring parameters and blindly generates a page, thus it's vulnerable to XSS attacks. I've been tasked with fixing it and I want to do it right.
views:
76answers:
5Yes, try this:
if(Uri.IsWellFormedUriString(url, UriKind.Absolute) && url.StartsWith("http"))
Response.Write(string.Format("<a href=\"{0}\">{0}</a>",
HttpUtility.HtmlEncode(url)));
You should call Server.HtmlEncode
to properly escape your generated HTML.
One solution is to store the destination urls in a database or other data store that cannot be accessed from the internet. Then you could pass a key value to the interstitial warning page in the query string and have the page read the url from your database on the server side.
So things not to do;
- Use regex
- Use HtmlEncode without thought.
Things to do;
- Treat all input as untrusted.
- Encode input before it is output. However make sure you're using the right type of encoding. If you put user input in an attribute then you use HtmlAttributeEncode, if it's just HTML then you use HtmlEncode, if you put it into JavaScript then it's JavaScriptEncode. If your javascript puts it into a div then it's HtmlEncode, followed by JavaScriptEncode.
- Consider using AntiXSS which provides more encoding mechanisms and uses a safe list approach which is inherently safer.
- Whitelist the exit URLs so people cannot use this page as an open referrer. Do not have a parameter which has the URL, rather have a GUID which looks up the URL from a database, session table or whatever.
(Disclosure : I own AntiXSS)
The best way is to get rid of the page entirely and just accept that its a website and make it act like a website. Websites link to other resources, it's why the web has over 200million sites instead of about a dozen.
Failing that, your best bet is to start with HtmlEncoding as a quick fix, and then replacing it with a lookup of ids to bring one to different sites.
But really, those "ZOMG you are leaving!" pages are horrible. They're even worse than the sites that open new tabs for every so-called "external" link.