有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SQL注入和准备好的语句

我的老师和我正在讨论是否可以将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

服务器:Tomcat7

数据库:MySQL

IDE:Eclipse

语言:Java

所以请帮我破解密码


共 (1) 个答案

  1. # 1 楼答案

    您不能在准备好的语句的SQL中添加单独的语句,但可以将其打断,例如:

    • 使用' OR 'x' = 'x作为用户名(这样查询将在所有用户之间进行笛卡尔连接,并在它们之间进行类型映射);如果usersuser_type_lookup是大型表,这将极大地损害性能,这将是拒绝服务攻击的良好开端
    • 使用' OR (SELECT stored_procedure_that_deletes_things()) = 1(以便查询将调用具有有害影响的存储过程)