Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent SQL injection attacks in a Java program

I have to add a statement to my java program to update a database table:

String insert =
    "INSERT INTO customer(name,address,email) VALUES('" + name + "','" + addre + "','" + email + "');";

I heard that this can be exploited through an SQL injection like:

DROP TABLE customer; 

My program has a Java GUI and all name, address and email values are retrieved from Jtextfields. I want to know how the following code (DROP TABLE customer;) could be added to my insert statement by a hacker and how I can prevent this.

like image 400
Grant Avatar asked Mar 01 '12 12:03

Grant


2 Answers

You need to use PreparedStatement. e.g.

String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStatement ps = connection.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, addre);
ps.setString(3, email);

ResultSet rs = ps.executeQuery();

This will prevent injection attacks.

The way the hacker puts it in there is if the String you are inserting has come from input somewhere - e.g. an input field on a web page, or an input field on a form in an application or similar.

like image 95
Matt Fellows Avatar answered Sep 20 '22 12:09

Matt Fellows


I want to know how this kind piece of code("DROP TABLE customer;") can be added to my insert statement by a hacker

For example:

name = "'); DROP TABLE customer; --"

would yield this value into insert:

INSERT INTO customer(name,address,email)     VALUES(''); DROP TABLE customer; --"','"+addre+"','"+email+"');

I specially want to know how can I prevent this

Use prepared statements and SQL arguments (example "stolen" from Matt Fellows):

String insert = "INSERT INTO customer(name,address,email) VALUES(?, ?, ?);";
PreparedStament ps = connection.prepareStatment(insert);

Also parse the values you have on such variables and make sure they don't contain any non-allowed characters (such as ";" in a name).

like image 38
m0skit0 Avatar answered Sep 21 '22 12:09

m0skit0