How does a PreparedStatement avoid or prevent SQL injection?

前端 未结 10 1840
再見小時候
再見小時候 2020-11-22 05:21

I know that PreparedStatements avoid/prevent SQL Injection. How does it do that? Will the final form query that is constructed using PreparedStatements will be a string or o

相关标签:
10条回答
  • 2020-11-22 05:42

    As explained in this post, the PreparedStatement alone does not help you if you are still concatenating Strings.

    For instance, one rogue attacker can still do the following:

    • call a sleep function so that all your database connections will be busy, therefore making your application unavailable
    • extracting sensitive data from the DB
    • bypassing the user authentication

    Not only SQL, but even JPQL or HQL can be compromised if you are not using bind parameters.

    Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose:

    • JPA Criteria API
    • jOOQ
    0 讨论(0)
  • 2020-11-22 05:45

    Consider two ways of doing the same thing:

    PreparedStatement stmt = conn.createStatement("INSERT INTO students VALUES('" + user + "')");
    stmt.execute();
    

    Or

    PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
    stmt.setString(1, user);
    stmt.execute();
    

    If "user" came from user input and the user input was

    Robert'); DROP TABLE students; --
    

    Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.

    0 讨论(0)
  • 2020-11-22 05:48

    PreparedStatement:

    1) Precompilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.

    2) Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the value.

    0 讨论(0)
  • 2020-11-22 05:51

    The problem with SQL injection is, that a user input is used as part of the SQL statement. By using prepared statements you can force the user input to be handled as the content of a parameter (and not as a part of the SQL command).

    But if you don't use the user input as a parameter for your prepared statement but instead build your SQL command by joining strings together, you are still vulnerable to SQL injections even when using prepared statements.

    0 讨论(0)
提交回复
热议问题