I am learning sh to make some customized function. I am looking for a safety location for the personal script, since I check from stack exchange, some say that put personal script under ~/bin
may explore to malicious software like make a ls()
that really perform like rm -rf
.
1 Answer
Edited following ilkkachu's comment. I forgot that write protection on a file doesn't protect it against deletion, so it also needs to be in a write-protected folder.
Your file will require a password to modify if
- only the owner has write permissions
- the owner is root
Even so, anyone can still delete the file, and then recreate it with their own content. To prevent that, the file needs to be placed in a folder without write permissions. And that folder could be deleted too, so it also needs to be in a protected folder, etc all the way up to /
...
In other words, you want the file permissions to look like this:
.rw-r--r-- root
which lets your normal user shell run it, but requires sudo to modify it; or
.rwxr-xr-x root
if it also needs to be executable.
And all the containing folders between /
and the file need to look like this:
drwxr-xr-x root
Fortunately, most of the top-level system folders outside of home
fit the bill, since they're writeable by root only. I'm not sure what the convention says would be best, let's pick /usr/share
for example.
So, starting from an ordinary file ~/myscripts/script.sh
:
# change file permissions to .rw-r--r--
chmod 644 myscripts/script.sh
# or to .rwxr-xr-x
chmod 755 myscripts/script.sh
# set permissions on the folder (they should be like this by default already)
chmod 755 myscripts
# make root the owner
sudo chown root:root myscripts/script.sh
sudo chown root:root myscripts
# place it in one of the root folders
sudo mv myscripts /usr/share/
If you're worried about that attack vector, you should make sure all your auto-run shell scripts are similarly protected: .bashrc, .bash_profile... (I don't know if it may give undesirable side-effects, haven't tried). You would also have to lock down any symlinks or config files that point to the new location.
-
but you'd also need them to remove write access to their home directory, as otherwise they can just remove and recreate the file using their own account– ilkkachuCommented Apr 6, 2023 at 17:56
~/bin
. It can also modify your shell's startup files, like~/.bashrc
, or~/.profile
, along with any other similar configuration files of other programs.