Im writing a java program and I have a SQL statement that currently is outputting wrong:
so the code is:
String sql = "SELECT Name from Users WHERE Name LIKE "+t;
and the Output is:
SELECT Name from Users WHERE Name LIKE David
But I need it to be with single quotes how can I add that to be like:
SELECT Name from Users WHERE Name LIKE 'David'
how can I add those quotes?
Many thanks for the help
This is a very common mistake. I'm guessing you are using Statement class to create your query and executing it.
I'd like to suggest that you use prepared statements. It'll since your issue and help you with further issues.
PreparedStatement ps = yourconn.prepareStatement("select name from users where name like ?");
ps.setString(1,yoursearchedusername);
ResultSet rs = ps.executeQuery();
This will add your quotes. Plus it will prevent from sql injection attacks in future.
Your current query will also cause issues of your actual query has ' or ? Or any other sql wild card. Prepared statement avoids all these issues and helps with performance by having the sql already compiled and stored at db layer (if enabled)
Use a prepared statement to prevent sql injections.
String searchedName = "cdaiga";
String sql = "SELECT Name from Users WHERE UPPER(Name) LIKE '%?%'";
PreparedStatement preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setString(1, (searchedName!=null? searchedName.toUpper(): ""));
// execute the SQL stetement
preparedStatement .executeUpdate();
ResultSet rs = preparedStatement.executeQuery();
// print the results if any is returned
while (rs.next()) {
String name= rs.getString("Name");
System.out.println("name: " + name);
}
Note that a case insensitive search would be appropriate.
Related
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.
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.
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).
You can check THIS article for info on that! :)
I recommend Parameterized Queries:
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
An attacker just has to enter something like 'foo#example.com"); DROP TABLE customer; into the field for email and you are done.
You can prevent this by using the proper escaping for JDBC Statements.
That's why you should be using question marks in your string statements:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
quoted from here
As explained in this post, the PreparedStatement alone does not help you if you are still concatenating Strings.
For instance, one rogue attacker can still do the following:
call a sleep function so that all your database connections will be busy, therefore making your application unavailable
extracting sensitive data from the DB
bypassing the user authentication
And it's not just SQL, but JPQL and HQL can be compromised if you are not using bind parameters:
PreparedStatement ps = connection.prepareStatement(
INSERT INTO customer(name,address,email) VALUES(?, ?, ?)
);
int index = 0;
ps.setString(++index, name);
ps.setString(++index, address);
ps.setString(++index, email);
ResultSet rs = ps.executeQuery();
Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:
JPA Criteria API
jOOQ
Go for PreparedStatement
Advantages of a PreparedStatement:
Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.
Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value
You should also limit the privileges of the account that accesses the database as tightly as possible. For example, for searching, the account only needs to have read access to those tables and columns that are required. This will prevent any damaging SQL injection and limit access to sensitive data.
Even though all the other answers tell you as how can you fix SQL injections in Java, answer by Mukesh Kumar actually tells you as who is actually preventing these kind of attacks. Understand that its actually DB server which is preventing SQL injection attacks provided you as a programmer follow their recommendation of using parametrized queries.
Refer Here - Preventing SQL Injection Vulnerabilities
It wouldn't be possible for Java programmer to sanitize each & every input String so DB vendors have given us options of Prepared Statements and they tell us to prepare & execute queries by using that & rest of the things will be taken care of by the DB vendor.
Things as drastic as DROP TABLE customer; might not happen but basic premise of SQL injection is that nobody should be able to break your query by just providing invalid input ( either intentional or non - intentional ).
OWASP - SQL Injection Prevention Cheat Sheet
Here's my query:
select *
from reg
where indexno=?
or tel=?
And here's my code:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
String query = "select * from reg where indexno= ? or tel=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Let's take a closer look at what your code is doing.
Connecting to the database:
Connection con =DriverManager.getConnection("jdbc:mysql://url","unam","pass");
Creating the SQL query:
String query = "select * from reg where indexno= ? or tel=?"`;
Creating a prepared statement:
PreparedStatement ps = con.prepareStatement(query);
Setting some bind parameter values:
ps.setString(1, in.getText());
ps.setString(2, tl.getText());
Creating a whole new non-prepared statement (wait, what? Why are we not using the prepared statement we spent some time creating?):
Statement st = con.createStatement();
Using the new non-prepared statement to execute the SQL query.
ResultSet rs = st.executeQuery(query);
As a result of the last two lines, your SQL query is sent straight to the MySQL database. MySQL doesn't understand what the ? marks are for, and hence complains with a syntax error about them.
When handling prepared statements, JDBC drivers will either replace the ? marks with the database's own syntax for bind parameters (unless the database supports ? marks directly, but not all databases do), or put the values directly in the SQL string after suitable escaping of any characters, before they send the SQL to the database. Statements don't support bind parameters, and will just send the SQL string they are given straight to the database.
Your code creates a PreparedStatement and sets two bind parameter values. It seems a shame not to actually use your prepared statement once you've created it. You can get the result set you want out of it by calling ps.executeQuery(). There is no need for the separate Statement you created by calling connection.createStatement().
The fix therefore is to remove the last two lines of the code in your question and add the following line in place of them:
ResultSet rs = ps.executeQuery();
I'm trying to execute following SQL query where it tries to find results that matches the column2 values ending with abc
PreparedStatement stmt = conn.prepareStatement("SELECT column1 FROM dbo.table1 WHERE column2 LIKE ?");
stmt.setString(1, "%" +"abc");
But it returns nothing even though there is a matching value. This only happens with SQL Server. Same query with informix database returns correct results. Anyone has an idea about what causing this to behave differently?
Is this due to an issue in how PreparedStatement creates the SQL query for SQL Server?
Edit
I found out this happens when the data in the column which i perform the like contain space. eg: when the column contains "some word" and if i perform the search by stmt.setString(1, "%" + "word"); it won't return a matching result but if i perform the same on for "someword" it would return the matching result
SQL Server accepts wild characters in the LIKE clause within the single quotation marks, like this ''.
A sample SQL query:
SELECT NAME FROM VERSIONS WHERE NAME LIKE 'Upd%'
The query above will yield you results on SQL Server. Applying the same logic to your Java code will retrieve results from your PreparedStatement as well.
PreparedStatement stmt = conn.prepareStatement("SELECT NAME FROM VERSIONS WHERE NAME LIKE ?");
stmt.setString(1, "Upd%");
I've tested this code on SQL Server 2012 and it works for me. You need to ensure that there are no trailing spaces in the search literal that you pass on to your JDBC code.
Though as a side note, you need to understand that a wildcard % used in the beginning, enforces a full table scan on the table which can deteriorate your query performance. A good article for your future reference.
Hope this helps!
i have same problem,i have done with the CONCATE function for this.
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
ps.setString(1, notes);
ResultSet rs = ps.executeQuery();
I read many articles on Stack Overflow regarding how SQL injection can be prevented by using prepared statements
But is there any way to do SQL injection even on prepared statements or is it 100% safe?
Below is my java code
String query = "SELECT * FROM Users WHERE username=? and password=?";
ps=con.prepareStatement(query);
ps.setString(1,username);
ps.setString(2,password);
rs = ps.executeQuery();
status = rs.next();
if(status==true){
.....
}else{
....
}
I tried some sql injection queries like
Some Inputs:
SELECT * FROM users WHERE username = 'xxx#xxx.xxx' OR 1 = 1 LIMIT 1 -- ' ] AND password = md5('1234');
SELECT * FROM users WHERE email = 'xxx#xxx.xxx' AND password = md5('xxx') OR 1 = 1 -- ]');
I have also tried with some more queries but as the (single quote)' is escaped(/') none of the SQL injection queries seem to work.
Kindly suggest me if there are any SQL injection queries/techniques which can be applied to do SQL injection in the above code.
This query : String query = "SELECT * FROM Users WHERE username=? and password=?"; is safe, because whatever the parameters can be, it will still be executed as a simple select. At most, it will end browsing a whole table.
But prepared statement is just a tool and (bad) programmers may still misuse it.
Let's look at the following query
String query = "SELECT id, " + paramName + " FROM Users WHERE username=? and password=?";
where paramName would be a parameter name. It is only as safe as paramName is, because you use directly a variable to build the string that will be parsed by the database engine. Here PreparedStatement cannot help because JDBC does not allow to parameterize a column name.
So the rule here will be :
avoid such a construct if you can !
if you really need it, double check (regexes, list of allowed strings, etc.) that paramName cannot be anything other than what you expect because that control is the only prevention against SQL injection
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.
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.
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).
You can check THIS article for info on that! :)
I recommend Parameterized Queries:
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
An attacker just has to enter something like 'foo#example.com"); DROP TABLE customer; into the field for email and you are done.
You can prevent this by using the proper escaping for JDBC Statements.
That's why you should be using question marks in your string statements:
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00)
pstmt.setInt(2, 110592)
quoted from here
As explained in this post, the PreparedStatement alone does not help you if you are still concatenating Strings.
For instance, one rogue attacker can still do the following:
call a sleep function so that all your database connections will be busy, therefore making your application unavailable
extracting sensitive data from the DB
bypassing the user authentication
And it's not just SQL, but JPQL and HQL can be compromised if you are not using bind parameters:
PreparedStatement ps = connection.prepareStatement(
INSERT INTO customer(name,address,email) VALUES(?, ?, ?)
);
int index = 0;
ps.setString(++index, name);
ps.setString(++index, address);
ps.setString(++index, email);
ResultSet rs = ps.executeQuery();
Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:
JPA Criteria API
jOOQ
Go for PreparedStatement
Advantages of a PreparedStatement:
Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.
Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value
You should also limit the privileges of the account that accesses the database as tightly as possible. For example, for searching, the account only needs to have read access to those tables and columns that are required. This will prevent any damaging SQL injection and limit access to sensitive data.
Even though all the other answers tell you as how can you fix SQL injections in Java, answer by Mukesh Kumar actually tells you as who is actually preventing these kind of attacks. Understand that its actually DB server which is preventing SQL injection attacks provided you as a programmer follow their recommendation of using parametrized queries.
Refer Here - Preventing SQL Injection Vulnerabilities
It wouldn't be possible for Java programmer to sanitize each & every input String so DB vendors have given us options of Prepared Statements and they tell us to prepare & execute queries by using that & rest of the things will be taken care of by the DB vendor.
Things as drastic as DROP TABLE customer; might not happen but basic premise of SQL injection is that nobody should be able to break your query by just providing invalid input ( either intentional or non - intentional ).
OWASP - SQL Injection Prevention Cheat Sheet