2 # This should be sourced by bash (though we welcome changes to make it POSIX sh compliant)
4 # Shared sh functions for the monkeysphere
7 # Jameson Rollins <jrollins@finestructure.net>
8 # Jamie McClelland <jm@mayfirst.org>
9 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
11 # Copyright 2008, released under the GPL, version 3 or later
13 # all-caps variables are meant to be user supplied (ie. from config
14 # file) and are considered global
16 ########################################################################
20 SYSCONFIGDIR=${MONKEYSPHERE_SYSCONFIGDIR:-"/etc/monkeysphere"}
23 # monkeysphere version
30 KEYSERVER="pool.sks-keyservers.net"
32 # whether or not to check keyservers by defaul
33 CHECK_KEYSERVER="true"
35 # default monkeysphere user
36 MONKEYSPHERE_USER="monkeysphere"
38 # default about whether or not to prompt
41 ########################################################################
44 # failure function. exits with code 255, unless specified otherwise.
46 [ "$1" ] && echo "$1" >&2
50 # write output to stderr based on specified LOG_LEVEL the first
51 # parameter is the priority of the output, and everything else is what
52 # is echoed to stderr. If there is nothing else, then output comes
53 # from stdin, and is not prefaced by log prefix.
61 # don't include SILENT in alllevels: it's handled separately
62 # list in decreasing verbosity (all caps).
63 # separate with $IFS explicitly, since we do some fancy footwork
65 alllevels="DEBUG${IFS}VERBOSE${IFS}INFO${IFS}ERROR"
67 # translate lowers to uppers in global log level
68 LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
70 # just go ahead and return if the log level is silent
71 if [ "$LOG_LEVEL" = 'SILENT' ] ; then
75 for level in $alllevels ; do
76 if [ "$LOG_LEVEL" = "$level" ] ; then
80 if [ -z "$found" ] ; then
85 # get priority from first parameter, translating all lower to
87 priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
90 # scan over available levels
91 for level in $alllevels ; do
92 # output if the log level matches, set output to true
93 # this will output for all subsequent loops as well.
94 if [ "$LOG_LEVEL" = "$level" ] ; then
97 if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
108 # run command as monkeysphere user
109 su_monkeysphere_user() {
110 # our main goal here is to run the given command as the the
111 # monkeysphere user, but without prompting for any sort of
112 # authentication. If this is not possible, we should just fail.
114 # FIXME: our current implementation is overly restrictive, because
115 # there may be some su PAM configurations that would allow su
116 # "$MONKEYSPHERE_USER" -c "$@" to Just Work without prompting,
117 # allowing specific users to invoke commands which make use of
120 # chpst (from runit) would be nice to use, but we don't want to
121 # introduce an extra dependency just for this. This may be a
122 # candidate for re-factoring if we switch implementation languages.
125 # if monkeysphere user, run the command under bash
126 "$MONKEYSPHERE_USER")
130 # if root, su command as monkeysphere user
132 su "$MONKEYSPHERE_USER" -c "$@"
137 log error "non-privileged user."
142 # cut out all comments(#) and blank lines from standard input
144 grep -v -e "^[[:space:]]*#" -e '^$' "$1"
147 # cut a specified line from standard input
149 head --line="$1" "$2" | tail -1
152 # make a temporary directly
154 mktemp -d ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX
157 # this is a wrapper for doing lock functions.
159 # it lets us depend on either lockfile-progs (preferred) or procmail's
160 # lockfile, and should
162 local use_lockfileprogs=true
166 if ! ( which lockfile-create >/dev/null 2>/dev/null ) ; then
167 if ! ( which lockfile >/dev/null ); then
168 failure "Neither lockfile-create nor lockfile are in the path!"
175 if [ -n "$use_lockfileprogs" ] ; then
176 lockfile-create "$file" || failure "unable to lock '$file'"
178 lockfile -r 20 "${file}.lock" || failure "unable to lock '$file'"
180 log debug "lock created on '$file'."
183 if [ -n "$use_lockfileprogs" ] ; then
184 lockfile-touch --oneshot "$file"
188 log debug "lock touched on '$file'."
191 if [ -n "$use_lockfileprogs" ] ; then
192 lockfile-remove "$file"
196 log debug "lock removed on '$file'."
199 failure "bad argument for lock subfunction '$action'"
204 # for portability, between gnu date and BSD date.
205 # arguments should be: number longunits format
207 # e.g. advance_date 20 seconds +%F
215 # try things the GNU way first
216 if date -d "$number $longunits" "$format" >/dev/null 2>&1; then
217 date -d "$number $longunits" "$format"
219 # otherwise, convert to (a limited version of) BSD date syntax:
243 # this is a longshot, and will likely fail; oh well.
244 shortunits="$longunits"
246 date "-v+${number}${shortunits}" "$format"
251 # check that characters are in a string (in an AND fashion).
252 # used for checking key capability
253 # check_capability capability a [b...]
262 if echo "$usage" | grep -q -v "$capcheck" ; then
271 md5sum "$1" 2> /dev/null
274 # convert escaped characters in pipeline from gpg output back into
276 # FIXME: undo all escape character translation in with-colons gpg
282 # convert nasty chars into gpg-friendly form in pipeline
283 # FIXME: escape everything, not just colons!
288 # prompt for GPG-formatted expiration, and emit result on stdout
289 get_gpg_expiration() {
294 if [ -z "$keyExpire" ]; then
296 Please specify how long the key should be valid.
297 0 = key does not expire
298 <n> = key expires in n days
299 <n>w = key expires in n weeks
300 <n>m = key expires in n months
301 <n>y = key expires in n years
303 while [ -z "$keyExpire" ] ; do
304 read -p "Key is valid for? (0) " keyExpire
305 if ! test_gpg_expire ${keyExpire:=0} ; then
306 echo "invalid value" >&2
310 elif ! test_gpg_expire "$keyExpire" ; then
311 failure "invalid key expiration value '$keyExpire'."
317 passphrase_prompt() {
322 if [ "$DISPLAY" ] && which "${SSH_ASKPASS:-ssh-askpass}" >/dev/null; then
323 "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
325 read -s -p "$prompt" PASS
326 # Uses the builtin echo, so should not put the passphrase into
327 # the process table. I think. --dkg
328 echo "$PASS" > "$fifo"
332 test_gnu_dummy_s2k_extension() {
334 # this block contains a demonstration private key that has had the
335 # primary key stripped out using the GNU S2K extension known as
336 # "gnu-dummy" (see /usr/share/doc/gnupg/DETAILS.gz). The subkey is
337 # present in cleartext, however.
339 # openpgp2ssh will be able to deal with this based on whether the
340 # local copy of GnuTLS contains read_s2k support that can handle it.
342 # read up on that here:
344 # http://lists.gnu.org/archive/html/gnutls-devel/2008-08/msg00005.html
347 -----BEGIN PGP PRIVATE KEY BLOCK-----
348 Version: GnuPG v1.4.9 (GNU/Linux)
350 lQCVBEO3YdABBACRqqEnucag4+vyZny2M67Pai5+5suIRRvY+Ly8Ms5MvgCi3EVV
351 xT05O/+0ShiRaf+QicCOFrhbU9PZzzU+seEvkeW2UCu4dQfILkmj+HBEIltGnHr3
352 G0yegHj5pnqrcezERURf2e17gGFWX91cXB9Cm721FPXczuKraphKwCA9PwARAQAB
353 /gNlAkdOVQG0OURlbW9uc3RyYXRpb24gS2V5IGZvciBTMksgR05VIGV4dGVuc2lv
354 biAxMDAxIC0tIGdudS1kdW1teYi8BBMBAgAmBQJDt2HQAhsDBQkB4TOABgsJCAcD
355 AgQVAggDBBYCAwECHgECF4AACgkQQZUwSa4UDezTOQP/TMQXUVrWzHYZGopoPZ2+
356 ZS3qddiznBHsgb7MGYg1KlTiVJSroDUBCHIUJvdQKZV9zrzrFl47D07x6hGyUPHV
357 aZXvuITW8t1o5MMHkCy3pmJ2KgfDvdUxrBvLfgPMICA4c6zA0mWquee43syEW9NY
358 g3q61iPlQwD1J1kX1wlimLCdAdgEQ7dh0AEEANAwa63zlQbuy1Meliy8otwiOa+a
359 mH6pxxUgUNggjyjO5qx+rl25mMjvGIRX4/L1QwIBXJBVi3SgvJW1COZxZqBYqj9U
360 8HVT07mWKFEDf0rZLeUE2jTm16cF9fcW4DQhW+sfYm+hi2sY3HeMuwlUBK9KHfW2
361 +bGeDzVZ4pqfUEudABEBAAEAA/0bemib+wxub9IyVFUp7nPobjQC83qxLSNzrGI/
362 RHzgu/5CQi4tfLOnwbcQsLELfker2hYnjsLrT9PURqK4F7udrWEoZ1I1LymOtLG/
363 4tNZ7Mnul3wRC2tCn7FKx8sGJwGh/3li8vZ6ALVJAyOia5TZ/buX0+QZzt6+hPKk
364 7MU1WQIA4bUBjtrsqDwro94DvPj3/jBnMZbXr6WZIItLNeVDUcM8oHL807Am97K1
365 ueO/f6v1sGAHG6lVPTmtekqPSTWBfwIA7CGFvEyvSALfB8NUa6jtk27NCiw0csql
366 kuhCmwXGMVOiryKEfegkIahf2bAd/gnWHPrpWp7bUE20v8YoW22I4wIAhnm5Wr5Q
367 Sy7EHDUxmJm5TzadFp9gq08qNzHBpXSYXXJ3JuWcL1/awUqp3tE1I6zZ0hZ38Ia6
368 SdBMN88idnhDPqPoiKUEGAECAA8FAkO3YdACGyAFCQHhM4AACgkQQZUwSa4UDezm
369 vQP/ZhK+2ly9oI2z7ZcNC/BJRch0/ybQ3haahII8pXXmOThpZohr/LUgoWgCZdXg
370 vP6yiszNk2tIs8KphCAw7Lw/qzDC2hEORjWO4f46qk73RAgSqG/GyzI4ltWiDhqn
371 vnQCFl3+QFSe4zinqykHnLwGPMXv428d/ZjkIc2ju8dRsn4=
373 -----END PGP PRIVATE KEY BLOCK-----
374 " | openpgp2ssh 4129E89D17C1D591 >/dev/null 2>/dev/null
378 # remove all lines with specified string from specified file
387 if [ -z "$file" -o -z "$string" ] ; then
391 if [ ! -e "$file" ] ; then
395 # if the string is in the file...
396 if grep -q -F "$string" "$file" 2> /dev/null ; then
397 tempfile=$(mktemp "${file}.XXXXXXX") || \
398 failure "Unable to make temp file '${file}.XXXXXXX'"
400 # remove the line with the string, and return 0
401 grep -v -F "$string" "$file" >"$tempfile"
402 cat "$tempfile" > "$file"
411 # remove all lines with MonkeySphere strings in file
412 remove_monkeysphere_lines() {
418 if [ -z "$file" ] ; then
422 if [ ! -e "$file" ] ; then
426 tempfile=$(mktemp "${file}.XXXXXXX") || \
427 failure "Could not make temporary file '${file}.XXXXXXX'."
429 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
431 cat "$tempfile" > "$file"
435 # translate ssh-style path variables %h and %u
436 translate_ssh_variables() {
443 # get the user's home directory
444 userHome=$(getent passwd "$uname" | cut -d: -f6)
446 # translate '%u' to user name
447 path=${path/\%u/"$uname"}
448 # translate '%h' to user home directory
449 path=${path/\%h/"$userHome"}
454 # test that a string to conforms to GPG's expiration format
456 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
459 # check that a file is properly owned, and that all it's parent
460 # directories are not group/other writable
461 check_key_file_permissions() {
469 # function to check that the given permission corresponds to writability
477 log debug "checking path permission '$path'..."
479 # return 255 if cannot stat file
480 if ! stat=$(ls -ld "$path" 2>/dev/null) ; then
481 log error "could not stat path '$path'."
485 owner=$(echo "$stat" | awk '{ print $3 }')
486 gAccess=$(echo "$stat" | cut -c6)
487 oAccess=$(echo "$stat" | cut -c9)
489 # return 1 if path has invalid owner
490 if [ "$owner" != "$uname" -a "$owner" != 'root' ] ; then
491 log error "improper ownership on path '$path'."
495 # return 2 if path has group or other writability
496 if is_write "$gAccess" || is_write "$oAccess" ; then
497 log error "improper group or other writability on path '$path'."
501 # return zero if all clear, or go to next path
502 if [ "$path" = '/' ] ; then
505 check_key_file_permissions "$uname" $(dirname "$path")
509 ### CONVERSION UTILITIES
511 # output the ssh key for a given key ID
517 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
520 # output known_hosts line from ssh key
529 echo -n "$key" | tr -d '\n'
530 echo " MonkeySphere${DATE}"
533 # output authorized_keys line from ssh key
534 ssh2authorized_keys() {
541 echo -n "$key" | tr -d '\n'
542 echo " MonkeySphere${DATE} ${userID}"
545 # convert key from gpg to ssh known_hosts format
553 # NOTE: it seems that ssh-keygen -R removes all comment fields from
554 # all lines in the known_hosts file. why?
555 # NOTE: just in case, the COMMENT can be matched with the
557 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
559 gpg2ssh "$keyID" | tr -d '\n'
560 echo " MonkeySphere${DATE}"
563 # convert key from gpg to ssh authorized_keys format
564 gpg2authorized_keys() {
571 # NOTE: just in case, the COMMENT can be matched with the
573 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
574 gpg2ssh "$keyID" | tr -d '\n'
575 echo " MonkeySphere${DATE} ${userID}"
580 # retrieve all keys with given user id from keyserver
581 # FIXME: need to figure out how to retrieve all matching keys
582 # (not just first N (5 in this case))
587 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
593 log verbose " checking keyserver $KEYSERVER... "
595 gpg --quiet --batch --with-colons \
596 --command-fd 0 --keyserver "$KEYSERVER" \
597 --search ="$userID" > /dev/null 2>&1
603 ########################################################################
604 ### PROCESSING FUNCTIONS
606 # userid and key policy checking
607 # the following checks policy on the returned keys
608 # - checks that full key has appropriate valididy (u|f)
609 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
610 # - checks that requested user ID has appropriate validity
611 # (see /usr/share/doc/gnupg/DETAILS.gz)
612 # output is one line for every found key, in the following format:
616 # "flag" is an acceptability flag, 0 = ok, 1 = bad
617 # "sshKey" is the translated gpg key
619 # all log output must go to stderr, as stdout is used to pass the
620 # flag:sshKey to the calling function.
622 # expects global variable: "MODE"
625 local requiredCapability
626 local requiredPubCapability
641 # set the required key capability based on the mode
642 if [ "$MODE" = 'known_hosts' ] ; then
643 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
644 elif [ "$MODE" = 'authorized_keys' ] ; then
645 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
647 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
649 # fetch the user ID if necessary/requested
650 gpg_fetch_userid "$userID"
652 # output gpg info for (exact) userid and store
653 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
654 --with-fingerprint --with-fingerprint \
655 ="$userID" 2>/dev/null)
657 # if the gpg query return code is not 0, return 1
658 if [ "$?" -ne 0 ] ; then
659 log verbose " no primary keys found."
663 # loop over all lines in the gpg output and process.
664 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
665 while IFS=: read -r type validity keyid uidfpr usage ; do
666 # process based on record type
668 'pub') # primary keys
669 # new key, wipe the slate
676 log verbose " primary key found: $keyid"
678 # if overall key is not valid, skip
679 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
680 log debug " - unacceptable primary key validity ($validity)."
683 # if overall key is disabled, skip
684 if check_capability "$usage" 'D' ; then
685 log debug " - key disabled."
688 # if overall key capability is not ok, skip
689 if ! check_capability "$usage" $requiredPubCapability ; then
690 log debug " - unacceptable primary key capability ($usage)."
694 # mark overall key as ok
697 # mark primary key as ok if capability is ok
698 if check_capability "$usage" $requiredCapability ; then
703 if [ "$lastKey" != pub ] ; then
704 log verbose " ! got a user ID after a sub key?! user IDs should only follow primary keys!"
707 # if an acceptable user ID was already found, skip
708 if [ "$uidOK" = 'true' ] ; then
711 # if the user ID does matches...
712 if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
713 # and the user ID validity is ok
714 if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
715 # mark user ID acceptable
718 log debug " - unacceptable user ID validity ($validity)."
724 # output a line for the primary key
726 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
727 log verbose " * acceptable primary key."
728 if [ -z "$sshKey" ] ; then
729 log error " ! primary key could not be translated (not RSA or DSA?)."
734 log debug " - unacceptable primary key."
735 if [ -z "$sshKey" ] ; then
736 log debug " ! primary key could not be translated (not RSA or DSA?)."
743 # unset acceptability of last key
748 # don't bother with sub keys if the primary key is not valid
749 if [ "$keyOK" != true ] ; then
753 # don't bother with sub keys if no user ID is acceptable:
754 if [ "$uidOK" != true ] ; then
758 # if sub key validity is not ok, skip
759 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
760 log debug " - unacceptable sub key validity ($validity)."
763 # if sub key capability is not ok, skip
764 if ! check_capability "$usage" $requiredCapability ; then
765 log debug " - unacceptable sub key capability ($usage)."
772 'fpr') # key fingerprint
773 fingerprint="$uidfpr"
775 sshKey=$(gpg2ssh "$fingerprint")
777 # if the last key was the pub key, skip
778 if [ "$lastKey" = pub ] ; then
782 # output a line for the sub key
784 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
785 log verbose " * acceptable sub key."
786 if [ -z "$sshKey" ] ; then
787 log error " ! sub key could not be translated (not RSA or DSA?)."
792 log debug " - unacceptable sub key."
793 if [ -z "$sshKey" ] ; then
794 log debug " ! sub key could not be translated (not RSA or DSA?)."
801 done | sort -t: -k1 -n -r
802 # NOTE: this last sort is important so that the "good" keys (key
803 # flag '0') come last. This is so that they take precedence when
804 # being processed in the key files over "bad" keys (key flag '1')
807 # process a single host in the known_host file
808 process_host_known_hosts() {
818 # set the key processing mode
819 export MODE='known_hosts'
822 userID="ssh://${host}"
824 log verbose "processing: $host"
830 for line in $(process_user_id "${userID}") ; do
831 # note that key was found
834 ok=$(echo "$line" | cut -d: -f1)
835 sshKey=$(echo "$line" | cut -d: -f2)
837 if [ -z "$sshKey" ] ; then
841 # remove any old host key line, and note if removed nothing is
843 remove_line "$KNOWN_HOSTS" "$sshKey" || noKey=true
845 # if key OK, add new host line
846 if [ "$ok" -eq '0' ] ; then
847 # note that key was found ok
848 nKeysOK=$((nKeysOK+1))
851 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
852 # FIXME: this is really hackish cause ssh-keygen won't
853 # hash from stdin to stdout
854 tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
855 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
856 ssh-keygen -H -f "$tmpfile" 2> /dev/null
857 cat "$tmpfile" >> "$KNOWN_HOSTS"
858 rm -f "$tmpfile" "${tmpfile}.old"
860 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
863 # log if this is a new key to the known_hosts file
864 if [ "$noKey" ] ; then
865 log info "* new key for $host added to known_hosts file."
870 # if at least one key was found...
871 if [ "$nKeys" -gt 0 ] ; then
872 # if ok keys were found, return 0
873 if [ "$nKeysOK" -gt 0 ] ; then
879 # if no keys were found, return 1
885 # update the known_hosts file for a set of hosts listed on command
887 update_known_hosts() {
894 # the number of hosts specified on command line
900 # touch the known_hosts file so that the file permission check
901 # below won't fail upon not finding the file
902 (umask 0022 && touch "$KNOWN_HOSTS")
904 # check permissions on the known_hosts file path
905 check_key_file_permissions "$USER" "$KNOWN_HOSTS" || failure
907 # create a lockfile on known_hosts:
908 lock create "$KNOWN_HOSTS"
909 # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
910 trap "lock remove $KNOWN_HOSTS" EXIT
912 # note pre update file checksum
913 fileCheck="$(file_hash "$KNOWN_HOSTS")"
917 process_host_known_hosts "$host"
921 nHostsOK=$((nHostsOK+1))
924 nHostsBAD=$((nHostsBAD+1))
928 # touch the lockfile, for good measure.
929 lock touch "$KNOWN_HOSTS"
932 # remove the lockfile and the trap
933 lock remove "$KNOWN_HOSTS"
936 # note if the known_hosts file was updated
937 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
938 log debug "known_hosts file updated."
941 # if an acceptable host was found, return 0
942 if [ "$nHostsOK" -gt 0 ] ; then
944 # else if no ok hosts were found...
946 # if no bad host were found then no hosts were found at all,
948 if [ "$nHostsBAD" -eq 0 ] ; then
950 # else if at least one bad host was found, return 2
957 # process hosts from a known_hosts file
958 process_known_hosts() {
961 # exit if the known_hosts file does not exist
962 if [ ! -e "$KNOWN_HOSTS" ] ; then
963 failure "known_hosts file '$KNOWN_HOSTS' does not exist."
966 log debug "processing known_hosts file..."
968 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
970 if [ -z "$hosts" ] ; then
971 log debug "no hosts to process."
975 # take all the hosts from the known_hosts file (first
976 # field), grep out all the hashed hosts (lines starting
978 update_known_hosts $hosts
981 # process uids for the authorized_keys file
982 process_uid_authorized_keys() {
989 # set the key processing mode
990 export MODE='authorized_keys'
994 log verbose "processing: $userID"
1000 for line in $(process_user_id "$userID") ; do
1001 # note that key was found
1004 ok=$(echo "$line" | cut -d: -f1)
1005 sshKey=$(echo "$line" | cut -d: -f2)
1007 if [ -z "$sshKey" ] ; then
1011 # remove the old host key line
1012 remove_line "$AUTHORIZED_KEYS" "$sshKey"
1014 # if key OK, add new host line
1015 if [ "$ok" -eq '0' ] ; then
1016 # note that key was found ok
1017 nKeysOK=$((nKeysOK+1))
1019 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
1023 # if at least one key was found...
1024 if [ "$nKeys" -gt 0 ] ; then
1025 # if ok keys were found, return 0
1026 if [ "$nKeysOK" -gt 0 ] ; then
1032 # if no keys were found, return 1
1038 # update the authorized_keys files from a list of user IDs on command
1040 update_authorized_keys() {
1047 # the number of ids specified on command line
1053 # check permissions on the authorized_keys file path
1054 check_key_file_permissions "$USER" "$AUTHORIZED_KEYS" || failure
1056 # create a lockfile on authorized_keys
1057 lock create "$AUTHORIZED_KEYS"
1058 # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
1059 trap "lock remove $AUTHORIZED_KEYS" EXIT
1061 # note pre update file checksum
1062 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
1064 # remove any monkeysphere lines from authorized_keys file
1065 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
1068 # process the user ID, change return code if key not found for
1070 process_uid_authorized_keys "$userID"
1075 nIDsOK=$((nIDsOK+1))
1078 nIDsBAD=$((nIDsBAD+1))
1082 # touch the lockfile, for good measure.
1083 lock touch "$AUTHORIZED_KEYS"
1086 # remove the lockfile and the trap
1087 lock remove "$AUTHORIZED_KEYS"
1092 # note if the authorized_keys file was updated
1093 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
1094 log debug "authorized_keys file updated."
1097 # if an acceptable id was found, return 0
1098 if [ "$nIDsOK" -gt 0 ] ; then
1100 # else if no ok ids were found...
1102 # if no bad ids were found then no ids were found at all, and
1104 if [ "$nIDsBAD" -eq 0 ] ; then
1106 # else if at least one bad id was found, return 2
1113 # process an authorized_user_ids file for authorized_keys
1114 process_authorized_user_ids() {
1119 authorizedUserIDs="$1"
1121 # exit if the authorized_user_ids file is empty
1122 if [ ! -e "$authorizedUserIDs" ] ; then
1123 failure "authorized_user_ids file '$authorizedUserIDs' does not exist."
1126 # check permissions on the authorized_user_ids file path
1127 check_key_file_permissions "$USER" "$authorizedUserIDs" || failure
1129 log debug "processing authorized_user_ids file..."
1131 if ! meat "$authorizedUserIDs" > /dev/null ; then
1132 log debug " no user IDs to process."
1138 # extract user IDs from authorized_user_ids file
1140 for line in $(meat "$authorizedUserIDs") ; do
1141 userIDs["$nline"]="$line"
1145 update_authorized_keys "${userIDs[@]}"