in reply to HTML Form and Perl

If i hardcode the values of dir and zip like this cd /dog/cat and unzip rat.zip they work just fine...
I am really confused by this. cd and unzip are not built-in perl functions. As kyle suggested, you normally would do something like this:
chdir($dir) && system("unzip", $unzip);
The && is there to make sure that the unzip command is run only if the chdir succeeds.

However, since you are using these commands in a CGI script, you need to take extra precautions to make sure that users cannot subvert your script to make it do something you don't want them to do. That means you have to validate the input to make sure it looks like what you expect it to look like. For example, I'm sure you don't want users to be able to chdir to just any directory and unzip just any file.

Perl has a nice feature called tainting which helps you keep track of user input which needs to be vetted before it can be passed on to commands like chdir and system. You can enable it using the -T switch in the she-bang line of your script:

#!/usr/bin/perl -T
When enabled, user input (like posted form data) will be marked as tainted, and if you try to pass the data directly to a command like chdir or system, perl will throw an exception. To untaint the data, you have to examine it with a regular expression:
my $dir = $query->param('dir'); my $zip = $query->param('zip'); die "invalid dir" unless ($dir =~ m/^([a-zA-Z0-9]+)\z/); my $valid_dir = $1; # $valid_dir is untainted die "invalid zip file" unless ($zip =~ m/^([a-zA-Z0-9]+)\z/); my $valid_zip = $1; chdir($valid_dir) && system("unzip", $valid_zip);

Replies are listed 'Best First'.
Re^2: HTML Form and Perl
by workman_m (Initiate) on May 07, 2008 at 19:16 UTC
    Well... i am about 75 and new to perl..so maybe i am confused :) BUT... when i hardcoded the perl script with the cd and unzip (as shown) and specified text not a variable... and executed the script by itself...it sure went to the right directory and unzipped the file...so...i just wanted to enhance that with a variable... It may have something to do with taint then...cause it only would not work with the variable... i will try your idea and see if that works. OLD MAN trying to learn :)
      well unless i missed something... this code as suggested...ran...but did not do anything or produce any errors that i could find. plus when i try to print it...nothing prints... here is what i have coded.
      #!/usr/bin/perl -T print "Content-type: text/plain\n\n"; use CGI; my $query = new CGI; my $dir = $query->param('dir'); my $zip = $query->param('zip'); die "invalid dir" unless ($dir =~ m/^([a-zA-Z0-9]+)\z/); my $valid_dir = $1; # $valid_dir is untainted die "invalid zip file" unless ($zip =~ m/^([a-zA-Z0-9]+)\z/); my $valid_zip = $1; chdir($valid_dir) && system("unzip", $valid_zip); print $valid_dir; print $valid_zip;