SQL injection on PostgreSQL - java

My clienet(android) sends user details in the user form and my servlet just enters those details into to the database(postgre sql). I tried to give to do a sql injection attack by giving ;DELETE FROM tbl_name; in the username field.
But postgresql just treats it as a value and enters it as the username. How do I do the SQLINjection attack. (I have not done any sort of checking in the postgre sql or the servlet).Does it mean that postgresql is SQLInjection attack resistant?
I am using the following statements to insert the data:
String insert ="insert into userdetail(username,id,sno) values('"+username+"','"+userid+"','"+no+"')";
Statement stmt = conn.createStatement();
stmt.executeUpdate(insert);
The username contains ;DELETE FROM userdetail;.
I have tried the following also:
');DELETE FROM userdetail;
But it fives the following error:
org.postgresql.util.PSQLException: ERROR: unterminat
ed quoted string at or near "');"
Position: 1
I have also tried this:
','',');DELETE FROM userdetail;
This gives the following error:
17:36:46,828 INFO [STDOUT] org.postgresql.util.PSQLException: ERROR: unterminat
ed quoted string at or near "''');"
Position: 38
but does not delete the records of the table. How do I make it delete the tables records?

The key trick is that the complete statement string must
do something innovative
be still valid SQL
So far the answers have omitted the second part. But an invalid SQL statement will abort the transaction and hence most likely does nothing at all. If you set autoCommit to true that attack may be easier.
But this string should to the trick in a "clean" way:
foo', '42', '42'); delete from userdetail; --
Note: The resulting string is this (line breaks only for better reading):
insert into userdetail(username,id,sno) values('foo', '42', '42');
delete from userdetail;
-- ','21','21')
Both the INSERT part is complete and correct (assuming no unique index collisions of course) and also the DELETE is correct. The potentially offending rest is masked by the trailing SQL comment --.

hat type of attack that you are describing - even if you get the use of single quotes "correct" - will not work with PostgreSQL
It does not work because the JDBC driver does not allow to run more than one statement in a single Statement.execute() call.
It will throw an error ("invalid character" pointing to the ;)
(Sorry, this is only true for Oracle)
There are other scenarios that would work with a badly written application.
Assuming the application is checking the username/password like this (note that this is a very simplified example!)
String sql = "SELECT count(*) FROM users WHERE username = '";
sql += username;
sql += "' AND password = '";
sql += pwd;
sql += "'"
then a possible attack could be to enter the value:
' or 1=1 or '' = '
into the password field.
This would wind up with the following generated SQL
SELECT count(*) FROM users WHERE username = 'arthur'
AND password = '' or 1=1 or ''=''
Which would always be true and one could login without a password.

Try ', '', '');DELETE FROM tbl_name; to delete your table.
In simplest case, you can give ' as user name and your server should give you an error.
Besides, there is no SQL injection resistant database because SQL injection happens because of poorly coded server-side (CGI) script and not because of database weaknesses.

Related

ExecuteUpdate with possible single quotes

I have the following code:
sql = update [myTable] set content = '" map.getString() + "' where id = " map.getKey();
stmt.executeUpdate(sql);
This is running in a loop, and map.getString() can return a string with single or double quotes in them. I've tried escaping it with multiple quotes around map.getString() (for example
sql = update [myTable] set content = ''" map.getString() + "'' where id = " map.getKey();
But with no luck.
How can I get it to update the content column with the literal value of map.getString()?
Sample error I receive is: (there are many similar ones)
java.sql.SQLException: Incorrect syntax near 's'.
or
java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ''' not found.
Avoid using concatenate strings of parameter values for building your request:
it is not safe (possible sql injection)
it is not optimized (as the db engine will have always to parse the request even if always the same string is sent to the db)
it will generated lot of bad conversion error (special character etc)
Prefer using PreparedStatement with bind parameters.
Example:
PreparedStatement stmt = connection.prepareStatement("UPDATE mytable SET content = ? WHERE id = ?");
stmt.setString(1, map.getString());
stmt.setInt(2,map.getKey());
stmt.executeUpdate();
Using bind parameters will avoid conversion mistakes and syntax error you are encountering
Use a PreparedStatement. See http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html . They are precomiled, and thus more amenable for executing in loops as well as handling content containing characters which otherwise require special handling.

"UcanaccessSQLException: unexpected token" when column name contains apostrophe

I am converting an existing program from JDBC-ODBC Bridge to UCanAccess. It has been working for years. The Java program writes to an MDB file. After conversion, one Insert command stopped working.
It throws "net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: [".
After some experimentation I determined that the problem is caused by three columns that include apostrophes in their names. Example: [Sched'd PO Place Date]. Apparently JDBC-ODBC Bridge did not care but UCanAccess does.
I am somewhat trapped with the existing MDB structure or I'd simply rename the fields. But there is no telling how many downstream reports could be broken if I did that. The MDB is used for Ad Hoc reporting.
Here is a simplified SQL Select version of the problem. It throws the same error as the Insert.
String cJD = "net.ucanaccess.jdbc.UcanaccessDriver";
String cS = "jdbc:ucanaccess://C:/MosAll/mosall.mdb";
String uid = "";
String pw = "";
String sql4 = "select [Sched'd PO Place Date] from [Tier 1] ";
Class.forName(cJD);
Connection con = DriverManager.getConnection(cS, uid, pw);
PreparedStatement pstmt4;
pstmt4 = con.prepareStatement(sql4);
pstmt4.execute();
Is there a way to "escape" the apostrophes or reconfigure ucanaccess so that the driver can execute them?
This issue has been fixed in UCanAccess 2.0.9.4.
Previous answer:
I have been able to recreate the issue with UCanAccess version 2.0.9.3.
select [Sched'd PO Place Date] ...
fails, but for now simply omitting the '
select [Schedd PO Place Date] ...
works okay. Interestingly, using backticks instead of square brackets
select `Sched'd PO Place Date` ...
also produces the exception
net.ucanaccess.jdbc.UcanaccessSQLException: unexpected token: [
With luck this will get fixed in a future release of UCanAccess.
have you tried table, columns names between `` (they not apostrophe but the one next to ~), the \' may work, and finally the JDBC standard way is to define the escape character at the end of the query:
String sql4 = "select [Sched\'d PO Place Date] from [Tier 1] { escape '\'}"
You may want to try the one above also with ``instead of []
Finally, your last resource is "select *" and extract the right column yourself

SQL Injection and possible attacks

Hi I have the following query which is part of a java class. I just want to know what are the possible attacks possible with the SQL Injection. How an attacker can inject queries? What are sample queries in this case that can be used to gain access to the database?
String query = ("SELECT username, password, admin FROM users
WHERE " + "username='" + username + "' AND password='" +
password + "'");
ResultSet rs = st.executeQuery(query);
// Entry in the result set means the query was successful and
//the user is a valid user
if (rs.next()) {
username = rs.getString(1);
isAdmin = rs.getBoolean(3);
I think this is a possible way of attack also by putting username as abc';# since anything after # will be considered as a comment in SQL. What others think about it?
I want to know what the attacker will be entering in the username box and password box of the HTML page to gain access as an administrator. Assuming the job of the above java class is to process the request of the users's input from a HTML page by querying a database.
basically it works like this https://xkcd.com/327/
what I do is assuming, that everything a user inputs is a threat, so I would save everything to variables like usUsername, where "us" means unsafe.
After that I check every "us"-variable for injections, what results in sUsername (s means safe). So when I build a query I can only use s-varaibles and should be safe in most cases.
This idea is totally taken from here: http://www.joelonsoftware.com/articles/Wrong.html
Based on this code you could do ANYTHING you want by manipulating the values of the username or password text sent to the query.
The only constraint is the level of permission of the user account executing the query. If it was a sysadmin, you could delete everything. If it's SQL Server and xp_cmdshell is enabled, you could format the hard drive of the SQL server.
SQL Injection is one of those things where if you can do something you can pretty much do anything.
Look into the Havij tool, that is a security research tool that can demonstrate the power of SQLi.
You can not do that. username and password can be replaced by anything leading to all types of queries. You must use a prepared statement to provide username and password
Entering the following values for password would add a row to the result set containing the values 'admin', 'dummy', 1 for username, password, and admin, respectively:
' AND 1=0 UNION SELECT 'admin', 'dummy', admin FROM users WHERE admin = 1 AND '1'='1
The resulting query would look like:
SELECT username, password, admin FROM users
WHERE username='dummy' AND password='' AND 1=0 UNION SELECT 'admin', 'dummy', admin FROM users WHERE admin = 1 AND '1'='1'
The first SELECT would return no result as 1=0 is false for each record. But the second, injected SELECT would return all records where admin=1 is true and replaces the original values for username and password with admin and dummy, respectively.
You should use prepared statements and pass the values as parameters on execution.

Intermittently getting "sqlexception invalid column index" [duplicate]

I got the following error while testing some code:
SQLException: Invalid column index
What exactly does that mean?
Is there an online document explaining what all the Oracle error codes and statements?
If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.
For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.
It sounds like you're trying to SELECT a column that doesn't exist.
Perhaps you're trying to ORDER BY a column that doesn't exist?
Any typos in your SQL statement?
Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:
String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);
I had an argument to queryForList that didn't correspond to a question mark in the SQL. The first line should have been:
String sqlString = "select pwy_code from approver where university_id = ?";
I also got this type error, problem is wrong usage of parameters to statement like, Let's say you have a query like this
SELECT * FROM EMPLOYE E WHERE E.ID = ?
and for the preparedStatement object (JDBC) if you set the parameters like
preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)
then it results in SQLException: Invalid column index
So, I removed that second parameter setting to prepared statement then problem solved
Just try this fix, as I faced your error:
Remove the single quotation marks around your question mark, which means, if you used your reserved parameters like ('?','?','?') you should make it look like this:
(?,?,?)
I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
the final sql statement is something like:
select col_1 from table_X where col_2 = 'abcd';
i run this inside my SQL IDE and everything is ok.
Next, i try to build this statement with java:
String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index
Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.
i just removed the characters that appear on white background
"select col_1 from table_X where col_2 = ' ? ' ; ";
to obtain
"select col_1 from table_X where col_2 = ?";
(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)
I had this problem in one legacy application that create prepared statement dynamically.
String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());
when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.

What does the following Oracle error mean: invalid column index

I got the following error while testing some code:
SQLException: Invalid column index
What exactly does that mean?
Is there an online document explaining what all the Oracle error codes and statements?
If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.
For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.
It sounds like you're trying to SELECT a column that doesn't exist.
Perhaps you're trying to ORDER BY a column that doesn't exist?
Any typos in your SQL statement?
Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:
String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);
I had an argument to queryForList that didn't correspond to a question mark in the SQL. The first line should have been:
String sqlString = "select pwy_code from approver where university_id = ?";
I also got this type error, problem is wrong usage of parameters to statement like, Let's say you have a query like this
SELECT * FROM EMPLOYE E WHERE E.ID = ?
and for the preparedStatement object (JDBC) if you set the parameters like
preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)
then it results in SQLException: Invalid column index
So, I removed that second parameter setting to prepared statement then problem solved
Just try this fix, as I faced your error:
Remove the single quotation marks around your question mark, which means, if you used your reserved parameters like ('?','?','?') you should make it look like this:
(?,?,?)
I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
the final sql statement is something like:
select col_1 from table_X where col_2 = 'abcd';
i run this inside my SQL IDE and everything is ok.
Next, i try to build this statement with java:
String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index
Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.
i just removed the characters that appear on white background
"select col_1 from table_X where col_2 = ' ? ' ; ";
to obtain
"select col_1 from table_X where col_2 = ?";
(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)
I had this problem in one legacy application that create prepared statement dynamically.
String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());
when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.

Categories

Resources