Secure temporary folders on existing Unix or Linux systems



This cheatsheet provides instrutions about how to quickly secure /tmp and /var/tmp folders, to prevent malicious scripts execution.

dd if=/dev/zero of=/mnt/tmp bs=1024 count=1024000
mke2fs -t ext3 /mnt/tmp

cp -aR /tmp /tmp_backup
mount -o loop,noexec,nosuid,rw /mnt/tmp /tmp
cp -aR /tmp_backup /tmp
rm -rf /tmp_backup

mv /var/tmp /tmp_backup
ln -s /tmp /var/tmp
cp -aR /tmp_backup /tmp
rm -rf /tmp_backup

chmod 1777 /tmp

cp /etc/fstab /etc/fstab.original
echo "/mnt/tmp /tmp ext3 loop,noexec,nosuid,rw     0 0" >> /etc/fstab

Finally, reboot to check if everything is working:

df -h
reboot

Now, it is time to test the configuration: a binary file present in the /tmp folder should be executed. If there is a permission denied error, that means the configuration is successful.

On a cPanel server, it is much easier to secure the /tmp folder – simply run the following command as the ROOT user:

/scripts/securetmp

Note: the above steps doesn't stop things like:

perl /tmp/script.pl
sh /tmp/script.sh
php /tmp/script.php