简体   繁体   中英

Java SQL Injection - MySQLSyntaxErrorException

I am attempting to SQL inject one of my applications for a write up that I need to do for a project.

I have used the following statement:

Statement statement = conn.createStatement();
String insertTableSQL = "INSERT INTO activity (activity_name, user_id, category_id, started, completed) VALUES ('" + activityForm.getName() + "', '" + user.getId() + "', '" + category.getId() + "', '" + 0 + "', '" + 0 + "')";
System.out.println(insertTableSQL);
statement.executeUpdate(insertTableSQL);

When I then put the following into one of my form inputs (in this case the activity name input):

ActivityName'); DROP TABLE STUDENTS; --

I get the following error:

INSERT INTO activity (activity_name, patient_id, category_id, started, completed) VALUES ('ActivityName'); DROP TABLE STUDENTS; --', '1', '1', '0', '0')
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'DROP TABLE STUDENTS; --', '1', '1', '0', '0')' at line 1

I cannot seem to find a way to avoid this error so I hope someone has some ideas.

I am guessing the error is occuring because of the way Statement in java works and the rest of the query being parsed.

Thanks

EDIT: I know that I should use prepared statements, I do. My application uses ORM with JPA. For university, I am just testing how SQL injection works.

By default, the MySQL JDBC driver does not allow one execute to run multiple SQL statements. This means the type of SQL injection test you show cannot execute. This is a good thing!

You'd have to explicitly allow multi-query when you connect to your JDBC data source, by putting allowMultiQueries=true in the JDBC URL.

See also Multiple queries executed in java in single statement

There are other types of SQL injections that don't run additional statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM