I have to process raw sql user input with Laravel. I've backed them up as follows:
$query = DB::table('table_name');
function escapeString($str) {
return DB::connection()->getPdo()->quote($str);
}
$column = escapeString($rule['query']['operand']);
$value = escapeString($rule['query']['value']);
if(in_array($rule['query']['operator'], $query->operators)) {
return $column . ' ' . $rule['query']['operator'] . ' ' . $value;
}
Is that enough, or can I still be attacked over it?
I read:
- https://stackoverflow.com/questions/18951057/escape-raw-sql-queries-in-laravel-4 - recommend it
- https://www.php.net/manual/de/pdo.quote.php - they do not recommend it, but it seems possible
(This question was postet originaly at https://stackoverflow.com/questions/63091979/is-my-code-protected-against-sql-injection, but STA suggest to post this question here again)
Update:
I figured out, how to use value
in variable binding. Also I changed escapeString
to
$column = preg_replace('/[^a-zA-Z_]/', '', $rule['query']['operand']);
Thats fine for alle columns names and I am pretty sure that this is safe. This filtering approch ist also used in https://stackoverflow.com/questions/10080850/using-a-whitelist-on-user-input