3 # Shared sh functions for the monkeysphere
6 # Jameson Rollins <jrollins@fifthhorseman.net>
8 # Copyright 2008, released under the GPL, version 3 or later
10 # all-caps variables are meant to be user supplied (ie. from config
11 # file) and are considered global
13 ########################################################################
17 ETC="/etc/monkeysphere"
20 ########################################################################
23 # failure function. exits with code 255, unless specified otherwise.
29 # write output to stderr
39 # cut out all comments(#) and blank lines from standard input
41 grep -v -e "^[[:space:]]*#" -e '^$' "$1"
44 # cut a specified line from standard input
46 head --line="$1" "$2" | tail -1
49 # check that characters are in a string (in an AND fashion).
50 # used for checking key capability
51 # check_capability capability a [b...]
60 if echo "$usage" | grep -q -v "$capcheck" ; then
69 md5sum "$1" 2> /dev/null
72 # convert escaped characters from gpg output back into original
74 # FIXME: undo all escape character translation in with-colons gpg output
76 echo "$1" | sed 's/\\x3a/:/g'
79 # remove all lines with specified string from specified file
87 if [ -z "$file" -o -z "$string" ] ; then
91 if [ ! -e "$file" ] ; then
95 # if the string is in the file...
96 if grep -q -F "$string" "$file" 2> /dev/null ; then
97 # remove the line with the string, and return 0
98 grep -v -F "$string" "$file" | sponge "$file"
106 # remove all lines with MonkeySphere strings in file
107 remove_monkeysphere_lines() {
112 if [ -z "$file" ] ; then
116 if [ ! -e "$file" ] ; then
120 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
121 "$file" | sponge "$file"
124 # translate ssh-style path variables %h and %u
125 translate_ssh_variables() {
132 # get the user's home directory
133 userHome=$(getent passwd "$uname" | cut -d: -f6)
135 # translate '%u' to user name
136 path=${path/\%u/"$uname"}
137 # translate '%h' to user home directory
138 path=${path/\%h/"$userHome"}
143 # test that a string to conforms to GPG's expiration format
145 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
148 # check that a file is properly owned, and that all it's parent
149 # directories are not group/other writable
150 check_key_file_permissions() {
157 # function to check that an octal corresponds to writability
159 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
165 # return 0 is path does not exist
166 [ -e "$path" ] || return 0
168 owner=$(stat --format '%U' "$path")
169 access=$(stat --format '%a' "$path")
170 gAccess=$(echo "$access" | cut -c2)
171 oAccess=$(echo "$access" | cut -c3)
174 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
178 # check group/other writability
179 if is_write "$gAccess" || is_write "$oAccess" ; then
183 if [ "$path" = '/' ] ; then
186 check_key_file_permissions $(dirname "$path")
190 ### CONVERSION UTILITIES
192 # output the ssh key for a given key ID
198 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
201 # output known_hosts line from ssh key
210 echo -n "$key" | tr -d '\n'
211 echo " MonkeySphere${DATE}"
214 # output authorized_keys line from ssh key
215 ssh2authorized_keys() {
222 echo -n "$key" | tr -d '\n'
223 echo " MonkeySphere${DATE} ${userID}"
226 # convert key from gpg to ssh known_hosts format
234 # NOTE: it seems that ssh-keygen -R removes all comment fields from
235 # all lines in the known_hosts file. why?
236 # NOTE: just in case, the COMMENT can be matched with the
238 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
240 gpg2ssh "$keyID" | tr -d '\n'
241 echo " MonkeySphere${DATE}"
244 # convert key from gpg to ssh authorized_keys format
245 gpg2authorized_keys() {
252 # NOTE: just in case, the COMMENT can be matched with the
254 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
255 gpg2ssh "$keyID" | tr -d '\n'
256 echo " MonkeySphere${DATE} ${userID}"
261 # retrieve all keys with given user id from keyserver
262 # FIXME: need to figure out how to retrieve all matching keys
263 # (not just first N (5 in this case))
268 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
274 log -n " checking keyserver $KEYSERVER... "
276 gpg --quiet --batch --with-colons \
277 --command-fd 0 --keyserver "$KEYSERVER" \
278 --search ="$userID" > /dev/null 2>&1
282 # if the user is the monkeysphere user, then update the
283 # monkeysphere user's trustdb
284 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
285 gpg_authentication "--check-trustdb" > /dev/null 2>&1
291 ########################################################################
292 ### PROCESSING FUNCTIONS
294 # userid and key policy checking
295 # the following checks policy on the returned keys
296 # - checks that full key has appropriate valididy (u|f)
297 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
298 # - checks that requested user ID has appropriate validity
299 # (see /usr/share/doc/gnupg/DETAILS.gz)
300 # output is one line for every found key, in the following format:
304 # "flag" is an acceptability flag, 0 = ok, 1 = bad
305 # "fingerprint" is the fingerprint of the key
307 # expects global variable: "MODE"
310 local requiredCapability
311 local requiredPubCapability
326 # set the required key capability based on the mode
327 if [ "$MODE" = 'known_hosts' ] ; then
328 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
329 elif [ "$MODE" = 'authorized_keys' ] ; then
330 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
332 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
334 # fetch the user ID if necessary/requested
335 gpg_fetch_userid "$userID"
337 # output gpg info for (exact) userid and store
338 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
339 --with-fingerprint --with-fingerprint \
340 ="$userID" 2>/dev/null)
342 # if the gpg query return code is not 0, return 1
343 if [ "$?" -ne 0 ] ; then
344 log " no primary keys found."
348 # loop over all lines in the gpg output and process.
349 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
350 while IFS=: read -r type validity keyid uidfpr usage ; do
351 # process based on record type
353 'pub') # primary keys
354 # new key, wipe the slate
361 log " primary key found: $keyid"
363 # if overall key is not valid, skip
364 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
365 log " - unacceptable primary key validity ($validity)."
368 # if overall key is disabled, skip
369 if check_capability "$usage" 'D' ; then
370 log " - key disabled."
373 # if overall key capability is not ok, skip
374 if ! check_capability "$usage" $requiredPubCapability ; then
375 log " - unacceptable primary key capability ($usage)."
379 # mark overall key as ok
382 # mark primary key as ok if capability is ok
383 if check_capability "$usage" $requiredCapability ; then
388 if [ "$lastKey" != pub ] ; then
389 log " - got a user ID after a sub key! user IDs should only follow primary keys!"
392 # don't bother with a uid if there is no valid or reasonable primary key.
393 if [ "$keyOK" != true ] ; then
396 # if an acceptable user ID was already found, skip
397 if [ "$uidOK" ] ; then
400 # if the user ID does not match, skip
401 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
404 # if the user ID validity is not ok, skip
405 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
409 # mark user ID acceptable
412 # output a line for the primary key
414 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
415 log " * acceptable primary key."
416 if [ -z "$sshKey" ] ; then
417 log " ! primary key could not be translated (not RSA or DSA?)."
422 log " - unacceptable primary key."
423 if [ -z "$sshKey" ] ; then
424 log " ! primary key could not be translated (not RSA or DSA?)."
431 # unset acceptability of last key
436 # don't bother with sub keys if the primary key is not valid
437 if [ "$keyOK" != true ] ; then
441 # don't bother with sub keys if no user ID is acceptable:
442 if [ "$uidOK" != true ] ; then
446 # if sub key validity is not ok, skip
447 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
450 # if sub key capability is not ok, skip
451 if ! check_capability "$usage" $requiredCapability ; then
458 'fpr') # key fingerprint
459 fingerprint="$uidfpr"
461 sshKey=$(gpg2ssh "$fingerprint")
463 # if the last key was the pub key, skip
464 if [ "$lastKey" = pub ] ; then
468 # output a line for the sub key
470 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
471 log " * acceptable sub key."
472 if [ -z "$sshKey" ] ; then
473 log " ! sub key could not be translated (not RSA or DSA?)."
478 log " - unacceptable sub key."
479 if [ -z "$sshKey" ] ; then
480 log " ! sub key could not be translated (not RSA or DSA?)."
487 done | sort -t: -k1 -n -r
488 # NOTE: this last sort is important so that the "good" keys (key
489 # flag '0') come last. This is so that they take precedence when
490 # being processed in the key files over "bad" keys (key flag '1')
493 # process a single host in the known_host file
494 process_host_known_hosts() {
504 userID="ssh://${host}"
506 log "processing: $host"
512 for line in $(process_user_id "${userID}") ; do
513 # note that key was found
516 ok=$(echo "$line" | cut -d: -f1)
517 sshKey=$(echo "$line" | cut -d: -f2)
519 if [ -z "$sshKey" ] ; then
523 # remove the old host key line, and note if removed
524 remove_line "$KNOWN_HOSTS" "$sshKey"
526 # if key OK, add new host line
527 if [ "$ok" -eq '0' ] ; then
528 # note that key was found ok
529 nKeysOK=$((nKeysOK+1))
532 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
533 # FIXME: this is really hackish cause ssh-keygen won't
534 # hash from stdin to stdout
536 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
537 ssh-keygen -H -f "$tmpfile" 2> /dev/null
538 cat "$tmpfile" >> "$KNOWN_HOSTS"
539 rm -f "$tmpfile" "${tmpfile}.old"
541 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
546 # if at least one key was found...
547 if [ "$nKeys" -gt 0 ] ; then
548 # if ok keys were found, return 0
549 if [ "$nKeysOK" -gt 0 ] ; then
555 # if no keys were found, return 1
561 # update the known_hosts file for a set of hosts listed on command
563 update_known_hosts() {
570 # the number of hosts specified on command line
576 # set the trap to remove any lockfiles on exit
577 trap "lockfile-remove $KNOWN_HOSTS" EXIT
579 # create a lockfile on known_hosts
580 lockfile-create "$KNOWN_HOSTS"
582 # note pre update file checksum
583 fileCheck="$(file_hash "$KNOWN_HOSTS")"
587 process_host_known_hosts "$host"
591 nHostsOK=$((nHostsOK+1))
594 nHostsBAD=$((nHostsBAD+1))
598 # touch the lockfile, for good measure.
599 lockfile-touch --oneshot "$KNOWN_HOSTS"
602 # remove the lockfile
603 lockfile-remove "$KNOWN_HOSTS"
605 # note if the known_hosts file was updated
606 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
607 log "known_hosts file updated."
610 # if an acceptable host was found, return 0
611 if [ "$nHostsOK" -gt 0 ] ; then
613 # else if no ok hosts were found...
615 # if no bad host were found then no hosts were found at all,
617 if [ "$nHostsBAD" -eq 0 ] ; then
619 # else if at least one bad host was found, return 2
626 # process hosts from a known_hosts file
627 process_known_hosts() {
630 log "processing known_hosts file..."
632 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
634 if [ -z "$hosts" ] ; then
635 log "no hosts to process."
639 # take all the hosts from the known_hosts file (first
640 # field), grep out all the hashed hosts (lines starting
642 update_known_hosts $hosts
645 # process uids for the authorized_keys file
646 process_uid_authorized_keys() {
655 log "processing: $userID"
661 for line in $(process_user_id "$userID") ; do
662 # note that key was found
665 ok=$(echo "$line" | cut -d: -f1)
666 sshKey=$(echo "$line" | cut -d: -f2)
668 if [ -z "$sshKey" ] ; then
672 # remove the old host key line
673 remove_line "$AUTHORIZED_KEYS" "$sshKey"
675 # if key OK, add new host line
676 if [ "$ok" -eq '0' ] ; then
677 # note that key was found ok
678 nKeysOK=$((nKeysOK+1))
680 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
684 # if at least one key was found...
685 if [ "$nKeys" -gt 0 ] ; then
686 # if ok keys were found, return 0
687 if [ "$nKeysOK" -gt 0 ] ; then
693 # if no keys were found, return 1
699 # update the authorized_keys files from a list of user IDs on command
701 update_authorized_keys() {
708 # the number of ids specified on command line
714 # set the trap to remove any lockfiles on exit
715 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
717 # create a lockfile on authorized_keys
718 lockfile-create "$AUTHORIZED_KEYS"
720 # note pre update file checksum
721 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
723 # remove any monkeysphere lines from authorized_keys file
724 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
727 # process the user ID, change return code if key not found for
729 process_uid_authorized_keys "$userID"
737 nIDsBAD=$((nIDsBAD+1))
741 # touch the lockfile, for good measure.
742 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
745 # remove the lockfile
746 lockfile-remove "$AUTHORIZED_KEYS"
748 # note if the authorized_keys file was updated
749 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
750 log "authorized_keys file updated."
753 # if an acceptable id was found, return 0
754 if [ "$nIDsOK" -gt 0 ] ; then
756 # else if no ok ids were found...
758 # if no bad ids were found then no ids were found at all, and
760 if [ "$nIDsBAD" -eq 0 ] ; then
762 # else if at least one bad id was found, return 2
769 # process an authorized_user_ids file for authorized_keys
770 process_authorized_user_ids() {
775 authorizedUserIDs="$1"
777 log "processing authorized_user_ids file..."
779 if ! meat "$authorizedUserIDs" > /dev/null ; then
780 log "no user IDs to process."
786 # extract user IDs from authorized_user_ids file
788 for line in $(meat "$authorizedUserIDs") ; do
789 userIDs["$nline"]="$line"
793 update_authorized_keys "${userIDs[@]}"