我的老师和我正在讨论是否可以将SQL注入准备好的语句。我明白通常你不能,但教授坚持使用sql连接而不是使用(?)。
现在我试图打破我的代码,但我没有运气。
public Users getUserByUsername(String username) throws SQLException {
StringBuffer sql = new StringBuffer();
sql.append("select * from users as u, user_type_lookup as l, user_types as t ");
sql.append("where u.users_id=l.user_id and l.type_id=t.user_types_id and u.username='");
sql.append(username);
sql.append("';");
System.out.println(sql.toString());
PreparedStatement ps = conn.prepareStatement(sql.toString());
ResultSet rs = ps.executeQuery(sql.toString());
if (!rs.next()) {
return null;
}
String password = rs.getString("password");
String type = rs.getString("description");
int id = rs.getInt("users_id");
int incorrect_logins = rs.getInt("incorrect_logins");
Time wait_time = rs.getTime("wait_time");
Users u = new Users(id, username, password, type, incorrect_logins,
wait_time);
return u;
}
我试过的插入内容:
string: '; DELETE FROM users WHERE 1 or users_id = '
string: ';delete from users where username<>'
//The only one that worked
string: stan' or 'a'<>'b
SQL输出(导致java错误):
select * from users as u, user_type_lookup as l, user_types as t where u.users_id=l.user_id and l.type_id=t.user_types_id and u.username=''; DELETE FROM users WHERE 1 or users_id = '';
SQL输出(按预期工作):
select * from users as u, user_type_lookup as l, user_types as t where u.users_id=l.user_id and l.type_id=t.user_types_id and u.username='stan';
错误讯息:
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 'DELETE FROM users WHERE 1 or users_id = ''' at line 1
服务器:Tomcat 7
数据库:MySQL
IDE:Eclipse
语言:Java
所以请帮我破解我的代码!
答案 0 :(得分:4)
您不能在prepared-statement的SQL中添加单独的语句,但可以将其分解,例如:
' OR 'x' = 'x
作为用户名(以便查询将跨所有用户进行笛卡尔联接并在它们之间键入类型);如果users
和user_type_lookup
是大型表,这将极大地损害性能,并且将是拒绝服务攻击的良好开端。' OR (SELECT stored_procedure_that_deletes_things()) = 1
(以便查询将调用具有有害影响的存储过程)。