SQL injection High

User-provided inputs must be sanitized before being used to generate a SQL database query. An untrusted input can be intentionally built by an attacker in order to run unwanted query statements, possibly allowing the attacker to read, modify, or delete database content.

Detector ID
java/sql-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public void executeSqlStatementNoncompliant(HttpServletRequest request, java.sql.Connection connection) {
2    final String favoriteColor = request.getParameter("favoriteColor");
3    try {
4        String sql = "SELECT * FROM people WHERE favorite_color='" + favoriteColor + "'";
5        java.sql.Statement statement = connection.createStatement();
6        // Noncompliant: user-given input is not sanitized before use.
7        statement.execute(sql);
8    } catch (java.sql.SQLException e) {
9        throw new RuntimeException(e);
10    }
11}

Compliant example

1public void executeSqlStatementCompliant(HttpServletRequest request, java.sql.Connection connection) {
2    final String favoriteColor = request.getParameter("favoriteColor");
3    // Compliant: user-given input is sanitized before use.
4    if (!favoriteColor.matches("[a-z]+")) {
5        throw new IllegalArgumentException();
6    }
7    try {
8        String sql = "SELECT * FROM people WHERE favorite_color='" + favoriteColor + "'";
9        java.sql.Statement statement = connection.createStatement();
10        statement.execute(sql);
11    } catch (java.sql.SQLException e) {
12        throw new RuntimeException(e);
13    }
14}