Search code examples
javasqljdbcsql-injectionjdbctemplate

Java enum values and SQL injection


I have the following enum:

public enum AccountStatus {

    ENABLED,
    CONFIRMATION_PENDING,
    EXPIRED,
    LOCKED,
    DISABLED,
    CREDENTIALS_EXPIRED,
}

That I'm binding to checkboxes in a JSP form:

<li><form:checkbox path="accountStatus" value="ENABLED" label="Enabled" /></li>
<li><form:checkbox path="accountStatus" value="CONFIRMATION_PENDING" label="Confirmation Pending" /></li>
...
<li><form:checkbox path="accountStatus" value="CREDENTIALS_EXPIRED" label="Credentials Expired" /></li>

In my controller when I get the selected checkbox values I convert the String to an Enum as follows:

AccountStatus accountStatus = AccountStatus.valueOf("selected string here");

Then in my DAO (using Spring JdbcTemplate) I query my database using the selected values:

String SQL = "SELECT * FROM TABLE_A WHERE column = \'" + accountStatus.name() + "\'";

jdbcTemplate.query(SQL, new MyMapper());

Since I'm validating each user selected checkbox by using AccountStatus.valueOf(...), is this way of doing safe from SQL injection?


Solution

  • You don't have any danger of somebody injecting arbitrary SQL for how you're showing this enum value getting set. An attacker could send an invalid enum name but valueOf would throw an IllegalArgumentException when it couldn't match it to a valid value.

    If there was some reason a valid enum value shouldn't be entered (for instance, a particular role doesn't have privileges to look up entries with a DISABLED value) then in the absence of other server-side validation the attacker could change the entry to that valid-but-not-permitted value. So that would be a possible attack, which you could remediate by adding more validation (in my example, checking that the enum value is permitted for the user's roles).

    It would improve the legibility of this SQL to rewrite it to use parameters (preferably named parameters). Also this will keep showing up in every code review, static code analysis, and code audit, and I would be annoyed to have to keep answering questions about it. But I understand wanting to avoid touching something complex that is working.