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

26

u/seanprefect Grumpy Guy Who Remembers Java 2 Apr 12 '21

5

u/fabiopires10 Apr 12 '21

I can't because column name, column type,etc can't be parameterized or else PreparedStatement puts ' ' on it

1

u/msx Apr 13 '21

you could use a regular expression that matches allowed identifier for your database implementation. usually something like AZaz09_