Sign In/My Account | View Cart  
advertisement


Listen Print Discuss

Perl Code Kata: Testing Taint
by chromatic | Pages: 1, 2

Tips, Tricks, Suggestions, and One Solution

To test tainting properly, you must understand its effects. When Perl sees the -T or -t flags, it immediately marks some of its data and environment as tainted. This includes the PATH environment variable.

Also, taint is sticky. If you use a piece of tainted data in an expression, it will taint the results of that expression.

Both of those facts make it easy to find a source of taint. CGI::Untaint::boolean's do the following to make tainted data:

my $tainted_on = substr( 'off' . $ENV{PATH}, 0, 3 );

Concatenating the clean string off with the tainted value of the PATH environment variable produces a tainted string. The substr() expression then returns the equivalent of original string with tainting added.

How can you tell if a variable holds a tainted value? The Perl FAQ gives one solution that attempts to perform an unsafe operation with tainted data, but I prefer the Scalar::Util module's tainted() function. It's effectively the same thing, but I don't have to remember any abnormal details.

This technique does rely on Test::Harness launching the test program with the -T flag. If that's not an option, the test program itself could launch other programs with that flag, using the $^X variable to find the path of the currently executing Perl. It may be worthwhile to check that the -T flag is in effect before skipping the rest of the tests or launching a new process and reporting its results.

The prove utility included with recent versions of Test::Harness may come in handy; launch the test with prove -T testfile.t to run under taint mode. See perldoc prove for more information.

You could also use this approach to launch programs designed to abort if the untainting fails, checking for exit codes automatically. It seems much easier to use Scalar::Util though.

Conclusion

This should give you everything you need to solve the problem. Check your code against the tests for CGI::Untaint::boolean.

If you've found a differently workable approach, I'd like to hear from you. Also, if you have suggestions for another kata (or would like to write one), please let me know.