0

I have a jsp-form with field named Description. This field declared as follows

<input type="text" name="description">

This value used to compose SQL query:

select * from Engines where description like '% (Value from the field)%'

When a user enters alphanumeric characters it works fine, but it fails when user enters special characters, like single quote symbol: '

My questions:

  1. How can I deal with this on the server-side
  2. If it is necessary to implement on JavaScript, then what characters have to be filtered out?

Thank you.

Sunny Gupta
  • 6,929
  • 15
  • 52
  • 80
  • Endusers have full control over JavaScript code. So absolutely don't do this kind of escaping in JavaScript. Use `PreparedStatement` in server side. Whatever framework you're using that doesn't support it, blame its authors. This is a **huge** design mistake in the framework as it puts doors wide open to SQL injection attacks. – BalusC Apr 26 '12 at 14:24

4 Answers4

3

Use prepared statement instead of composing SQL query string. Your way is vulnerable to SQL Injection attack.

If it is not possible to use PreparedStatements, then use java regular expression to remove special chars before passing this field value to SQL query.

There is a post related to this task.

Do not use javascript to filter out special symbols. It won't protect you from sql-injection attack. An attacker may forge his own form without validation javascript and attack your server.

Community
  • 1
  • 1
1

Use parameterized query for handle this kind of problems.

hkutluay
  • 6,794
  • 2
  • 33
  • 53
  • I think you are talking about PreparedStatement in java, But it is not possible for me to use the PreparedStatement as the framework does not support it. – Sunny Gupta Apr 26 '12 at 12:57
0

What you do is considered a very bad practice and may result in very bad things... http://en.wikipedia.org/wiki/SQL_injection

Frantisek Kossuth
  • 3,524
  • 2
  • 23
  • 42
0

You could remove the invalid characters through basic validation using JavaScript and Regex:

<script type="text/javascript">
var str= document.getElementById('mySearch').value;
str=str.replace(/[^A-Za-z0-9]/g,'');
alert(str);
</script>

But I agree with hkutluay, parametrized queries would be the better route.

SurinderBhomra
  • 2,169
  • 2
  • 24
  • 49