Am I safe against SQL injection Am I safe against SQL injection postgresql postgresql

Am I safe against SQL injection


In terms of your procedure you seem safe as the variable in the SP won't be expanded into code, but you can still expose yourself if you don't use a parameterized query like "SELECT * FROM sp_list_name(?);" in your appplication code. Something like "SELECT * FROM sp_list_name('$start_name');" could be subverted by a user passing a start name of "');delete from t_player where last_name NOT IN ('". So use a parameterized query or sanity check your inputs in your program.

NB: To others, please note that a variable in a stored procedure will not expand into code even if it contains a ' or ;, (excluding passing it to EXECUTE, for which you would use quote_literal, not hand-rolled replace functions) so replacing ; or ' is totally unnecessary (in the stored procedure, the application using it is a different story, of course) and would prevent you from always finding the "tl;dr" or "O'Grady" teams.

Leo Moore, Karl, LFSR Consulting: v_temp_name in the stored procedure will NOT be expanded into code in the SP (no EXECUTE), the check would need to be done n the application, not the SP (or the OP could just use a parameterized query in their app code, instead). What others are suggesting is similar to worrying about

my $bar = "foo; unlink('/etc/password');"; my $baz = $bar;

actually running the unlink in the absence of an eval.


Rule #1 to prevent against sql injection: Sanitize all input that is coming from someone/something you cannot trust/have no control over.

The problem itself does not lie within the database code, but from the application that is executing those statements.


The proper way to protect against SQL Injection is via White Listing* - the long and short is set the characters that you're going to accept and filter them out.

The incorrect way is to Black List - Black listing what characters aren't accepted is going to lead to trouble, because you can't keep up with attackers. There are ways around black lists via ASCII tables, escape characters and what not.

Also, here's a nice cheat sheet to try out on your site. Run some tests and try to get things to fail.

* In the application, not the DB (Thanks James)