r/javahelp • • Apr 12 '21

How can I prevent SQL injection?

I have to concatenate the SQL expression because some variable values come from a XML file so that leaves me open to SQL injection. I was thinking of verifiying if the value of the variables is only a single word(if the value doesn't have spaces). Would it be viable?

@Override
    public void execute(Database database) throws CustomChangeException {

        try {
            //check if there are any errors in the changelog file
            checkArgumentsNumber();

            boolean tablesFound = false;
            boolean columnsAdded = false;
            String sqlStatement = "ALTER TABLE NAME ADD COLUMN " +this.getColumnName()+" "+this.getColumnType();

            if(notNull){
                sqlStatement+=" NOT NULL";
            }

            if(defaultValue!=null){
                sqlStatement+=" DEFAULT ?";
            }

            if (this.after != null) {
                sqlStatement += " AFTER " +this.after;
            }

            System.out.println("The statement is: "+sqlStatement);

            //get tables in the database
            JdbcConnection connection = (JdbcConnection) database.getConnection();
            DatabaseMetaData metadata;
            metadata = connection.getMetaData();
            String[] types = {"TABLE"};
            ResultSet rs = metadata.getTables(connection.getCatalog(), null, "%", types);

            //if the user chose to use a regex
            if (this.getRegex() != null) {
                Pattern pattern = Pattern.compile(this.getRegex());

                while (rs.next()) {
                    String tableName = rs.getString(3);
                    Matcher matcher = pattern.matcher(tableName);
                    boolean matches = matcher.matches();
                    if (matches) {
                        tablesFound = true;
                        String addStatement=sqlStatement.replaceAll("NAME",tableName);
                        PreparedStatement s = connection.prepareStatement(addStatement);
                        if (!checkColumnsExists(s, tableName)) {
                            if(this.defaultValue!=null){
                                s.setString(1,this.defaultValue);
                            }
                            System.out.println("REGEX:"+s.toString());
                            s.executeUpdate();
                            columnsAdded = true;
                        }
                    }
                }
            }

            checkInvalidInfo(tablesFound, columnsAdded, "All the matching tables already had that column");
        } catch (InvalidArgumentsNumberException | SQLException | InvalidInfoException | DatabaseException e) {
            throw new CustomChangeException("Error enabling trigger: " + e);
        }
    }
20 Upvotes

20 comments sorted by

View all comments

3

u/Uncle_DirtNap Extreme Brewer Apr 13 '21

There's no platform that allows you to parameterize elements of DDL statements like this. If you don't care about fully supporting your platform's allowances for special characters in object names, you can do some trivial parsing to make sure that there aren't unexpected special characters, but that won't help you if you support the operations that would be injected, and your XML file base is a compromise vector.

Think about little bobby tables... Your concern in that a case like that is someone will introduce or modify an XML file that's supposed to look something like:

<change><operation>add</operation><tabName>fun_table</tabName><colName>new_column</colname></change>

to something like:

<change><operation>add</operation><tabName>fun_table</tabName><colName>new_column; ALTER TABLE important_table DROP money_column;</colname></change>

but it seems like your system would be open to the more effective exploit of changing:

<change><operation>drop</operation><tabName>fun_table</tabName><colName>legacy_column</colname></change>

to:

<change><operation>drop</operation><tabName>important_table</tabName><colName>money_column</colname></change>

at which point it's not really about the syntax, it's about the meaning of the objects.

If I had to do this, I would do this using a dry-run database, and ideally pass the diff in front of a human or some other validation process.