3 # Shared sh functions for the monkeysphere
6 # Jameson Rollins <jrollins@fifthhorseman.net>
7 # Jamie McClelland <jm@mayfirst.org>
8 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
10 # Copyright 2008, released under the GPL, version 3 or later
12 # all-caps variables are meant to be user supplied (ie. from config
13 # file) and are considered global
15 ########################################################################
19 ETC="/etc/monkeysphere"
22 ########################################################################
25 # failure function. exits with code 255, unless specified otherwise.
31 # write output to stderr based on specified LOG_LEVEL the first
32 # parameter is the priority of the output, and everything else is what
41 # don't include SILENT in alllevels: it's handled separately
42 # list in decreasing verbosity (all caps).
43 # separate with $IFS explicitly, since we do some fancy footwork
45 alllevels="DEBUG${IFS}VERBOSE${IFS}INFO${IFS}ERROR"
47 # translate lowers to uppers in global log level
48 LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
50 # just go ahead and return if the log level is silent
51 if [ "$LOG_LEVEL" = 'SILENT' ] ; then
55 for level in $alllevels ; do
56 if [ "$LOG_LEVEL" = "$level" ] ; then
60 if [ -z "$found" ] ; then
65 # get priority from first parameter, translating all lower to
67 priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
70 # scan over available levels
71 for level in $alllevels ; do
72 # output if the log level matches, set output to true
73 # this will output for all subsequent loops as well.
74 if [ "$LOG_LEVEL" = "$level" ] ; then
77 if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
84 # cut out all comments(#) and blank lines from standard input
86 grep -v -e "^[[:space:]]*#" -e '^$' "$1"
89 # cut a specified line from standard input
91 head --line="$1" "$2" | tail -1
94 # this is a wrapper for doing lock functions.
96 # it lets us depend on either lockfile-progs (preferred) or procmail's
97 # lockfile, and should
99 local use_lockfileprogs=true
103 if ! ( which lockfile-create >/dev/null 2>/dev/null ) ; then
104 if ! ( which lockfile >/dev/null ); then
105 failure "Neither lockfile-create nor lockfile are in the path!"
111 if [ -n "$use_lockfileprogs" ] ; then
112 lockfile-create "$file" || failure "unable to lock '$file'"
114 lockfile -r 20 "${file}.lock" || failure "unable to lock '$file'"
118 if [ -n "$use_lockfileprogs" ] ; then
119 lockfile-touch "$file"
125 if [ -n "$use_lockfileprogs" ] ; then
126 lockfile-remove "$file"
132 failure "bad argument for lock subfunction '$action'"
136 # check that characters are in a string (in an AND fashion).
137 # used for checking key capability
138 # check_capability capability a [b...]
147 if echo "$usage" | grep -q -v "$capcheck" ; then
156 md5sum "$1" 2> /dev/null
159 # convert escaped characters in pipeline from gpg output back into
161 # FIXME: undo all escape character translation in with-colons gpg
167 # convert nasty chars into gpg-friendly form in pipeline
168 # FIXME: escape everything, not just colons!
173 # prompt for GPG-formatted expiration, and emit result on stdout
174 get_gpg_expiration() {
179 if [ -z "$keyExpire" ]; then
181 Please specify how long the key should be valid.
182 0 = key does not expire
183 <n> = key expires in n days
184 <n>w = key expires in n weeks
185 <n>m = key expires in n months
186 <n>y = key expires in n years
188 while [ -z "$keyExpire" ] ; do
189 read -p "Key is valid for? (0) " keyExpire
190 if ! test_gpg_expire ${keyExpire:=0} ; then
191 echo "invalid value" >&2
195 elif ! test_gpg_expire "$keyExpire" ; then
196 failure "invalid key expiration value '$keyExpire'."
202 passphrase_prompt() {
207 if [ "$DISPLAY" ] && which "${SSH_ASKPASS:-ssh-askpass}" >/dev/null; then
208 "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
210 read -s -p "$prompt" PASS
211 # Uses the builtin echo, so should not put the passphrase into
212 # the process table. I think. --dkg
213 echo "$PASS" > "$fifo"
217 test_gnu_dummy_s2k_extension() {
219 # this block contains a demonstration private key that has had the
220 # primary key stripped out using the GNU S2K extension known as
221 # "gnu-dummy" (see /usr/share/doc/gnupg/DETAILS.gz). The subkey is
222 # present in cleartext, however.
224 # openpgp2ssh will be able to deal with this based on whether the
225 # local copy of GnuTLS contains read_s2k support that can handle it.
227 # read up on that here:
229 # http://lists.gnu.org/archive/html/gnutls-devel/2008-08/msg00005.html
232 -----BEGIN PGP PRIVATE KEY BLOCK-----
233 Version: GnuPG v1.4.9 (GNU/Linux)
235 lQCVBEO3YdABBACRqqEnucag4+vyZny2M67Pai5+5suIRRvY+Ly8Ms5MvgCi3EVV
236 xT05O/+0ShiRaf+QicCOFrhbU9PZzzU+seEvkeW2UCu4dQfILkmj+HBEIltGnHr3
237 G0yegHj5pnqrcezERURf2e17gGFWX91cXB9Cm721FPXczuKraphKwCA9PwARAQAB
238 /gNlAkdOVQG0OURlbW9uc3RyYXRpb24gS2V5IGZvciBTMksgR05VIGV4dGVuc2lv
239 biAxMDAxIC0tIGdudS1kdW1teYi8BBMBAgAmBQJDt2HQAhsDBQkB4TOABgsJCAcD
240 AgQVAggDBBYCAwECHgECF4AACgkQQZUwSa4UDezTOQP/TMQXUVrWzHYZGopoPZ2+
241 ZS3qddiznBHsgb7MGYg1KlTiVJSroDUBCHIUJvdQKZV9zrzrFl47D07x6hGyUPHV
242 aZXvuITW8t1o5MMHkCy3pmJ2KgfDvdUxrBvLfgPMICA4c6zA0mWquee43syEW9NY
243 g3q61iPlQwD1J1kX1wlimLCdAdgEQ7dh0AEEANAwa63zlQbuy1Meliy8otwiOa+a
244 mH6pxxUgUNggjyjO5qx+rl25mMjvGIRX4/L1QwIBXJBVi3SgvJW1COZxZqBYqj9U
245 8HVT07mWKFEDf0rZLeUE2jTm16cF9fcW4DQhW+sfYm+hi2sY3HeMuwlUBK9KHfW2
246 +bGeDzVZ4pqfUEudABEBAAEAA/0bemib+wxub9IyVFUp7nPobjQC83qxLSNzrGI/
247 RHzgu/5CQi4tfLOnwbcQsLELfker2hYnjsLrT9PURqK4F7udrWEoZ1I1LymOtLG/
248 4tNZ7Mnul3wRC2tCn7FKx8sGJwGh/3li8vZ6ALVJAyOia5TZ/buX0+QZzt6+hPKk
249 7MU1WQIA4bUBjtrsqDwro94DvPj3/jBnMZbXr6WZIItLNeVDUcM8oHL807Am97K1
250 ueO/f6v1sGAHG6lVPTmtekqPSTWBfwIA7CGFvEyvSALfB8NUa6jtk27NCiw0csql
251 kuhCmwXGMVOiryKEfegkIahf2bAd/gnWHPrpWp7bUE20v8YoW22I4wIAhnm5Wr5Q
252 Sy7EHDUxmJm5TzadFp9gq08qNzHBpXSYXXJ3JuWcL1/awUqp3tE1I6zZ0hZ38Ia6
253 SdBMN88idnhDPqPoiKUEGAECAA8FAkO3YdACGyAFCQHhM4AACgkQQZUwSa4UDezm
254 vQP/ZhK+2ly9oI2z7ZcNC/BJRch0/ybQ3haahII8pXXmOThpZohr/LUgoWgCZdXg
255 vP6yiszNk2tIs8KphCAw7Lw/qzDC2hEORjWO4f46qk73RAgSqG/GyzI4ltWiDhqn
256 vnQCFl3+QFSe4zinqykHnLwGPMXv428d/ZjkIc2ju8dRsn4=
258 -----END PGP PRIVATE KEY BLOCK-----
259 " | openpgp2ssh 4129E89D17C1D591 >/dev/null 2>/dev/null
263 # remove all lines with specified string from specified file
272 if [ -z "$file" -o -z "$string" ] ; then
276 if [ ! -e "$file" ] ; then
280 # if the string is in the file...
281 if grep -q -F "$string" "$file" 2> /dev/null ; then
282 tempfile=$(mktemp "${file}.XXXXXXX") || \
283 failure "Unable to make temp file '${file}.XXXXXXX'"
285 # remove the line with the string, and return 0
286 grep -v -F "$string" "$file" >"$tempfile"
287 cat "$tempfile" > "$file"
296 # remove all lines with MonkeySphere strings in file
297 remove_monkeysphere_lines() {
303 if [ -z "$file" ] ; then
307 if [ ! -e "$file" ] ; then
311 tempfile=$(mktemp "${file}.XXXXXXX") || \
312 failure "Could not make temporary file '${file}.XXXXXXX'."
314 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
316 cat "$tempfile" > "$file"
320 # translate ssh-style path variables %h and %u
321 translate_ssh_variables() {
328 # get the user's home directory
329 userHome=$(getent passwd "$uname" | cut -d: -f6)
331 # translate '%u' to user name
332 path=${path/\%u/"$uname"}
333 # translate '%h' to user home directory
334 path=${path/\%h/"$userHome"}
339 # test that a string to conforms to GPG's expiration format
341 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
344 # check that a file is properly owned, and that all it's parent
345 # directories are not group/other writable
346 check_key_file_permissions() {
353 # function to check that an octal corresponds to writability
355 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
361 # return 0 is path does not exist
362 [ -e "$path" ] || return 0
364 owner=$(stat --format '%U' "$path")
365 access=$(stat --format '%a' "$path")
366 gAccess=$(echo "$access" | cut -c2)
367 oAccess=$(echo "$access" | cut -c3)
370 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
374 # check group/other writability
375 if is_write "$gAccess" || is_write "$oAccess" ; then
379 if [ "$path" = '/' ] ; then
382 check_key_file_permissions $(dirname "$path")
386 ### CONVERSION UTILITIES
388 # output the ssh key for a given key ID
394 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
397 # output known_hosts line from ssh key
406 echo -n "$key" | tr -d '\n'
407 echo " MonkeySphere${DATE}"
410 # output authorized_keys line from ssh key
411 ssh2authorized_keys() {
418 echo -n "$key" | tr -d '\n'
419 echo " MonkeySphere${DATE} ${userID}"
422 # convert key from gpg to ssh known_hosts format
430 # NOTE: it seems that ssh-keygen -R removes all comment fields from
431 # all lines in the known_hosts file. why?
432 # NOTE: just in case, the COMMENT can be matched with the
434 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
436 gpg2ssh "$keyID" | tr -d '\n'
437 echo " MonkeySphere${DATE}"
440 # convert key from gpg to ssh authorized_keys format
441 gpg2authorized_keys() {
448 # NOTE: just in case, the COMMENT can be matched with the
450 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
451 gpg2ssh "$keyID" | tr -d '\n'
452 echo " MonkeySphere${DATE} ${userID}"
457 # retrieve all keys with given user id from keyserver
458 # FIXME: need to figure out how to retrieve all matching keys
459 # (not just first N (5 in this case))
464 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
470 log info " checking keyserver $KEYSERVER... "
472 gpg --quiet --batch --with-colons \
473 --command-fd 0 --keyserver "$KEYSERVER" \
474 --search ="$userID" > /dev/null 2>&1
477 # if the user is the monkeysphere user, then update the
478 # monkeysphere user's trustdb
479 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
480 gpg_authentication "--check-trustdb" > /dev/null 2>&1
486 ########################################################################
487 ### PROCESSING FUNCTIONS
489 # userid and key policy checking
490 # the following checks policy on the returned keys
491 # - checks that full key has appropriate valididy (u|f)
492 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
493 # - checks that requested user ID has appropriate validity
494 # (see /usr/share/doc/gnupg/DETAILS.gz)
495 # output is one line for every found key, in the following format:
499 # "flag" is an acceptability flag, 0 = ok, 1 = bad
500 # "sshKey" is the translated gpg key
502 # all log output must go to stderr, as stdout is used to pass the
503 # flag:sshKey to the calling function.
505 # expects global variable: "MODE"
508 local requiredCapability
509 local requiredPubCapability
524 # set the required key capability based on the mode
525 if [ "$MODE" = 'known_hosts' ] ; then
526 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
527 elif [ "$MODE" = 'authorized_keys' ] ; then
528 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
530 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
532 # fetch the user ID if necessary/requested
533 gpg_fetch_userid "$userID"
535 # output gpg info for (exact) userid and store
536 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
537 --with-fingerprint --with-fingerprint \
538 ="$userID" 2>/dev/null)
540 # if the gpg query return code is not 0, return 1
541 if [ "$?" -ne 0 ] ; then
542 log verbose " no primary keys found."
546 # loop over all lines in the gpg output and process.
547 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
548 while IFS=: read -r type validity keyid uidfpr usage ; do
549 # process based on record type
551 'pub') # primary keys
552 # new key, wipe the slate
559 log verbose " primary key found: $keyid"
561 # if overall key is not valid, skip
562 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
563 log error " - unacceptable primary key validity ($validity)."
566 # if overall key is disabled, skip
567 if check_capability "$usage" 'D' ; then
568 log error " - key disabled."
571 # if overall key capability is not ok, skip
572 if ! check_capability "$usage" $requiredPubCapability ; then
573 log error " - unacceptable primary key capability ($usage)."
577 # mark overall key as ok
580 # mark primary key as ok if capability is ok
581 if check_capability "$usage" $requiredCapability ; then
586 if [ "$lastKey" != pub ] ; then
587 log error " - got a user ID after a sub key?! user IDs should only follow primary keys!"
590 # if an acceptable user ID was already found, skip
591 if [ "$uidOK" = 'true' ] ; then
594 # if the user ID does matches...
595 if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
596 # and the user ID validity is ok
597 if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
598 # mark user ID acceptable
605 # output a line for the primary key
607 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
608 log verbose " * acceptable primary key."
609 if [ -z "$sshKey" ] ; then
610 log error " ! primary key could not be translated (not RSA or DSA?)."
615 log error " - unacceptable primary key."
616 if [ -z "$sshKey" ] ; then
617 log error " ! primary key could not be translated (not RSA or DSA?)."
624 # unset acceptability of last key
629 # don't bother with sub keys if the primary key is not valid
630 if [ "$keyOK" != true ] ; then
634 # don't bother with sub keys if no user ID is acceptable:
635 if [ "$uidOK" != true ] ; then
639 # if sub key validity is not ok, skip
640 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
643 # if sub key capability is not ok, skip
644 if ! check_capability "$usage" $requiredCapability ; then
651 'fpr') # key fingerprint
652 fingerprint="$uidfpr"
654 sshKey=$(gpg2ssh "$fingerprint")
656 # if the last key was the pub key, skip
657 if [ "$lastKey" = pub ] ; then
661 # output a line for the sub key
663 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
664 log verbose " * acceptable sub key."
665 if [ -z "$sshKey" ] ; then
666 log error " ! sub key could not be translated (not RSA or DSA?)."
671 log error " - unacceptable sub key."
672 if [ -z "$sshKey" ] ; then
673 log error " ! sub key could not be translated (not RSA or DSA?)."
680 done | sort -t: -k1 -n -r
681 # NOTE: this last sort is important so that the "good" keys (key
682 # flag '0') come last. This is so that they take precedence when
683 # being processed in the key files over "bad" keys (key flag '1')
686 # process a single host in the known_host file
687 process_host_known_hosts() {
697 userID="ssh://${host}"
699 log verbose "processing: $host"
705 for line in $(process_user_id "${userID}") ; do
706 # note that key was found
709 ok=$(echo "$line" | cut -d: -f1)
710 sshKey=$(echo "$line" | cut -d: -f2)
712 if [ -z "$sshKey" ] ; then
716 # remove the old host key line, and note if removed
717 remove_line "$KNOWN_HOSTS" "$sshKey"
719 # if key OK, add new host line
720 if [ "$ok" -eq '0' ] ; then
721 # note that key was found ok
722 nKeysOK=$((nKeysOK+1))
725 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
726 # FIXME: this is really hackish cause ssh-keygen won't
727 # hash from stdin to stdout
729 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
730 ssh-keygen -H -f "$tmpfile" 2> /dev/null
731 cat "$tmpfile" >> "$KNOWN_HOSTS"
732 rm -f "$tmpfile" "${tmpfile}.old"
734 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
739 # if at least one key was found...
740 if [ "$nKeys" -gt 0 ] ; then
741 # if ok keys were found, return 0
742 if [ "$nKeysOK" -gt 0 ] ; then
748 # if no keys were found, return 1
754 # update the known_hosts file for a set of hosts listed on command
756 update_known_hosts() {
763 # the number of hosts specified on command line
769 # create a lockfile on known_hosts:
770 lock create "$KNOWN_HOSTS"
771 # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
772 trap "lock remove $KNOWN_HOSTS" EXIT
774 # note pre update file checksum
775 fileCheck="$(file_hash "$KNOWN_HOSTS")"
779 process_host_known_hosts "$host"
783 nHostsOK=$((nHostsOK+1))
786 nHostsBAD=$((nHostsBAD+1))
790 # touch the lockfile, for good measure.
791 lock touch --oneshot "$KNOWN_HOSTS"
794 # remove the lockfile and the trap
795 lock remove "$KNOWN_HOSTS"
798 # note if the known_hosts file was updated
799 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
800 log verbose "known_hosts file updated."
803 # if an acceptable host was found, return 0
804 if [ "$nHostsOK" -gt 0 ] ; then
806 # else if no ok hosts were found...
808 # if no bad host were found then no hosts were found at all,
810 if [ "$nHostsBAD" -eq 0 ] ; then
812 # else if at least one bad host was found, return 2
819 # process hosts from a known_hosts file
820 process_known_hosts() {
823 log verbose "processing known_hosts file..."
825 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
827 if [ -z "$hosts" ] ; then
828 log error "no hosts to process."
832 # take all the hosts from the known_hosts file (first
833 # field), grep out all the hashed hosts (lines starting
835 update_known_hosts $hosts
838 # process uids for the authorized_keys file
839 process_uid_authorized_keys() {
848 log verbose "processing: $userID"
854 for line in $(process_user_id "$userID") ; do
855 # note that key was found
858 ok=$(echo "$line" | cut -d: -f1)
859 sshKey=$(echo "$line" | cut -d: -f2)
861 if [ -z "$sshKey" ] ; then
865 # remove the old host key line
866 remove_line "$AUTHORIZED_KEYS" "$sshKey"
868 # if key OK, add new host line
869 if [ "$ok" -eq '0' ] ; then
870 # note that key was found ok
871 nKeysOK=$((nKeysOK+1))
873 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
877 # if at least one key was found...
878 if [ "$nKeys" -gt 0 ] ; then
879 # if ok keys were found, return 0
880 if [ "$nKeysOK" -gt 0 ] ; then
886 # if no keys were found, return 1
892 # update the authorized_keys files from a list of user IDs on command
894 update_authorized_keys() {
901 # the number of ids specified on command line
907 # create a lockfile on authorized_keys
908 lock create "$AUTHORIZED_KEYS"
909 # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
910 trap "lock remove $AUTHORIZED_KEYS" EXIT
912 # note pre update file checksum
913 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
915 # remove any monkeysphere lines from authorized_keys file
916 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
919 # process the user ID, change return code if key not found for
921 process_uid_authorized_keys "$userID"
929 nIDsBAD=$((nIDsBAD+1))
933 # touch the lockfile, for good measure.
934 lock touch --oneshot "$AUTHORIZED_KEYS"
937 # remove the lockfile and the trap
938 lock remove "$AUTHORIZED_KEYS"
941 # note if the authorized_keys file was updated
942 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
943 log verbose "authorized_keys file updated."
946 # if an acceptable id was found, return 0
947 if [ "$nIDsOK" -gt 0 ] ; then
949 # else if no ok ids were found...
951 # if no bad ids were found then no ids were found at all, and
953 if [ "$nIDsBAD" -eq 0 ] ; then
955 # else if at least one bad id was found, return 2
962 # process an authorized_user_ids file for authorized_keys
963 process_authorized_user_ids() {
968 authorizedUserIDs="$1"
970 log verbose "processing authorized_user_ids file..."
972 if ! meat "$authorizedUserIDs" > /dev/null ; then
973 log error "no user IDs to process."
979 # extract user IDs from authorized_user_ids file
981 for line in $(meat "$authorizedUserIDs") ; do
982 userIDs["$nline"]="$line"
986 update_authorized_keys "${userIDs[@]}"