53

I want to secure the execution of a program with a password. How can I ask the user to enter a password without echoing it?

1

3 Answers 3

86

This command will read into var pw from stdin (with echo disabled):

IFS= read -r -s -p 'Password: ' pw
echo

The last echo adds a newline to the terminal output (otherwise next commands would appear in the same line as the Password: prompt.

Unsetting IFS allows for leading and trailing whitespace in passwords (which may be supported in some environments, so best to support it during your script's input of the user credentials).

If you want, you can verify that the above works by running it with a fake password that includes whitespace and then printing the variable's contents into hexdump:

printf '%s' "$pw" | hexdump -C

Note: don't use with real passwords as it dumps to the console!

HT: Ron DuPlain for this additional information on IFS unsetting.

Sign up to request clarification or add additional context in comments.

2 Comments

Are there any disadvantages if I used this instead of the accepted answer?
@Triztian yes, the above will probably only work in Bash. The accepted answer should work on most (all?) shells.
58
stty_orig=$(stty -g) # save original terminal setting.
stty -echo           # turn-off echoing.
IFS= read -r passwd  # read the password
stty "$stty_orig"    # restore terminal setting.

Comments

5

If you need to grab a passwd to supply as a paramter to a program, then unicorns advice to just turn off the echo is good.
Having a passwd check in the script doesn't work - if the user can execute the bash script they also have permission to read it and see the passwd.

If you want to only allow people with a passwd to run a program then the secure way is to create a new user account that owns the program and have a script that uses 'sudo' to run the program as that user - it will prompt for the users passwd in a secure way.

2 Comments

One might precompute the checksum of the password and store it in the script instead of the plaintext and test the checksum of the input against that. It can still be broken, though, but less easily.
In which case you just simply copy the script to somewhere you have write permission, and remove the check.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.