Is there a possible way to inject some code in the the following statements (I tried the sleep function and it worked , but i'm looking for a way to get the table's name):
PreparedStatement statement = connection.prepareStatement(
"select password from " + USERS_TABLE_NAME + " where userid = ? and password = ?");
statement.setString(1, username_login);
statement.setString(2, password_login);
Using a prepared statement makes the code safe from SQL injection; the only way to inject some code into that query would be to tamper with USERS_TABLE_NAME somehow. I can't tell much about this as you didn't provide any code related to this, but if it's just a string constant you should be fine.
I read it can be be injectable using the ORDER BY clause !!
The example you showed above is not vulnerable to injection in the ORDER BY clause. The query doesn't even have an ORDER BY clause, or any string concatenation that could append an ORDER BY clause to the end of the query.
SQL injection can occur only if you allow untrusted content to modify the SQL query before passing it to the prepare() method.
Related
Does this prevent SQL injection or do I have to pass the parameter with preparedStatement.setString()
String sqlQuery = "select st from master where st_id= %1s ";
sqlQuery = String.format(sqlQuery, id);
preparedStatement = conn.prepareStatement(sqlQuery);
rs = preparedStatement.executeQuery();
This is not a code review, the code above is an example for the question.
You are directly embedding user input in SQL code right here:
String.format(sqlQuery, id)
Effectively running user input as code. So, no, this is not safe from SQL injections. This is the definition of SQL injections.
Instead of directly embedding user input into the SQL code, use parameters in a prepared statement to treat user input as values rather than as code. Essentially the query would become this:
String sqlQuery = "select st from master where st_id= ? ";
Then you'd use the tooling in the language to add the parameter value to the query:
preparedStatement = conn.prepareStatement(sqlQuery);
preparedStatement.setInt(1, id); // <--- here
rs = preparedStatement.executeQuery();
Side note: Some may point out that if id is a non-string type then this code would still be safe from SQL injections, because nobody could inject anything dangerous as a number for example. While that may be circumstantially true for any given instance of this, it's not guaranteed and still not safe practice.
Always treat user input as values, not as code. Regardless of the type of that input or how sure you may otherwise be of the source of that input. Don't give an attacker any avenue of attack, even if you can't think of any way in which they can exploit it.
I am executing an update and I want to insert the value that is returned from my getter into the my table.
statement.executeUpdate("INSERT INTO my_table " +
"VALUES(myClass.getValue(), 'abcd',now())");
I have tried debugging through and I found that the String value and datetime executes correctly. However it gives me an exception when I am calling my getter. The detail message that it shows is FUNCTION myClass.getValue does not exist.
My imports are in order. Any ideas?
statement.executeUpdate("INSERT INTO my_table " + "VALUES("+myClass.getValue() + ", 'abcd',now())");
Your get-call was interpreted as a String because of the missing ' " '.
Take a look at prepared statements, they are easy to read and use and you don't have to struggle with these problems.
Prepared Statement Version (also a lot more secure because they are preventing SQL Injection):
PreparedStatement pst = yourconnection.prepareStatement("INSERT INTO my_table VALUES(?,?,now())";
pst.setString(1,myClass.getValue());
pst.setString(2,"abcd");
pst.executeUpdate();
This is the SQL that you're trying to execute.
INSERT INTO my_table VALUES(myClass.getValue(), 'abcd',now())
You need to pass valid SQL to the executeUpdate method in order for it to run. Java won't interpolate variables and method calls inside strings for you. You have to either concatenate their values into the SQL string that you pass to executeUpdate, or use Prepared Statements instead.
You need to make a method call to your myClass object, not a string. The string will not be executed, its not code, just words.
statement.executeUpdate("INSERT INTO my_table VALUES(" + myClass.getValue() + ", 'abcd',now())");
I'm going to show you how to do it with prepared statements since the other answers did not show you:
PreparedStatement prepStmt = con.prepareStatement("INSERT INTO my_table VALUES( ? , 'abcd',now())"));
prepStmt.setString(1, myClass.getValue());
prepStmt.executeUpdate();
Notice the ?. It will get replaced by your Java call to myClass.getValue().
Please do not concatenate SQL strings.
I'm trying to build a web page to better learn Java and SQL. My question is, is there a way in Java to make a generic SQL select statement? For example:
SELECT var1 FROM var2 WHERE var3=var4
or something of the sort.
My idea is to fill the vars with user selected items from the web page. I know this can be done in PHP using the Post method, but I'm not using PHP. Also, I've read about the Prepared Statement in Java, but seems only to work when the used after the comparison operator; ex:
SELECT * FROM table Where attr = ? &
Also, I do know i can do the hard coded version of "SELECT " + var1 + "FROM " + var2 + "WHERE attr = " + var3 + " " but that doesn't seem very generic and prone to a lot of errors.
Incase: I'm trying to build this test page using HTML & JSP.
What you are doing with the ? is parameterizing the query. The query can only be parameterized for values not names of tables or columns.
Every time you run a query. The database has to create a query plan. If you are running the same query again and again, you can reduce this overhead by creating a PreparedStatement.
The first execution of PreparedStatement will generate the query plan. The subsequent executions will reuse the same plan.
Same query here means, it is identical in all respects except values used in where clause, expressions etc.
If you change the Column or Table name or modify the structure of the query, then it is a different query and will require a different query plan. A PreparedStement is not useful in this case and you should stick to the hardcoded version you talked about. Because of this reason you will get an error if you try to parameterize Table or Column names in PreparedStement.
Having said that. It is not advisable to take such a generic approach for queries. If your queries are that simple, you can benefit from ORM tools. You would not have to maintain even a line of SQL. For complex queries you have an option of using ORM specific query language or JPQL or Native SQL. Look for JPA + Hibernate
Your specific usage is not permitted by JDBC. You need to hard code the table name when creating the prepared statement. If you really do want to do that I suggest you use String concatenation to create the SQL statements and then create a PreparedStatement with parameters to handle the where part. In case you are wondering why bother with PreparedStatements in the specific solution, it's to avoid SQL injection.
You can use PreparedStatement to achive your objective.
For example -
String query = "SELECT * FROM table Where attr = ?";
PreparedStatement pt = con.prepareStatement(query);
pt.setString(1, attribete);
pt.executeUpdate();
There is no such direct provision in any of SQL packaged classes or others to replace table, column names along with query parameter values, in a query string, using a single method.
You require to depend on both PreparedStatement and any of String methods replace(...) and replaceFirst(...) to achieve your requirement.
String sql = "Select $1, $2 from $3 where $4=? and $5=?";
sql = sql.replaceFirst( "$1", "col1_name" );
sql = sql.replaceFirst( "$2", "col2_name" );
sql = sql.replaceFirst( "$3", "table_name" );
sql = sql.replaceFirst( "$4", "col4_name" );
sql = sql.replaceFirst( "$5", "col5_name" );
// .. and so on
PreparedStatement pst = con.prepareStatement( sql );
// use relevant set methods to set the query parametrs.
pst.setXXX( 1, value_for_first_query_parameter ); // from a variable or literal
pst.setXXX( 2, value_for_second_query_parameter); // from a variable or literal
// ... and so on
If you are using JDBC, can try this
PreparedStatement statement = connection.prepareStatement("SELECT ? FROM ? WHERE ?=? ");
then
statement.setString(1, "column_name");
statement.setString(2, "table_name");
statement.setString(3, "column_name");
statement.setBigDecimal(4, 123);
If you are using other ORM like Hibernate or JPA, I believe there are also ways to do.
Currently i'm writing a JDBC application to manage a MySQL database. I have the delete, insert and select methods functioning with the correct queries. I'm having trouble with the Update method. When using using the following code I receive a MySQL error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "",Street",Town",City",PostCode",Age",email",RunningFee'false'Where PID=" at line 1...
private void updateData()
{
Connection con;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost/snr","root","");
String sql = "Update participant Set password='"+txtpassword.getText()+"'," +
"lastName='"+txtlastName.getText()+"',firstName='"+
txtfirstName.getText()+"',HouseNumber'"+txtHouseNumber.getText()+"',Street'"+txtStreet.getText()+"',Town'"+txtTown.getText()+"',City'"+txtCity.getText()+"',PostCode'"+txtPostCode.getText()+"',Age'"+txtAge.getText()+"',email'"+txtemail.getText()+"',RunningFee'"+cbRunningFee.isSelected()+"' Where PID='"+txtPID.getText()+"'";
Statement statement = con.createStatement();
statement.execute(sql);
createMessageBox("Updated Successfully");
clearControls();
}
catch(Exception e)
{
createMessageBox(e.getMessage());
}
}
Is there something wrong with my SQL query?
Yes, your query is wrong. You're missing = on a great big bunch of set column/value pairs.
(And please consider using prepared statements and bind variables, SQL injection is just not something you want to be open to.)
Yes there is something wrong with the query. Your way of building query is vulnerable to SQL Injection. Use Parameterized Queries instead of concatenating text like that.
Read this article: Preventing SQL Injection in Java
Not only is your query incorrect, but it may also open you to SQL Interjection Attacks.
You need to parameterize your query by replacing the pasted-in values with question marks, preparing the statement, and executing it. See the tutorial that I linked.
Finally, storing a password as plain text is a very, very bad idea.
String sql = "UPDATE participant SET "+
"password=?, lastName=?, firstName=?, HouseNumber=?, Street=?, Town=?, "+
"City=?,PostCode?,Age=?,email=?,RunningFee=? "+
"WHERE PID=?";
PreparedStatement upd = con.prepareStatement(sql);
upd.setString(1, txtpassword.getText());
upd.setString(2, txtlastName.getText());
// ... and so on
upd.executeUpdate();
con.commit();
You are forgetting some = in your query.
Try
String sql = "Update participant Set password='"+txtpassword.getText()+"'," +
"lastName='"+txtlastName.getText()+"',firstName='"+
txtfirstName.getText()+"',HouseNumber='"+txtHouseNumber.getText()+"',Street='"+
txtStreet.getText()+"',Town='"+txtTown.getText()+"',City='"+txtCity.getText()+
"',PostCode='"+txtPostCode.getText()+"',Age='"+txtAge.getText()+"',email='"+
txtemail.getText()+"',RunningFee='"+cbRunningFee.isSelected()+
"' Where PID='"+txtPID.getText()+"'";
The error 'you have an error in your SQL syntax' is from the sql server and indicates that yes, you do have an error in your query. In these cases I often find it useful to print the constructed query itself, just to check that it is being constructed correctly.
In your case I believe the problem is that you are missing a bunch of "="s, you also probably need to escape your single quotes in the java so they are passed through correctly (replace ' with \').
Following on from one of my previous questions to do with method design I was advised to implemented my SQL queries as a parameterized query as opposed to a simple string.
I've never used parameterized queries before so I decided to start with something simple, take the following Select statement:
String select = "SELECT * FROM ? ";
PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "person");
This gives me the following error: "[SQLITE_ERROR] SQL error or missing database (near "?": syntax error)"
I then tried a modified version which has additional criteria;
String select = "SELECT id FROM person WHERE name = ? ";
PreparedStatement ps = connection.prepareStatement(select);
ps.setString(1, "Yui");
This version works fine, in the my first example am I missing the point of parameterized queries or am I constructing them incorrectly?
Thanks!
Simply put, SQL binds can't bind tables, only where clause values. There are some under-the-hood technical reasons for this related to "compiling" prepared SQL statements. In general, parameterized queries was designed to make SQL more secure by preventing SQL injection and it had a side benefit of making queries more "modular" as well but not to the extent of being able to dynamically set a table name (since it's assumed you already know what the table is going to be).
If you want all rows from PERSON table, here is what you should do:
String select = "SELECT * FROM person";
PreparedStatement ps = connection.prepareStatement(select);
Variable binding does not dynamically bind table names as others mentioned above.
If you have the table name coming in to your method as a variable, you may construct the whole query as below:
String select = "SELECT * FROM " + varTableName;
PreparedStatement ps = connection.prepareStatement(select);
Parameterized queries are for querying field names - not the table name!
Prepared statements are still SQL and need to be constructed with the appropriate where clause; i.e. where x = y. One of their advantages is they are parsed by the RDMS when first seen, rather than every time they are sent, which speeds up subsequent executions of the same query with different bind values.