Prevent Main System Directories From “rm -rf” Accidents
Something must be in the air this week as I have come across two instances of dedicated server clients accidentally when trying to clear the Magento cache (public_html/var/cache) (rm -r mage*), running the command on the server main /var directory (rm /var/* -rf) Whoops.
With out a system backup such as R1 where we can restore the /var directory the outcome is rather grim and a full server rebuild is require then a restore from a local backup. My advice is only use SSH as ROOT with extreme caution as an experienced user or login as a cPanel user to run these commands where the user permissions prevent these commands from running. Off the back of these issues it prompted me to look for a resolution that would give people a second chance to confirm deletion or ignore the request, here is what I found:
1. Download the safe-rm cd /usrc/src/
wget http://94.247.100.142/safe-rm
2. Give execute permission to the file
chmod +x safe-rm
3. Most of the server rm binary will be in /bin/rm
Next, we echo our environment $PATH so we can see the path order which our systems binaries are been searched for and executed.
echo @PATH /usr/local/jdk/bin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/X11R6/bin:/root/bin
We need to place our safe-rm in any of the paths BEFORE the path where rm is located, in this case I will keep the file in /usr/local/sbin/rm
mv safe-rm /usr/local/sbin/rm
4. Next add a file called /etc/safe-rm.conf and include the following files in /etc/safe-rm.conf to protect from deleting with a custom warning
/bin
/boot
/dev
/etc
/home
/initrd
/lib
/lib32
/lib64
/proc
/root
/sbin
/sys
/usr
/usr/bin
/usr/include
/usr/lib
/usr/local
/usr/local/bin
/usr/local/include
/usr/local/sbin
/usr/local/share
/usr/sbin
/usr/share
/usr/src
/var
/var/lib
/var/lib/mysql
Once installed and trying to delete the system /var directory instead of the Magento var the below custom warning will be displayed
===
root@server [~]# rm -rf /var/
This is a system directory/file DO NOT DELETE /var/
===
Give this a try I’m sure you will agree prevention will be better than cure.