Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using prepared statement in the most secure way

From a security validation perspective, is there a difference between:

stmt.setObject(1, theObject);

and

stmt.setString(1, theObject);?

I know that in this case theObject is a String but I am interested in making part of this code more general to cover other cases and was wondering if the security perspective of input validation is affected

like image 438
Jim Avatar asked Nov 05 '12 08:11

Jim


People also ask

Why is PreparedStatement more secure?

Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.

Is PreparedStatement Secure?

So using prepared statements is safe from SQL injection, as long as you aren't just doing unsafe things elsewhere (that is constructing SQL statements by string concatenation).

What is the advantage of PreparedStatement?

What is the advantage of using PreparedStatement? PreparedStatement objects are used to execute repetitive SQL statements. Compared to Statement object execution, Prepared Statement object creation is faster. The reason is the object is pre compiled, by eliminating the compilation task by DBMS.

Can all SQL queries be made safe using prepared statements?

Prepared statements can protect only data literals, but cannot be used with any other query part.


1 Answers

It is ok to use ssetObject() because jdbc will try to to do the type resolution for all java.lang.* types.

However, there is potential problem with passing an arbitrary SQL string to the database in this way - Security loopholes: without very judicious validation of any parameters that you use to build up the SQL string, you are liable to various types of SQL insertion attacks.

Beware of passing untyped null to setObject()

like image 86
aviad Avatar answered Oct 05 '22 22:10

aviad