Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I protect against SQL injection attacks using Perl's DBI?

Is there a function i can use in Perl to sanitize input before putting it into a MySQL db? I don't know regex very well so before I make my own function i was wondering if there was already one made.

like image 725
cskwrd Avatar asked Feb 20 '10 02:02

cskwrd


People also ask

What protection could be used to prevent an SQL injection attack?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is the best defense of SQL injection?

You should always use parameterized statements where available, they are your number one protection against SQL injection. You can see more examples of parameterized statements in various languages in the code samples below.

Which technique is used to help mitigate SQL injection attacks?

Parametrized queries This method makes it possible for the database to recognize the code and distinguish it from input data. The user input is automatically quoted and the supplied input will not cause the change of the intent, so this coding style helps mitigate an SQL injection attack.


1 Answers

The proper way to sanitize data for insertion into your database is to use placeholders for all variables to be inserted into your SQL strings. In other words, NEVER do this:

my $sql = "INSERT INTO foo (bar, baz) VALUES ( $bar, $baz )"; 

Instead, use ? placeholders:

my $sql = "INSERT INTO foo (bar, baz) VALUES ( ?, ? )"; 

And then pass the variables to be replaced when you execute the query:

my $sth = $dbh->prepare( $sql ); $sth->execute( $bar, $baz ); 

You can combine these operations with some of the DBI convenience methods; the above can also be written:

$dbh->do( $sql, undef, $bar, $baz ); 

See the DBI docs for more information.

like image 67
friedo Avatar answered Sep 29 '22 04:09

friedo