0

I have a href which gets filled in by reading a property from a database like this

  lblName.HRef = user.PublicSiteUrl; 

I want to safely encode this URL to protect against any persisted XSS attack.

Which encoding should be useful for this without causing any issues with the URL structure?

For example, if I have this URL coming from the database https://google.com?q=<SCRIPT>alert(“Cookie”+document.cookie)</SCRIPT> ..How Do i make this URL safe so the script is not executed as part of URL

svick
  • 236,525
  • 50
  • 385
  • 514
sp9
  • 755
  • 3
  • 11
  • 22

2 Answers2

0

Why not HttpUtility.UrlEncode?

Dmitry Sadakov
  • 2,128
  • 3
  • 19
  • 34
  • Console.WriteLine(HttpUtility.UrlEncode("http://Test/k=")); This does not work. – sp9 May 07 '15 at 21:11
  • @user3637345 If you had a test scenario that you wanted tested, why didn't you add it to your question to begin with? – David L May 07 '15 at 21:12
  • Sorry I don't have a scenraio as such. I just wanted to see if there is built in class for something that prevents any XSS attack. – sp9 May 07 '15 at 21:14
  • @user3637345 how would you expect something to actually keep the url in tact? If a threat is detected, shouldn't the request be blocked entirely? – David L May 07 '15 at 21:19
  • have an example added in the question – sp9 May 07 '15 at 21:38
0

I think what you are looking for is Uri.EscapeUriString().

https://server/test.aspx?<SCRIPT>alert(“Cookie”+document.cookie)</SCRIPT>

Will become:

https://server/test.aspx?%3CSCRIPT%3Ealert(%E2%80%9CCookie%E2%80%9D+document.cookie)%3C/SCRIPT%3E
Guvante
  • 18,775
  • 1
  • 33
  • 64
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
  • This works for me..Do you know if there can be XSS attacks that bypass this encoding. – sp9 May 07 '15 at 21:48
  • This should prevent tags from getting inserted, but I suppose you would still have problems if someone entered `javascript:alert('hi')`. Perhaps you could also check that the url starts with http:// or https://. Also, this post has some good info http://stackoverflow.com/questions/205923/best-way-to-handle-security-and-avoid-xss-with-user-entered-urls – Mike Hixson May 07 '15 at 22:07