r/javahelp • u/fabiopires10 • 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
1
u/HotRodLincoln Apr 12 '21 edited Apr 12 '21
Well, that's only sort of a java question, but does your database server and your java server recognize all the same whitespace as breaks? I mean not just spaces, but new lines, and any unicode bullshit like "Thin Space".
I have a feeling something very wrong is happening here, but you're likely going to find yourself finding the "good characters" and filtering based on being in that set.
From an Americentric view, that probably means filtering out A-Za-z0-9.
You'll probably find yourself slumming in the unicode spec trying to figure out accents and a bunch of other stuff if you need to add other languages or Asian languages.
Depending on the requirements exactly, it may make sense for a human to look at the column names either once per table or per column before adding them.
Also, just for thought: