You need to ensure that the password is only readable by authorized users. Don't store the password in the script, store it in a separate file that you read from the script. It's a lot easier to manage permissions this way. If you store credentials in the script, it's hard to be sure where they'll end up: they may be inadvertently copied around, they should be entered in version control, etc.
Separating the credentials from the script has a second and arguably more important benefit. It separates “permission to execute the script” from “permission to access the resource”, which is good, because you aren't really trying to prevent people from executing your script, you're trying to prevent people from accessing the resource. So set the permissions on the password file accordingly, and you'll be set.
The easy way to manage permissions is to create a group and put the users who are allowed to access the resource in that group. Let's call the group seniors
, and say that users alice
and bob
are allowed to access the resource. Create a group called seniors
(e.g. addgroup seniors
), and add the users to the group (e.g. adduser alice seniors; adduser bob seniors
). Make the password file owned by the group seniors
and readable only by the group.
chgrp seniors password.txt
chmod u=rw,g=r,o= password.txt # or chmod 640 password.txt for short
Maybe you want some users to be able to execute the script but not to have arbitrary access to the resource. You don't mention this in your question, but I'll explain how it can be done just in case.
Suppose that the users charlie
and dominique
must be able to execute that particular script, but not access the resource otherwise. Create a group called juniors
and put these users into this group. (You don't actually need to create a group but it makes management easier.) Create a sudo rule that allows users in the group juniors
to obtain the permissions of the group seniors
, but only to execute one specific program — the script that reads the password file. Run visudo
to add this line to the sudoers
file:
%juniors ALL = (:seniors) /path/to/script ""
The juniors can execute the script by calling sudo -g seniors /path/to/script
. The script will then run with the additional privileges conferred by the group seniors
. Nonetheless the user who called sudo
will not be able to access the password file (unless the script is buggy and can be tricked to leak it).
Note again that sudo is only useful if you need some people to be able to access the resource without knowing the password. It won't do anything for you if all you want is to restrict access to the password to certain users, and not allow anyone else to access the resource.
sudo
, obscurity != security! – slm Jul 09 '13 at 07:24sudo
. – slm Jul 09 '13 at 07:39