Tainted Variables in Perl

Tainted Variables in Perl

Perl includes a useful option to treat all input as unhygienic, or tainted, until it has been processed. An error is raised by the Perl engine if the code attempts to perform potentially dangerous tasks, such as calling the operating system, with the tainted data. Take a look at this code:

use strict; my $filename = <STDIN>; open (FILENAME, ">> " . $filename) or die $!; print FILENAME "Hello!"; close FILENAME;

This code is unsafe because the filename comes directly from a user and the file is created or overwritten by this code. There's nothing stopping the user from entering a filename such as \boot.ini. If you start the Perl interpreter with the taint option (-T) running, the code results in the following error: Insecure dependency in open while running with -T switch at testtaint.pl line 3, <STDIN> line 1.

Calling open with an untrusted name is dangerous. The way to remedy this is to check the data validity by using a regular expression. (Regular expressions are explained later in this chapter.)

use strict; my $filename = <STDIN>; $filename =~ /(\w{1,8}\.log)/; open (FILENAME, ">> " . $1) or die $!; print FILENAME "Hello!"; close FILENAME;

In this code, the filename is checked prior to being used as the name in the call to open. The regular expression validates that the name is no more than 8 characters long followed by a .log extension. Because the expression is wrapped in a capture operation (the ( and ) characters), the filename is stored in the $1 variable and then used as the filename for the open call. The Perl engine does not know whether or not you created a safe regular expression, and so it's not a panacea. For example, the regular expression could simply be /(.*)/, which will capture all the user's input. Even with this caveat, tainting helps developers catch many input trust errors.



Writing Secure Code
Writing Secure Code, Second Edition
ISBN: 0735617228
EAN: 2147483647
Year: 2001
Pages: 286

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net