Writing secure Perl code is a must, especially for web applications where user input is king. Always assume that input can be malicious, so sanitize, validate, and escape everything. Perl has built-in pragmas and modules that help keep your code clean and safe.
Some common security pitfalls in Perl include injection attacks (SQL injection, command injection), cross-site scripting (XSS), and unsafe file handling. Understanding and mitigating these risks will save your apps from getting pwned.
strict
and warnings
Start every Perl script with these pragmas to catch errors early and avoid sloppy code that could lead to security holes.
use strict;
use warnings;
Never trust user input! Use regex or modules like Scalar::Util
to verify input matches expected patterns.
my $username = param('username');
if ($username =~ /^[a-zA-Z0-9_]{3,20}$/) {
# safe to use
} else {
die "Invalid username!";
}
When calling external programs, use the list form of system
or exec
to avoid shell interpolation.
# BAD: vulnerable to injection
system("rm -rf $user_input");
# GOOD: safer approach
system('rm', '-rf', $user_input);
Never directly interpolate variables into SQL statements. Use DBI
’s placeholders to prevent SQL injection.
my $sth = $dbh->prepare("SELECT * FROM users WHERE username = ?");
$sth->execute($username);
Escape HTML output using modules like HTML::Entities
before displaying user data in web pages.
use HTML::Entities;
my $safe_output = encode_entities($user_input);
print "<p>$safe_output</p>";
CGI::Carp
– redirects errors to the browser or logs for debugging.Data::Dumper
– safely inspect data structures.Params::Validate
– validates function and user input parameters.Crypt::Eksblowfish::Bcrypt
– secure password hashing.Try::Tiny
– safer exception handling.