Cores and Extras Heliotropic Computing

Monday Nov 03, 2008

When your shell script generating a temporary file for programming purpose you must be very careful as it's much vulnerable to attack. Say, you are using a shell script which creates temporary files in this unsecured way:
sort /home/ritwik/filename > /tmp/temp.$$
Now this code will generate a temporary file with the PID as a suffix. It will help an attacker to guess the other filenames. Since PID of your program will most likely be between 1 and 33000, if he creates 33000 symlinks one of them will definitely work.Now if an attacker creates a symlink with the assumed file name and point it to another file , say abc , then abc will be overwritten. If abc is an important system file then the system will be suffered. Atleast if the attacker edits the contents of the temporary file (since all user has read write permission in /tmp directory) the program will produce a wrong output.
Removing the symlink ( you can do it by : rm -rf /tmp/temp.$S) won't be a good solution as an attacker may recreate it before the sort command execution.
Solaris provides a much safer way to create temporary files with 'mktemp' (Check out 'man mktemp'). As the man page suggest , you can create a temporary file securely in this way :

TMPFILE=`mktemp -t example.XXXXXX`
if [ -z "$TMPFILE" ]; then exit 1; fi
echo "program output" >> $TMPFILE

Here you can place some X as a suffix which will be replaced by some random value , so pretty difficult to assume the file name.

Now think about some another condition , where you have created a good number of temporary files in a shell script. If you want to create each file in the above mentioned way , that would be a pretty laborious job. 'mktemp' provides another option to securely create a temporary directory in this way :

TMPDIR=`mktemp -d /usr/tmp/dir.XXXXXX`
if [ -z "$TMPDIR" ]; then exit 1; fi
echo "program output" >> $TMPDIR/somefilename

Here also you can place some X as a suffix which will be replaced by some random value , so pretty difficult to assume the directory name.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed