Search code examples
javamysqlsql-injection

Vulnerable to SQL Injection?


I'm currently creating a Java application which uses MySQL.

I have read that in certain situations you should use a prepared statement to prevent SQL injection.

By now I don't use prepared statements and I'm actually a bit worried that my Code might be vulnerable to SQL injection.


Situations where MySQL queries are executed:

  • Direct query from inside the application(all variables used are defined in the application)
  • API call (another application makes a MySQL query --> All variables used are defined inside the application which makes the call)

MySQL code:

    public static void Update(final String qry) {

        try {
            Statement stnt = connection.createStatement();
            stnt.executeUpdate(qry);

        } catch (SQLException e) {
            e.printStackTrace();
        }

}

public static ResultSet Query(String qry) {
    final ResultSet rs;

        try {
            Statement stnt = connection.createStatement();
            rs = stnt.executeQuery(qry);
        } catch (Exception e) {
            e.printStackTrace();
        }

    return rs;
}

Solution

  • Depending on other factors, your application may remain vulnerable to SQL injection attack from someone with access to your application's environment.

    For example, if the variables defined inside your code obtain their values from a configuration file, and later become part of SQL query, an attacker with access to your configuration files can execute a SQL injection attack by altering the content of your configuration file. Same goes for the other application: if there is a way to alter the content of the variables that go into the construction of your SQL query, it is likely possible to execute a successful SQL injection attack.

    Using prepared statements provides catch-all defense against injection. The added complexity is well worth the trouble, though, because you plug a huge security hole with a relatively straightforward fix.