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

25

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

if your database is designed in such a way as the end users have to know your column names then i'm afraid you've got bigger fish to fry.

3

u/fabiopires10 Apr 12 '21 edited Apr 12 '21

The objective of the class is to run migrations , so the table and column names need to be known

0

u/denisfalqueto Apr 13 '21

As I understand it, your migrations are not written by users, right? If so, you will not have to worry about sql injections in this front. You only have possibility of sql injections if a user input is used by some sql statement directly without sanitation.