1

I am doing a web project using Java MVC, it has one search box. I am getting the search string from this text box and in turn calling a Javascript search script method. It in turn calls a Web service to search. Now if I search for a script like:

<script>alert("helllooooo")<\script >

then it alerts helloooo as well as searches using services. How can I avoid evaluating a script in this situation.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Juhan
  • 1,283
  • 2
  • 11
  • 30

3 Answers3

0

You would have to sanitize the input before sending it to your web service or searching on it.

By sanitizing it would mean escaping all HTML and Javascript tags from the input string.

Check the Apache StringEscapeUtils class for such methods like escapeJava, escapeJavascript etc. You would have to do this on the web service end. If you want this to happen on the javascript side itself you would have to write a Javascript function that would explicitly escape the HTML and JS special characters (notably the tags)

Prahalad Deshpande
  • 4,709
  • 1
  • 20
  • 22
  • Mainly If I enter one script it should not work, example if I search alert(hello ) this should not executed in the client side as well as search string without script should be passed to the service – Juhan May 28 '15 at 16:15
  • 1
    No. This is a security issue. You can't rely on client-side validation because it can be bypassed. – Neil Smithline May 28 '15 at 23:12
0

You have a cross-site scripting (XSS) vulnerability here. You need to do server-side escaping to prevent exploitation. This question has several potential solutions. You can also refer to the OWASP XSS Cheat Sheet.

Client-side escaping is insufficient because an attacker will bypass your client-side code when performing an attack.

Neil Smithline
  • 1,526
  • 9
  • 21
  • if I give one alert script, am getting alert. Actually when it's working, after getting Web services result or before or when I click the search button it's self? – Juhan May 29 '15 at 00:44
  • You want to do the escaping just before returning the data to the client – Neil Smithline May 29 '15 at 02:27
-1

You can replace the < and > like this :

var html = document.getElementById("searchboxid").value;
html = html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
loli
  • 1,058
  • 8
  • 14