12 Class.forName("com.mysql.cj.jdbc.Driver");
13 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm", "root", "root");
14 Statement stmt = con.createStatement();
15 return stmt.executeQuery(query);16
17 } catch (Exception e) {
18 return null;
42 Class.forName("com.mysql.cj.jdbc.Driver");
43 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm", "root", "root");
44 Statement stmt = con.createStatement();
45 ResultSet rs = stmt.executeQuery(query);46 while (rs.next()) {
47 temp = rs.getString(label);
48 }
It is not a good idea to use a dynamically generated string (such as a string created with concatenation, or a request parameter) to execute an sql query.
This issue will be raised when code that is commonly vulnerable to injection attacks, such as request processing code appears to be using possibly unsanitized data to create an SQL query through methods such as Statement.addBatch()
or Statement.execute()
.
String user = request.getParameter("user");
String pass = request.getParameter("pass");
String query = "SELECT * FROM users WHERE user = '" + user + "' AND pass = '" + pass + "'"; // Unsafe
In the example above, user
and pass
are untrusted values which have not been sanitized before use. Consider a case where user
has the value "' OR 1=1 --"
. The query string then becomes:
SELECT * FROM users WHERE user = '' OR 1=1 -- AND pass = '...'
Here, --
is the SQL comment token and turns the rest of the line after it into a comment. This line is now equivalent to:
SELECT * FROM users WHERE 1=1
Since 1=1
will always evaluate to a true value, it will not be necessary to check for the value of user
, leading to the final form of the statement:
SELECT * FROM users
This is clearly not a statement that can be safely executed in production, and would likely become an important step in an attacker's chain of exploitation.
There are a number of solutions to this issue:
Here is an example of using a prepared statement to write the same query:
String user = request.getParameter("user");
String pass = request.getParameter("pass");
String query = "SELECT * FROM users WHERE user = ? AND pass = ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, user); // Will be properly escaped
statement.setString(2, pass);
// Execute and use the returned ResultSet as required.