08409311b94dd4484ade65a43fd2d46da5c29403
[feisty_meow.git] / scripts / security / password_functions.sh
1 #!/bin/bash
2
3 # a set of useful functions for managing operations with passwords.
4 # a set of very simple operations, but the file needs to be protected from
5 # undesirable access.  a good way to do that is to make the file owned by
6 # root, and for it to have permssions of "600" (full access by owner only),
7 # and to only try to read the password file when in sudo mode.  the first
8 # two requirements are done automatically by the store_password function.
9
10 # load_password:
11 # provides a way to read a password out of a file.
12 # the return value is an echoed password, so this method should always be
13 # called from within a subshell, e.g.:
14 #    mypass="$(load_password /etc/glorp/secret_passcode)"
15 # the returned echo will be blank if the function failed.
16 function load_password()
17 {
18   local passfile="$1"; shift
19   if [ -z "$passfile" ]; then
20     echo 'The load_password function needs a filename to read the password from.'
21     return 1
22   fi
23   local passwd
24   read passwd < "$passfile"
25   echo "$passwd"
26 }
27
28 # stores a password into a password file.  the password file should be the
29 # first parameter and the password should be the second.
30 # this makes sure that only root can read the file.
31 function store_password()
32 {
33   local passfile="$1"; shift
34   local passwd="$1"; shift
35   if [ -z "$passfile" -o -z "$passwd" ]; then
36     echo '
37 The store_password function needs (1) the file to store the password into,
38 and (2) the password that should be stored.
39 '
40     return 1
41   fi
42
43   echo "$passwd" > "$passfile"
44   test_or_die "writing password into the file $passfile"
45
46   chown root:root "$passfile"
47   test_or_die "chowning the password file to root ownership for: $passfile"
48
49   chmod 600 "$passfile"
50   test_or_die "restricting permissions on password file for: $passfile"
51 }
52
53 # reads a password from the console, without echoing the letters when they
54 # are typed.  the prompt to show the user is required as the first parameter.
55 # the password read in is returned as an echo, like load_password above.
56 function read_password()
57 {
58   prompt="$1"; shift
59   echo -n "$prompt "
60   # turn off echo but remember former setting.
61   stty_orig=`stty -g`
62   stty -echo
63   read the_passwd
64   # turn echo back on.
65   stty $stty_orig
66   # return the password as an echo.
67   echo "$the_passwd"
68 }
69
70