# How can I set up a password for the 'rm' command?

My friends keep deleting my files using the terminal. So please help me out by explaining how to make a password for rm command.

• You will want to password protect the user account so those "friends" don't access it in the first place. Dec 27, 2016 at 12:37
• You should really try to learn how the system works and use its functionality. Dec 27, 2016 at 13:19
• It's likely that your friends are trying to "teach you a lesson" by screwing around with your computer when you leave it unguarded. Learn that lesson by protecting your account and disallowing guest access, or providing guest access with reduced permissions. Dec 27, 2016 at 15:53
• Please also remember about the unlink command. Also about the mv command, because you can effectively overwrite files with it. Also...
– Kos
Dec 27, 2016 at 16:01
• With friends like these who needs enemies? Dec 27, 2016 at 21:34

There's no easy way to set up such a password on the rm command itself, not without a lot of code hacking that'll probably break things like apt-get installing packages and removing files, and making you have to enter the password a thousand times, or potentially disrupting access to the command to people who would need it (like you, to delete your own files). You can sort of do this by having multiple user accounts and multiple access permission sets, and restricting access to different sections of data, such as your home directory so they can't get to it.

(The other option is individual user accounts for each users, and then Access Control Lists, as is detailed in the other answer that was posted by Videonauth)

Here's the core problem - you're letting your friends use your system. This has numerous security implications - the concept of "anyone with physical access to the box is going to be able to control the system and do any tasks" is an IT Security Mantra, which is why you don't 'share' physical systems access except with trusted authorized personnel.

The only truly sane way to do this is to not give your friends access to your computer, and give them a 'dedicated "Guest" system' that they can use, that you don't really care about the files on as much. This is the most 'secure' way to keep your files safe.

Of course, if that's not an option, then your only really safe option is to configure multiple user accounts, one for each user, with different home folders, and do not allow them access to your own home directory or access to any other user's home directories. And then keep everything you don't want them touching in your home directory, and don't give them sudo access, the root password, or share your password with them.

This is how you'd do this:

Let's say my name is "Foo" and I want user "Bar", a friend, to use my system but not access my files. The first step is to deny access to anyone but me to my home directory. This is to permit other users to not delete your files, but to also prevent other users from snooping around in your home directory and seeing what types of stuff you've got in your home directory:

chmod 750 /home/Foo


The second step is to create a user account for "Bar" (do NOT type what's in parentheses below, it's for information purposes only). This way, we can make sure he has his own separate set of access rights:

sudo adduser --create-home --user-group --shell /bin/bash Bar
sudo passwd Bar
(set a temporary password - you will not see characters as you type though)


The third step is to then restrict their home directory too so nobody can pry into their files either. This is just making things equal.

sudo chmod 750 /home/Bar


Wash your hands, rinse them off well, then repeat these steps for however many users you have on the system. They won't be able to access your files, and since you're not going to give them administrator privileges, they can't delete your files without attempting to sudo to do so - since you don't permit this, they can't touch your stuff. And they won't be able to see your files either, without becoming superuser, which won't happen here.

Just a note on disk encryption

While disk encryption works well to protect your data from a third party, there's limitations.

1. If the system is on, the disk is already decrypted, so you're at risk.
2. Some systems have broken disk encryption approaches. For example, some Acer systems use your password to only authorize the encryption/decryption and use hard-coded passwords, or use weak encryption that is easily cracked.
3. There are always methods to break into the 'keys', or try to extract them from memory just after a system is turned off but before the RAM data is 'gone' or deteriorated. (I will not go in depth on these, but these risks do exist).
4. Physical access to the machine, whether the system is encrypted or not, will always put your data at risk. Don't give physical access (or remote network access) to people you don't want to potentially give full access to your system to.

While Disk Encryption doesn't solve these problems, it puts extra layers of headaches for a threat actor. Someone who is a bad guy might give up if it's encrypted, or they may torture you (queue obligatory XKCD Security comic strip).

Therefore, if your system is encrypted, but you're letting other users use it, either they have a password to decrypt, or you're leaving your laptop decrypted so they can SSH in or have physical access. In both these cases, it's bad.

That said, if your system is not encrypted, then this section has no relevance for you.

• My laptop has an encrypted hard drive. Is allowing others access still a risk?
– Tim
Dec 27, 2016 at 18:41
• @Tim Yes, if the system is powered on and decrypted. And even when it's off, it's still possible with the right technology, time, and dedication to find decryption keys potentially still stored in RAM. Disk encryption is not 100% protection - there's ways around it, it's more a question of "Is the bad guy willing to actually put that much time and effort into it". And judging by the OP's question, their system is on and not encrypted (fully, or partially) so the deletion risk is there. Dec 27, 2016 at 18:43
• @Tim To add to Thomas's answer, some laptops have broken disk encryption implementation (if you're relying on hardware FDE). AFAIR Acer laptops don't really use your password for encryption, they use it only to authorize encrypting/decrypting with hardcoded password. Dec 27, 2016 at 19:28
• Data is always at risk if untrusted person has access to a system, encrypted or not Dec 27, 2016 at 19:54
• @LightnessRacesinOrbit apt-get runs dpkg, which runs scripts that often use rm. On my Xenial box, cd /var/lib/dpkg/info; grep -P '\brm\b' *inst outputs 344 lines, of which 333 look like real uses of the rm command -- just in installation scripts. grep -P '\brm\b' *rm shows even more in removal scripts (to delete config files, not package files). Dec 28, 2016 at 19:06

This may not really be about the rm command, since there are easy ways to delete files without using it. If the problem is that your friends are unintentionally misusing the rm command, then solutions that restrict use of that command specifically or cause it to work in a different way may be of some help. In contrast, if the problem is that your friends are deliberately treating your data in a way you don't want, then you need to implement actual security measures, and no solution that focuses on the rm command itself (or any discrete set of commands) will keep you safe.

## Do you need to control access, or just prevent honest mistakes?

Assuming your friends know you don't want them to delete your files, there are two possibilities:

1. They could be doing it on purpose. In this scenario, your friends are deliberately deleting your files, and you cannot even trust them to try to comply with your wishes about how they treat your data when they use your computer. The only solution to this problem is to use an actual effective security measure, as Thomas Ward has explained in detail. Often the best such measure is to keep them from using your computer. But making them use their own user accounts can provide some protection.

2. They could be doing it by mistake. In this scenario, your friends are extremely accident-prone, and they keep running rm commands they wish they hadn't. They want to treat you and your data with respect, but are really bad at doing so in practice because they keep running the wrong command, deleting the wrong file... or something like that. Although it would be nice to believe that this is what's happening, I caution you against assuming that people who keep deleting your data after you've told them to stop are operating without ill will.

Furthermore, even if their intentions are good, giving them separate user accounts is still the most foolproof way of preventing them from deleting your files, aside from not allowing them to use your computer.

If the situation really is #2 -- your friends are not trying to delete your files but just need help not accidentally deleting them, and the only way they ever accidentally delete them is through the inadvertent misuse of a small number of commands (like rm) that they have particular trouble using correctly -- then the techniques in Videonauth's answer may be of some use. But you must understand that they are not security measures, because the rm command is just one of many easy ways to delete files. See below for details.

I recommend you ask yourself, "Is my situation basically the same as if I, rather than the other people who use my computer, were the one using rm incorrectly?"

If the answer is no, then this is a matter of information security, and you need prevent your friends from using your user account. If the answer is yes, then you can use the same approaches you'd use if you were the one misusing rm:

• Education. Your friends need to know what they're doing and how to avoid it.
• Interface changes. Without taking away the actual ability to delete files (which requires separate user accounts), you can make it harder to accidentally delete files by making it so just running rm file by itself, without any further action, won't immediately delete file. Videonauth's answer gives one approach to this. In this answer, I present another.

But even if your friends aren't trying to do anything wrong, you should still consider having them use their own separate user accounts. This will still solve the problem -- the same security measures that protect data from deliberate destruction will protect it from unintentional destruction, too. Even without malicious intent, if someone keeps doing something you don't want them to do, then you cannot trust them to refrain from doing that thing.

## Making rm prompt before deletion can help prevent some mistakes.

To help people avoid accidentally deleting files with rm, you can make rm a shell alias that actually runs rm -i. Passing the -i flag to rm causes it to prompt the user before deleting each file (see man rm).

You could do this (for your user account) by adding alias rm='rm -i' to your .bash_aliases or .bashrc file. See this question and that one for details. This will take effect for your newly opened bash shells.

This provides no actual security, and is not foolproof at preventing mistakes either, because:

• They can choose to go ahead with the deletion, when prompted.
• They can bypass the alias in numerous ways, including by running /bin/rm or unaliasing it (unalias rm).
• There are many situations where alias expansion does not occur, and in these situations rm will not be run with -i.
• They can still delete files by using any of the techniques to do so that do not require rm (as is the case with Videonauth's approach -- see below).
• They can still damage data without deleting any files, such as by overwriting them or otherwise changing their contents (as is also the case with Videonauth's approach).

But if you don't need actual security (see above), then this might be the way to go. By comparison to the approach of preventing your friends from using the system-provided rm command:

• Aliasing rm to rm -i is less effective at preventing mistakes -- until they move on to using some other technique to remove files. At that point, keeping them from using rm will be entirely ineffective, even if they're not trying to do anything wrong, since presumably they'll use unlink (or any of the countless other commands that remove a file) with equal thoughtlessness.

• On the other hand, because alias expansion only occurs in some situations -- roughly speaking, ordinary interactive use of the shell -- your friends might think they're going to be prompted when they're not really prompted (because the command is in a script, for instance, or issued from a different shell). Videonauth's way does not have this problem, which is an objective advantage of that method over alias rm='rm -i'.

• When a script runs, unless it is written deliberately to use aliases, your aliases are not expanded in it. This means that aliasing rm to rm -i is very unlikely to break anything. This is an objective advantage of alias rm='rm -i'.

## rm can't do anything any other perfectly ordinary program couldn't do.

There's really nothing special about rm. It is a convenient and self-documenting way to remove files, so restricting access to it risks breaking numerous scripts that rely on it. But it is far from the only way to delete files -- it's just an ordinary program.

A few commands perform some task that a limited (non-root) user cannot perform without running them. For example, sudo lets you run programs as another user, after checking to ensure you're allowed to do so. passwd edits the database where users' passwords are stored, but only lets you change your own password (unless you're root, in which case you can change anybody's password).

/usr/bin/sudo and /usr/bin/passwd can do that because they have the setuid bit set, as shown by the s that appears in the leftmost column when you run ls -l:

ek@Io:~$type -a sudo passwd rm sudo is /usr/bin/sudo passwd is /usr/bin/passwd rm is /bin/rm ek@Io:~$ ls -l /usr/bin/sudo /usr/bin/passwd /bin/rm
-rwxr-xr-x 1 root root  60272 Feb 18  2016 /bin/rm
-rwsr-xr-x 1 root root  54256 Mar 29  2016 /usr/bin/passwd
-rwsr-xr-x 1 root root 136808 Aug 17 09:20 /usr/bin/sudo


Notice that /bin/rm has no s: its permissions are -rwxr-xr-x, while /usr/bin/passwd and /usr/bin/so have -rwsr-xr-x instead. This makes it so that, no matter who runs passwd or sudo, it actually runs as the root user, since root is the owner of the executable. (There is also a setgid bit, which, when set, causes executables to run with the group identity of their group owner rather than that of the caller.)

Except for any security vulnerabilities that haven't been discovered yet (or that have been discovered but haven't yet been patched), sudo and passwd are safe because those utilities are very carefully written so they can only do things that the caller ought to be allowed to do.

/bin/rm doesn't work this way. It's not setuid because it doesn't need to be. Directory permissions (and occasionally file permissions) control what files a user can delete, and they don't need to become root to do it. Just to be perfectly clear, please do not ever set the setuid bit on rm. The security implications would be disastrous, since then, no matter who runs rm, it's as though root ran it! (Utilities like sudo and passwd check who's really running them and check that something is permitted before doing it; rm does no such thing.)

Checking if the setuid (or setgid) bit is set on an executable will tell you if restricting who may run it stands a chance of improving security. Executables that aren't setuid (or setgid) don't have any special status, and anyone can simply copy them and run the copy, bring their own copy from another machine, write a script or program that does the same thing, or use another program to do it.

## Deleting Files Without rm

The obvious way to delete a file without rm in Ubuntu is to navigate to its location in the graphical file browser (Nautilus, if you're using Unity or GNOME Shell) and delete the file. There are also numerous commands that can be used to delete a file from a terminal, without ever using rm.

For example, to remove a file called foo.txt in the current directory, the following commands, which work out-of-the-box on Ubuntu and do not require access to rm, will achieve that. (Just to be sure, I tested them on a 16.04 minimal system installed with only the standard system utilities, after deleting /bin/rm.)

• unlink foo.txt
• busybox rm foo.txt
• perl -e 'unlink("foo.txt")'
• python3 -c 'import os; os.remove("foo.txt")' (python instead of python3 in older releases)

That list is, of course, nowhere near complete. No complete list of such commands is possible. Preventing file deletion is one of the things separate user accounts and file and directory permissions exist to achieve. They work very well to prevent it. In contrast, changing the rm command (to make it require a password, or in any other way) or restricting access to rm don't prevent it at all.

• For actual use, I like GNU rm's -I option. It prompts only for deleting 4 or more files, or for recursive deleting. So you don't get in the habit of always using -f, \rm to avoid alias expansion, or typing y without reading. But it will still save you from bad typos where you hit return before you meant to, or your glob matched many files. Dec 29, 2016 at 0:58
• Another interesting way to unlink files: mv foo.txt /tmp/.gone, then reboot, discarding the tmpfs that was backing /tmp. Or just use mv to rename multiple files all to the same name, so only the last one is left. Or just hide files by renaming them with obscure names. As the first part of this answer points out, if you're trying to defend against malice rather than incompetence, you need to just lock people out of your account. Dec 29, 2016 at 1:00

You can change the permissions on the /bin/rm command via the following line which will prevent it being executed without sudo access:

sudo chmod 750 /bin/rm


This specifically prevents them from using the rm command provided by the system. You should be aware that it does not prevent them from deleting files in other ways.

To also prevent them from using the rmdir command, which is a common way to delete directories, you can set permissions the same way on its executable path:

sudo chmod 750 /bin/rmdir


Remind that as well you can only use this commands with sudo rights too.

To change it back if you not like it or other problems occur use 755 for chmod

As @muru pointed out the above is a very crude solution and might even break system services which are not running on the root account. Therefore I add here another option using ACL (access control lists) to do the same and probably much safer (good to read into as well and you can skip the enabling part because ACL is usually installed on Ubuntu systems nowadays):

So to do the same as above just for the users you want to block would be

sudo setfacl -m u:<user-name>:- /bin/rm /bin/rmdir


Just replace <user-name> with the actual user names you want to prevent using the files.

As with chmod, using setfacl -m to prevent specific users from running rm and rmdir applies to those system-provided commands only. It doesn't keep them from deleting your files and folders in Nautilus or by using other terminal commands.

Explanation:

• the -m flag means to modify the files ACL.
• the first part of the change, the u stands for user. It can have the following values u for user, g for group and o for all others
• the middle part <user-name> can holt the actual user name or group name according to what you want to change. To set overall changes you leave it empty.
• the third part holds the kind of permissions you want to set. Here in the example we want to set no permissions at all so we put -, it can as well contain the following letters r for read permissions, w for write permissions and x for execution.
• It would be better to use ACLs than remove execute permissions for others - any system service that doesn't run as root is now handicapped.
– muru
Dec 27, 2016 at 12:43
• sudo setfacl -m u:<username>:- /bin/rm /bin/rmdir, IIRC. You can test the ACL with getfacl /bin/rm /bin/rmdir
– muru
Dec 27, 2016 at 12:49
• The only downside to ACLs like this is it's evil/tricky to maintain these long-term. And impossible to maintain if there's not individual users on the system for each person using the system. Otherwise, it's a good idea. Dec 27, 2016 at 13:45
• @DavidFoerster Yes. There's an effectively unlimited number ways to delete files without rm. The solution Videonauth has given here is a possible way to help accident-prone users stop deleting stuff, but it doesn't provide any actual security (which may be okay, if the OP's friends aren't deliberately trying to subvert the OP's wishes). Videonauth: I suggest editing this post so it prominently clarifies that it doesn't actually prevent people from deleting files since they don't need the rm command to do so. (I'm refraining from editing it myself, in case you don't want to say that.) Dec 27, 2016 at 19:59
• Don't forget that Perl, Python, and all the compilers on the system allow the other users to delete files too. Preventing people from deleting files requires more than just changing the permissions on the rm command. Dec 29, 2016 at 7:10

This is a very simple answer and will stop someone casually using the rm command without giving a password. It is not a secure solution and you should impliment some of the alternate suggestions in the other answers.

However, you could use alias to change the way that the rm command behaves. Try:

alias rm="sudo -l >/dev/null && rm"

What this does is when someone enters the rm command, it runs the sudo -l command. This command forces the user to enter their password. If they get it right, it lists their privileges (we discard this output) and exits with status 0, if they get it wrong, it exists with an error.

We then follow the sudo command with a "&&", which exits the following command -- in this case "rm" only if the previous command exits with status 0 -- ie they got the password right.

To make this permanent, include the alias command in ~/.bashrc.

Note this this is very easily defeated (for example, they could simply type /bin/rm.

# Sometimes it's not our friends, we are our own worst enemies

I've written a script to password protect rm like the OP requested but also put in edits to prevent you from accidentally deleting:

• /
• /home
• /bin

Edit: Mar 5 2017 - Change method of checking if running in terminal.

## Create the script

Use gksu gedit /usr/local/bin/rm and copy in these lines:

#!/bin/bash

tty -s;
if [ "0" == "$?" ]; then Terminal="Y"; else Terminal="N"; fi if [$Terminal == "Y" ] ; then
# Running from terminal don't allow delete of / or /toplevel directory even if sudo
for i in ${@:1} do # Skip options -i -r -v -d if [[${i:0:1} != "-" ]] ; then
# if parameter doesn't begin with '-' it's file or directory, so get real path.
fullname=$(realpath "$i" 2>&1) # No error messages if file doens't exist
# We must have at least two / in the full path
levels=$(echo "$fullname" | tr -cd '/' | wc -c)
if (( $levels == 1 )); then # Test for 1, will be zero when file doesn't exist. echo "Attempting to remove top level directory '$fullname'"
echo "Use 'sudo /bin/rm $@' instead." exit 1 # error fi fi done fi if [[$(id -u) != 0 ]]; then # Only non-root processes enter password (ie "sudo rm ..." is ok)
if [ $Terminal == "Y" ] ; then # Only running from a terminal needs password (ie not cron) # log rm usage to /var/log/syslog PARENT_COMMAND="$(ps -o comm= $PPID)" logger "$PARENT_COMMAND"" - rm command was used on file: ""$fullname" # Get password Password=$(zenity --password --title="Password for rm")
encryptPassword=$(echo -n "$Password" | md5sum)

echo "md5sum: $encryptPassword" # Comment out after viewing one time and updating line below. if [[ "$encryptPassword" != "d2c30dc65e59558c852ea30b7338abbe  -" ]]; then
/bin/rm "$@" exit 0  Change the password "WE2U" to anything you like and save the file. ## Mark new rm script as executable Flag new rm script as executable using: sudo chmod +x /usr/local/bin/rm  ## How it Works Unless the password is WE2U, the first time you run the script you will get "invalid password" and the encryption key for the password you entered is displayed. Copy and paste this encryption key from the terminal into the script. Then comment out the line with the echo that displayed the encryption key on the terminal. Because the path /usr/local/bin is higher on the list than /bin our command rm is called. After getting valid password it calls /bin/rm to do the real removal. As Thomas Ward pointed out in another answer, if you were to do a sudo apt-get install ... you could be asked for password a thousand times. The script checks if sudo is used and doesn't ask for a password. Furthermore if rm is called from within GUI application no password is required. The script calls logger to record every time rm was manually called using the terminal. Command usage is recorded to /var/log/syslog. • You could mask the password by simply including a hashed version of it in the script, and then whenever the user enters a password, it could simply hash it and check it against the hard-coded hash. Dec 31, 2016 at 3:43 • @InitializeSahib hashed password support (encryption) has been added to the script. Mar 2, 2017 at 2:18 Another alternative would be to create backup copies of any important files in a directory that non-root users don't have access to. You could use rsync or unison to synchronize them automatically, just make sure at least one directory in the path to the backup destination is owned by root and mode 700. This would result in having two copies of all the files though. It would be safer to just create a guest user for them to use, except you do need to remember to always lock or log out before giving them the computer or leaving it unattended. • You might want to point out how to avoid deletion being propagated? And ideally a way to switch that off and on so that when the user is doing something that requires delete to be permanent, it is permanent. Dec 27, 2016 at 15:03 • @ajostergaard My thought was that whenever he gets his computer back from his friends he manually checks that nothing is missing and restores anything that is. But my own preferred tool is unison used in gui interactive mode, which makes it easy to see (and reverse) deletions. Dec 27, 2016 at 15:28 Not the direct answer to the question you're looking for but: If your friends are deleting your files using the rm command then either your friends are either incompetent, jerks, or they're BOFH wannabes who are trying to teach you not to leave your sessions logged in and unattended. In all cases, the solution is the same: don't leave your session logged in and unattended. This has the advantage of not needing to remember to make special changes to the system whenever you upgrade or get a new system, and also prevents scripts and other things you use that rely on commands behaving as expected from failing in unpredictable ways. It also has the advantage of stopping "friends" from moving on to the next step. Will you also want to "password protect" the mv command if they decide to move your files to /dev/null when they find out that a simple remove doesn't do what they want? When you're in a game like this the only winning move is not to play. I have a similar possibility that I planned for. On the file server, if the main storage of photos is writable that somone in the family (less technical or by accident) might delete something, accidently drag in the gui which moves the directory, or overwrite an original with an edited version rather than renaming. I realized that I can protect against that without making the permissions unwritable for everyone else. ZFS makes periodic snapshots so any accidental deletion or overwriting can be reversed. (Unlike a backup, a snapshot is lightweight and copy-on-write so it doesn’t multiply your storage usage.) ZFS is native to FreeBSD. Linux has btrfs which also has snapshots. A very silly workaround for a very silly issue. If you don't want to chmod rm, rmdir, or mv (for mv filename /dev/null) or use ACLs, you could create a dummy user with a password nobody but you knows and alias each command to sudo [user], and then make aliases for each command that your friends don't know. This way, when your friends type rm the system will prompt them for a password (but guessing the password wrong will log the failed attempt), and you can still just type rmalias or whatever you choose to actually delete files. Or you could just create a guest account that doesn't have access to your home directory. • It sounds like you are on the right track. Your answer could be improve by elaborating on how to setup alias, sudo [user] and dummy user Dec 31, 2016 at 5:09 If you want to password-protect rm, a solution would be to make a wrapper for rm that would require root privileges, and ask for a password otherwise. (NOTE: This wrapper may go away when the coreutils package is updated or reinstalled.) Also, please note this only secures rm, there are still many, many other ways to delete a file. Open up a terminal and become root. Then run sudo mv /bin/rm /bin/rmold to move the old rm to another place. Now run sudo nano /bin/rm to create a wrapper. In Nano, type the following: #!/bin/bash /bin/rmold "$@"
exit "$?"  Then hold CTRL, and press X to exit. Press Y when you're prompted, then hit ENTER to save the file. Finally, we need to give this the appropriate permissions: sudo chmod a+x /bin/rm  And there you go. • Unless you have a very good reason, script variables should always be quoted: $@ => "$@". Here, what you are proposing is a very dangerous version of the original and safe rm: what if there is a file named foo -i -r * (-i added to protect the innocent users)? Dec 30, 2016 at 11:49 • In addition to "-quoting $@ as @xhienne says, I'd urge you to clearly warn readers that this provides no security at all since there are many ways to delete a file. One is to call rmold, but there's a multitude of other ways, as discussed in other answers and comments on them. (Even then, this will have the problem that rm will feel like it deletes files as the current user -- it's called without sudo, and normal rm runs as the caller -- but does so as root! If they've recently sudoed, they won't notice they might be deleting system files even if they know about the change.) Dec 30, 2016 at 12:24