Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 43 ยท Tools and Quality

Security and Safe Perl

Write safer Perl: taint mode, avoiding shell injection, three-argument open, DBI placeholders, encoding pitfalls, handling secrets and vetting CPAN modules.

Perl code often sits between the outside world and something valuable: a web form and a database, a file name and the file system, a log line and a shell command. Most security bugs in such code have one cause. Data from outside gets treated as code or as a trusted value. A name becomes part of a shell command, a quote character escapes from an SQL string, a path walks out of the directory it was meant to stay in.

This lesson covers the classic Perl-specific defenses: taint mode, safe ways to run commands and open files, DBI placeholders, character encoding, secrets, and how to choose dependencies you can trust. The rule behind all of them is the same: validate inputs with an allow-list, and keep data and code separate.

Perl is not installed on this site, so the Perl code below is read-only; the outputs shown come from real runs. The interactive examples are Python stand-ins that demonstrate the same attacks and the same defenses (parameterized queries and allow-list validation), because those ideas are language-independent.

The golden rule

Input is hostile Anything from outside can be crafted.
Allow-list Accept known-good shapes, reject the rest.
Keep code apart Never paste data into code or commands.
1 / 2

Taint mode

Perl has a feature almost no other language offers: taint mode. Turn it on with the -T switch, on the command line or in the #! line, and Perl marks every value that comes from outside as tainted: command-line arguments, environment variables, file contents, input from sockets and readdir, even locale data. Any value computed from a tainted one is tainted too. Perl then refuses to use a tainted value in anything dangerous, such as a shell command, opening a file for writing, unlink or eval.

PERL
#!/usr/bin/perl -T
use v5.36;

my $name = $ARGV[0] // '';

open(my $out, '>', "/tmp/$name.txt") or die;   # dies: tainted data
TEXT
Insecure dependency in open while running with -T switch at t1.pl line 5.

The only way to make a tainted value clean is to untaint it by extracting part of it with a regular expression capture. The capture is considered checked, because you wrote the pattern:

PERL
if ($name =~ /\A([A-Za-z0-9_-]{1,32})\z/) {
    my $safe = $1;                 # untainted
    open(my $out, '>', "/tmp/$safe.txt") or die "open: $!";
}
else {
    die "bad name\n";
}

Two habits make this work well. First, match what is allowed, not what is forbidden: the pattern above lists the safe characters, instead of trying to list every dangerous one. Second, anchor with \A and \z so an extra line or character cannot slip past. Taint mode also insists that $ENV{PATH} be set to a fixed value before you run an external program, so assign it near the top: $ENV{PATH} = '/usr/bin:/bin';.

Taint mode is a safety net, not a guarantee: a sloppy pattern like /(.*)/ untaints everything and defeats the check. It is strongly recommended for CGI-style programs and anything running with extra privileges, and Perl turns it on automatically when a script is run set-uid.

Running commands safely

The most dangerous Perl one-liner is a shell command built from a string. When you give system or backticks a single string with shell characters in it, Perl hands it to the shell, and the shell obeys every ;, |, &, backtick and $() in it.

PERL
my $ip = "1.2.3.4; echo INJECTED";
system("echo pinging $ip");              # the shell runs TWO commands
system('echo', 'pinging', $ip);          # list form: ONE command, safe
TEXT
pinging 1.2.3.4
INJECTED
pinging 1.2.3.4; echo INJECTED

The first call let the user's text become a second command. In the list form, with more than one argument, Perl runs the program directly without a shell, and every argument arrives as plain data. So:

  • Use the list form of system, exec, and the piped form open(my $fh, '-|', 'prog', @args).
  • Avoid backticks and qx// with variables in them. Capture output from a list-form pipe open or use a module such as IPC::Run3 or Capture::Tiny.
  • Better still, do not run a program when Perl can do the job: use File::Copy, File::Path or opendir rather than cp, mkdir -p and ls.
  • If you must build a shell string, validate each value against an allow-list first.

The idea of "one list of arguments, no shell" is the same in every language. Here it is in Python by showing what a naive shell would split a string into, and what a list holds:

Python Shell string versus argument list (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three-argument open

Perl's old two-argument open mixed the file name and the mode in one string, and it looks at the beginning and end of the string for special characters:

PERL
my $f = "> /tmp/pwned.txt";
open(my $fh, $f) or die;        # opens /tmp/pwned.txt for WRITING

If the name came from a user, they decide the mode. A leading > truncates a file, a trailing | runs a command, and a leading < is read mode. The three-argument form separates mode from name, so the name is only ever a name:

PERL
open(my $fh, '<', $f) or die "Cannot open '$f': $!";

With the same $f, this fails with No such file or directory, because there is no file literally called "> /tmp/pwned.txt". Always use the three-argument form, always use a lexical filehandle (my $fh), and always check the result. For file names you accept from users, also guard against path traversal: a name like ../../etc/passwd escapes the folder you intended. Reject names containing .. or slashes, or allow only a fixed pattern such as \A[\w.-]+\z and build the full path yourself with File::Spec.

Database queries with DBI placeholders

SQL injection happens when user input is pasted into a query string. A value such as x' OR '1'='1 changes the meaning of the query. The cure is the same in every language: send the SQL text and the values separately, with placeholders:

PERL
use DBI;
my $dbh = DBI->connect('dbi:SQLite:dbname=app.db', '', '',
                       { RaiseError => 1, PrintError => 0 });

# WRONG: user input becomes part of the SQL
my $rows = $dbh->selectall_arrayref(
    "SELECT * FROM users WHERE name = '$name'");

# RIGHT: ? is a placeholder, the value travels separately
my $sth = $dbh->prepare('SELECT id, name FROM users WHERE name = ?');
$sth->execute($name);
while (my $row = $sth->fetchrow_hashref) {
    say "$row->{id}: $row->{name}";
}

Placeholders work for values, not for table or column names. If a column name comes from the user, check it against a hard-coded list of allowed names. $dbh->quote($value) exists, but placeholders are simpler and safer; use them everywhere. Setting RaiseError => 1 makes failures die instead of being silently ignored, which is also safer.

You can see the difference with an in-memory SQLite database. The first query is built by pasting a string, the second uses a placeholder:

Python SQL injection and placeholders (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Encoding pitfalls

Text that looks right on your machine can break or be misread elsewhere, and encoding confusion can also bypass checks (for example a validator that sees bytes while the consumer sees characters). Perl distinguishes bytes from characters, and the safe pattern is: decode on the way in, work with characters, encode on the way out.

PERL
use v5.36;
use utf8;                                        # your source file is UTF-8
use Encode qw(decode encode);

binmode(STDOUT, ':encoding(UTF-8)');             # encode output
open(my $in, '<:encoding(UTF-8)', $file) or die; # decode file input

my $raw   = "caf\xc3\xa9";                       # five bytes from the network
my $chars = decode('UTF-8', $raw);
say length($raw), ' ', length($chars);           # 5 4
  • Use use utf8; only to declare that your source code is UTF-8. It does not decode input.
  • Use the :encoding(UTF-8) layer (not the lax :utf8) on file handles, so malformed input is detected.
  • Decode command-line arguments and environment values explicitly if they contain non-ASCII text.
  • Validate and normalize after decoding. Compare \x{e9} and e plus a combining accent only after normalizing with Unicode::Normalize, or visually identical names can slip past a uniqueness check.
  • Be careful with \d and \w on Unicode text: they match digits and letters from many scripts unless you add the /a modifier.

Secrets and randomness

  • Never put secrets in source code or in version control. Read passwords, API keys and tokens from environment variables or a file outside the repository with tight permissions. Do not print them in logs or error messages.
  • Do not store passwords as plain text or with a fast hash. Use a password-hashing library such as Crypt::Argon2 or Authen::Passphrase::BlowfishCrypt (bcrypt), which salt and slow down guessing.
  • Do not use rand for security. Its output is predictable. Use Crypt::URandom or Crypt::PRNG for tokens, session IDs and keys.
  • Do not invent cryptography. Pick a well-reviewed module for encryption or signatures, and use the recommended defaults.
  • Compare secrets in constant time where possible (some crypto modules provide a helper for this), to avoid leaking information through timing.
  • Use HTTPS and let the client verify certificates. With HTTP::Tiny, certificate checking (verify_SSL) should stay enabled.

Vetting modules

CPAN is a great resource, but every dependency runs with your program's rights. Before you add one:

  1. Check it is maintained: recent releases, open issues answered, and a clear repository on MetaCPAN.
  2. Look at its dependencies; a small module that pulls in dozens of others widens your exposure.
  3. Read its tests and documentation, and skim the code for eval of strings, system calls and network access.
  4. Prefer widely used modules that others have reviewed.
  5. Pin versions in a cpanfile with a snapshot (Carton) so an update never changes your production code unexpectedly. Dependency handling is covered in CPAN and Dependency Management.
  6. Run cpan-audit or a similar tool to check dependencies against known advisories.

Avoid string eval and do of user-supplied text entirely. Also be careful with use lib and PERL5LIB in privileged scripts, since they decide which code Perl will load.

Python Allow-list validation of a file name (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does taint mode (-T) do?

    Perl tracks values that come from outside and refuses to use them in operations like running commands or opening files for writing, until a regex capture untaints them.
  2. 2. Which call avoids shell injection?

    With a list of several arguments, Perl runs the program directly without a shell, so the value of $dir is a single plain argument.
  3. 3. Why prefer the three-argument open?

    In the two-argument form, special characters in the name such as > or | change the meaning. The three-argument form treats the name only as a name.
  4. 4. How do you prevent SQL injection with DBI?

    Placeholders keep the SQL text and the values apart, so a value can never change the structure of the query.
  5. 5. Which source of randomness is appropriate for session tokens?

    rand, time and process IDs are predictable. Use a cryptographically secure source for anything security-sensitive.

Summary

  • Treat all outside data as hostile; validate with allow-lists, not block-lists.
  • Taint mode (-T) makes Perl track untrusted data; untaint only with a precise, anchored regex capture.
  • Run programs with the list form of system and pipe opens, and avoid backticks with variables.
  • Always use three-argument open with lexical filehandles and error checks, and guard against path traversal.
  • Use DBI placeholders for every value in SQL, and whitelist any table or column names.
  • Decode input and encode output with explicit :encoding(UTF-8) layers.
  • Keep secrets out of code, hash passwords with a proper algorithm, use secure randomness, and vet and pin your CPAN dependencies.

Next, put your Perl text skills to work in Project: Log Analyzer.