perl open() injection prevention

Random User picture Random User · Oct 28, 2014 · Viewed 9.3k times · Source

I have read that the open() command with 2 arguments is vulnerable to injection whereas the open() command with 3 arguments isn't inject-able.

SAy I have a directory where all my files have a common prefix, i.e "file-" so an example filename would be, file-SomeSourceCode.txt

How would something like open(FILEHANDLE, "some/random/dir/file-" . $fileextension) be vulnerable?

where $fileextension could be any sort of 'filename' per say. As far as I understand, this would not be vulnerable to a filename like | shutdown -r | which would execute the command to the server.

Answer

ikegami picture ikegami · Oct 28, 2014
open(my $fh, "some/random/dir/file-" . $user_text)

is completely vulnerable. Not only does the improper injection make it impossible to open a file named

some/random/dir/file-foo|

it can be used to execute arbitrary commands

$ perl -e'open(my $fh, "file-".$ARGV[0])' ' ; echo 0wned >&2 |'
sh: 1: file-: not found
0wned