tags:

views:

110

answers:

4

Is storing my password this way safe?

echo 'Write sudo password (will not be displayed) and hit enter'
read -s password

I need it to make commands like this:

echo $password | sudo -S apt-get install -y foo bar
+2  A: 
echo $password | sudo -S apt-get install -y foo bar 

This is a bit dangerous. If the user is already authenticated to sudo, sudo won't request the password again and it will be forwarded to apt-get, with could lead to strange results (for example, if the postinstall script asks a question). I would suggest to use

sudo -k                         # remove previous sudo timestamp
echo $password | sudo -v -S     # create a new one for 15 minutes
sudo apt-get ...                # execute the command

instead.

EDIT: Dirk is correct about the password being visible for a very short time while echo is executed. Please see my answer as an extended comment rather than an answer to your question.

Heinzi
Why use the variable - why not just let sudo handle the prompting? I think the second line should become `sudo -v -S`. The only reason to keep it would be because 'read -s' does not echo the password - but then, neither does `sudo`, does it?
Jonathan Leffler
@Jonathan: True. However, such scripts are often used to execute sudo on multiple computers (see here for an example: http://www.heinzi.at/projects/upgradebest.sh/). Then, it makes sense not having to enter the password multiple times.
Heinzi
Fair enough - I forgot to account for the minimization for the purposes of asking the question on SO.
Jonathan Leffler
+7  A: 

No because you can see it via /proc/$PID/cmdline.

I suggest not to try to reinvent security tools. The sudo program can cache your password.

Dirk Eddelbuettel
There might be a very short window while the /proc entry for the echo command exists, but 'short' is the operative term, it seems to me (as in milliseconds, or less).
Jonathan Leffler
Do `strace -o bash.strace -f bash -c 'echo password | cat'` and examine the file `bash.strace`. You will see the line with `execve("/bin/cat", ["cat"], [/* 53 vars */]) = 0`, but you won't see echo there (except in the first line where it is passed to bash): it is a bash builtin. So, launching the script in bash is enough to keep it safe.
ZyX
+6  A: 

A better approach would be to edit your sudoers file and add your program that don't require password...

Do a sudo visudo and add following to enable your admin group to run apt-get w/o password: %admin ALL = NOPASSWD: /usr/bin/apt-get

See sudoers man page for more detail.

fseto
A: 

sudo is open source, so you can compile your own version which takes the password as a command line parameter.

CSpangled
I would strongly advise against using a home-brewn version of such an important part of the operating system without a *very* good reason. (You'd have to manually apply and recompile every patch, etc.)
Heinzi