Skip to content

Commit

Permalink
FINERACT-1893: Run reports fix
Browse files Browse the repository at this point in the history
  • Loading branch information
vidakovic committed Jan 6, 2024
1 parent e4944c4 commit aec6cbe
Showing 1 changed file with 17 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,16 @@ private SQLInjectionValidator() {

private static final String SQL_PATTERN = "[a-zA-Z_=,\\-:'!><.?\"`% ()0-9*\n\r]*";

// TODO: see here https://rails-sqli.org for and
// https://larrysteinle.com/2011/02/20/use-regular-expressions-to-detect-sql-code-injection more examples
private static final List<String> INJECTION_PATTERNS = List.of("(?i).*[or|and]\s*[\"']?-1[\"']?\\s*(-*).*",
"(?i).*\\s+[\"']?(\\d+)[\"']?\\s*=\\s*[\"']?(\\1)[\"']?\\s*(-*).*");

public static void validateSQLInput(final String sqlSearch) {
if (StringUtils.isBlank(sqlSearch)) {
return;
}

String lowerCaseSQL = sqlSearch.toLowerCase();
List<String[]> commandsList = List.of(DDL_COMMANDS, DML_COMMANDS, COMMENTS);
validateSQLCommands(lowerCaseSQL, commandsList, String::contains);
Expand All @@ -53,6 +59,7 @@ public static void validateAdhocQuery(final String sqlSearch) {
if (StringUtils.isBlank(sqlSearch)) {
return;
}

String lowerCaseSQL = sqlSearch.toLowerCase().trim();
validateSQLCommand(lowerCaseSQL, DDL_COMMANDS, String::startsWith);
validateSQLCommand(lowerCaseSQL, COMMENTS, String::contains);
Expand Down Expand Up @@ -80,16 +87,8 @@ private static void patternMatchSqlInjection(String sqlSearch, String lowerCaseS
// Removing the space before and after '=' operator
// String s = " \" OR 1 = 1"; For the cases like this
boolean injectionFound = false;
String inputSqlString = lowerCaseSQL;
while (inputSqlString.indexOf(" =") > 0) { // Don't remove space before
// = operator
inputSqlString = inputSqlString.replaceAll(" =", "=");
}

while (inputSqlString.indexOf("= ") > 0) { // Don't remove space after =
// operator
inputSqlString = inputSqlString.replaceAll("= ", "=");
}
String inputSqlString = lowerCaseSQL.replaceAll("\\s*=\\s*", "=");

StringTokenizer tokenizer = new StringTokenizer(inputSqlString, " ");
while (tokenizer.hasMoreTokens()) {
Expand Down Expand Up @@ -131,10 +130,19 @@ private static void patternMatchSqlInjection(String sqlSearch, String lowerCaseS
}
}
}

if (injectionFound) {
throw new SQLInjectionException();
}

for (String injectionPattern : INJECTION_PATTERNS) {
Pattern pattern = Pattern.compile(injectionPattern);
Matcher matcher = pattern.matcher(sqlSearch);
if (matcher.matches()) {
throw new SQLInjectionException();
}
}

Pattern pattern = Pattern.compile(SQL_PATTERN);
Matcher matcher = pattern.matcher(sqlSearch);
if (!matcher.matches()) {
Expand Down

0 comments on commit aec6cbe

Please sign in to comment.