Perl Security

Programmers often assume that their script will be used in a particular way and that users will behave as expected. When writing a script, you should always keep in mind that everybody makes mistakes, and some people deliberately try to break things. For example, if your script expects the number 2 but the user types two, what will happen? This is particularly important if you make your scripts available via the Web. You should never trust user input and use it directly for sensitive operations such as opening files or running commands on the server.

Perl has a taint mode that warns you if the script injects user input directly into a sensitive operation. You can turn on the Perl taint mode by adding the -T switch after the path to the Perl interpreter at the top of your script, for example:

#!/usr/bin/perl -T

Unfortunately, this taint mode does not recognize variables passed to the script from a web form via the param() function, so you’ll need to manually check that the user input is what you expect. This is typically performed using regular expressions, where we match a string against a template.

For example, we can ensure that the form variable Age is a number between 10 and 99:

if(param())
{
 if(!(param('Age')=~/^([1-9][0-9])$/))
 {
  print
   font({-color=>'red'}, 'Invalid age:  must be between 10 and 99 inclusive.');
   exit;
 }
 my $user_age = "$1";
 print $user_age;
}

Perl offers some cryptic syntax for regular expressions, but they make the expressions very easy to integrate ...

Get Learning MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.