How should I sanitize database input in Java?

前端 未结 5 2151
我在风中等你
我在风中等你 2020-12-31 07:10

Could someone please point me to a good beginner guide on safely running SQL queries formed partly from user input? I\'m using Java, but a language neutral guide is fine to

相关标签:
5条回答
  • 2020-12-31 07:25

    Your user input would actually have to be "Bob'; delete from foo; select '" (or something like that) so the implicit quotes added by the prepared statement would be closed:

    SELECT * FROM FOO WHERE NAME = 'Bob'; delete from foo; select ''
    

    but if you do that the prepared statement code will quote your quote so you get an actual query of

    SELECT * FROM FOO WHERE NAME = 'Bob''; delete from foo; select '''
    

    and your name would be stored as "Bob', delete from foo; select '" instead of running multiple queries.

    0 讨论(0)
  • 2020-12-31 07:29

    PreparedStatement? Yes, absolutely. But I think there's one more step: validation of input from UI and binding to objects prior to getting close to the database.

    I can see where binding a String in PreparedStatement might still leave you vulnerable to a SQL injection attack:

    String userInput = "Bob; DELETE FROM FOO";
    String query = "SELECT * FROM FOO WHERE NAME = ?";
    
    PreparedStatement ps = connection.prepareStatement(query);
    ps.setString(1, userInput);
    ps.executeQuery();
    

    I've gotta admit that I haven't tried it myself, but if this is remotely possible I'd say PreparedStatement is necessary but not sufficient. Validating and binding on the server side is key.

    I'd recommend doing it with Spring's binding API.

    0 讨论(0)
  • 2020-12-31 07:30

    You definitely want to use PreparedStatements. They are convenient. Here is an example.

    0 讨论(0)
  • 2020-12-31 07:36

    Normally, you shouldn't create a query concatenating input, but using PreparedStatement instead.

    That lets you specify in which places you'll be setting your parameters inside your query, so Java will take care of sanitizing all inputs for you.

    0 讨论(0)
  • 2020-12-31 07:44

    Use PreparedStatement instead of Statement

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