SQL injection

Separate input values from SQL syntax with parameter binding

Description

Inserting external input into SQL text can change a query’s conditions or operation. Preparing the statement after concatenation still leaves that input in the SQL.

Potential impact

Access checks may be bypassed and data exposed, changed or deleted. Operating-system command execution requires database features and privileges that allow it.

Remediation

Bind values with PreparedStatement or JdbcTemplate. Use binding for SQL, JPQL and HQL in an ORM as well. Choose table names, column names and sort directions from a server-side allow-list. Validate input format and length, and limit database privileges.

Examples

The excerpts look up user records. A login flow must also verify the password, and the application must check permission to read the records.

Before

java
String query = "SELECT id, username FROM users WHERE username = '" + username + "'";
jdbcTemplate.queryForList(query);

After

java
String query = "SELECT id, username FROM users WHERE username = ?";
jdbcTemplate.queryForList(query, username);

queryForList() receives username as the value for ?.

Related CVEs

References