1

My URL looks like the following:
http://example.com/value=S%0a%0d"><'script>alert(0)<'/script'>%20"

When I print value of the value request parameter in my Servlet, using the following code:

String Value=request.getParameter("value");

System.out.print("URL :"+Value);

The output is as follows:

URL :S

"><'script>alert(0)<'/script'>%20

It printed two lines (which makes this possibly vulnerable to XSS attacks). I tried the code below to replace the %0A%0D characters:

Value = value.replace('\n', ' ');
Value = value.replace('\r', ' ');
Value = value.replace("\n", "");
value = value.replace("\r", "");
value = value.replaceAll("0A", "");
value = value.replaceAll("0D", "");
value = value.replaceAll("%0A", "");
value = value.replaceAll("%0D", "");
value = value.replaceAll("%0A%0D", "");

But it only checks the first line of the output. How can I remove these characters from the URL, in order to mitigate XSS attacks?

Xiddoc
  • 3,369
  • 3
  • 11
  • 37

1 Answers1

1

To protect against XSS, I would advise against a character by character replace as you have used in the example snippet. You are bound to forget something from your list of characters you are substituting and you application may continue to be vulnerable.

Instead, I would recommend using: https://www.owasp.org/index.php/OWASP_Java_Encoder_Project

Anurag Kapur
  • 675
  • 4
  • 19
  • I can't able to use third party library.Is there any other solution? – user1976891 Feb 17 '15 at 06:02
  • The project mentioned above is opensource. If you do not want to use it directly, you could refer to the code and replicate/duplicate the code as you like. Source code: https://code.google.com/p/owasp-java-encoder/source/browse/#svn%2Ftrunk In summary the correct approach would be to encode all chars appropriately instead of having code that replaces unsafe chars. – Anurag Kapur Feb 17 '15 at 12:48