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 in pipeline from gpg output back into
74 # FIXME: undo all escape character translation in with-colons gpg
80 # convert nasty chars into gpg-friendly form in pipeline
81 # FIXME: escape everything, not just colons!
86 # remove all lines with specified string from specified file
94 if [ -z "$file" -o -z "$string" ] ; then
98 if [ ! -e "$file" ] ; then
102 # if the string is in the file...
103 if grep -q -F "$string" "$file" 2> /dev/null ; then
104 # remove the line with the string, and return 0
105 grep -v -F "$string" "$file" | sponge "$file"
113 # remove all lines with MonkeySphere strings in file
114 remove_monkeysphere_lines() {
119 if [ -z "$file" ] ; then
123 if [ ! -e "$file" ] ; then
127 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
128 "$file" | sponge "$file"
131 # translate ssh-style path variables %h and %u
132 translate_ssh_variables() {
139 # get the user's home directory
140 userHome=$(getent passwd "$uname" | cut -d: -f6)
142 # translate '%u' to user name
143 path=${path/\%u/"$uname"}
144 # translate '%h' to user home directory
145 path=${path/\%h/"$userHome"}
150 # test that a string to conforms to GPG's expiration format
152 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
155 # check that a file is properly owned, and that all it's parent
156 # directories are not group/other writable
157 check_key_file_permissions() {
164 # function to check that an octal corresponds to writability
166 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
172 # return 0 is path does not exist
173 [ -e "$path" ] || return 0
175 owner=$(stat --format '%U' "$path")
176 access=$(stat --format '%a' "$path")
177 gAccess=$(echo "$access" | cut -c2)
178 oAccess=$(echo "$access" | cut -c3)
181 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
185 # check group/other writability
186 if is_write "$gAccess" || is_write "$oAccess" ; then
190 if [ "$path" = '/' ] ; then
193 check_key_file_permissions $(dirname "$path")
197 ### CONVERSION UTILITIES
199 # output the ssh key for a given key ID
205 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
208 # output known_hosts line from ssh key
217 echo -n "$key" | tr -d '\n'
218 echo " MonkeySphere${DATE}"
221 # output authorized_keys line from ssh key
222 ssh2authorized_keys() {
229 echo -n "$key" | tr -d '\n'
230 echo " MonkeySphere${DATE} ${userID}"
233 # convert key from gpg to ssh known_hosts format
241 # NOTE: it seems that ssh-keygen -R removes all comment fields from
242 # all lines in the known_hosts file. why?
243 # NOTE: just in case, the COMMENT can be matched with the
245 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
247 gpg2ssh "$keyID" | tr -d '\n'
248 echo " MonkeySphere${DATE}"
251 # convert key from gpg to ssh authorized_keys format
252 gpg2authorized_keys() {
259 # NOTE: just in case, the COMMENT can be matched with the
261 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
262 gpg2ssh "$keyID" | tr -d '\n'
263 echo " MonkeySphere${DATE} ${userID}"
268 # retrieve all keys with given user id from keyserver
269 # FIXME: need to figure out how to retrieve all matching keys
270 # (not just first N (5 in this case))
275 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
281 log -n " checking keyserver $KEYSERVER... "
283 gpg --quiet --batch --with-colons \
284 --command-fd 0 --keyserver "$KEYSERVER" \
285 --search ="$userID" > /dev/null 2>&1
289 # if the user is the monkeysphere user, then update the
290 # monkeysphere user's trustdb
291 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
292 gpg_authentication "--check-trustdb" > /dev/null 2>&1
298 ########################################################################
299 ### PROCESSING FUNCTIONS
301 # userid and key policy checking
302 # the following checks policy on the returned keys
303 # - checks that full key has appropriate valididy (u|f)
304 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
305 # - checks that requested user ID has appropriate validity
306 # (see /usr/share/doc/gnupg/DETAILS.gz)
307 # output is one line for every found key, in the following format:
311 # "flag" is an acceptability flag, 0 = ok, 1 = bad
312 # "fingerprint" is the fingerprint of the key
314 # expects global variable: "MODE"
317 local requiredCapability
318 local requiredPubCapability
333 # set the required key capability based on the mode
334 if [ "$MODE" = 'known_hosts' ] ; then
335 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
336 elif [ "$MODE" = 'authorized_keys' ] ; then
337 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
339 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
341 # fetch the user ID if necessary/requested
342 gpg_fetch_userid "$userID"
344 # output gpg info for (exact) userid and store
345 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
346 --with-fingerprint --with-fingerprint \
347 ="$userID" 2>/dev/null)
349 # if the gpg query return code is not 0, return 1
350 if [ "$?" -ne 0 ] ; then
351 log " no primary keys found."
355 # loop over all lines in the gpg output and process.
356 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
357 while IFS=: read -r type validity keyid uidfpr usage ; do
358 # process based on record type
360 'pub') # primary keys
361 # new key, wipe the slate
368 log " primary key found: $keyid"
370 # if overall key is not valid, skip
371 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
372 log " - unacceptable primary key validity ($validity)."
375 # if overall key is disabled, skip
376 if check_capability "$usage" 'D' ; then
377 log " - key disabled."
380 # if overall key capability is not ok, skip
381 if ! check_capability "$usage" $requiredPubCapability ; then
382 log " - unacceptable primary key capability ($usage)."
386 # mark overall key as ok
389 # mark primary key as ok if capability is ok
390 if check_capability "$usage" $requiredCapability ; then
395 if [ "$lastKey" != pub ] ; then
396 log " - got a user ID after a sub key! user IDs should only follow primary keys!"
399 # don't bother with a uid if there is no valid or reasonable primary key.
400 if [ "$keyOK" != true ] ; then
403 # if an acceptable user ID was already found, skip
404 if [ "$uidOK" ] ; then
407 # if the user ID does not match, skip
408 if [ "$(echo "$uidfpr" | gpg_unescape)" != "$userID" ] ; then
411 # if the user ID validity is not ok, skip
412 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
416 # mark user ID acceptable
419 # output a line for the primary key
421 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
422 log " * acceptable primary key."
423 if [ -z "$sshKey" ] ; then
424 log " ! primary key could not be translated (not RSA or DSA?)."
429 log " - unacceptable primary key."
430 if [ -z "$sshKey" ] ; then
431 log " ! primary key could not be translated (not RSA or DSA?)."
438 # unset acceptability of last key
443 # don't bother with sub keys if the primary key is not valid
444 if [ "$keyOK" != true ] ; then
448 # don't bother with sub keys if no user ID is acceptable:
449 if [ "$uidOK" != true ] ; then
453 # if sub key validity is not ok, skip
454 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
457 # if sub key capability is not ok, skip
458 if ! check_capability "$usage" $requiredCapability ; then
465 'fpr') # key fingerprint
466 fingerprint="$uidfpr"
468 sshKey=$(gpg2ssh "$fingerprint")
470 # if the last key was the pub key, skip
471 if [ "$lastKey" = pub ] ; then
475 # output a line for the sub key
477 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
478 log " * acceptable sub key."
479 if [ -z "$sshKey" ] ; then
480 log " ! sub key could not be translated (not RSA or DSA?)."
485 log " - unacceptable sub key."
486 if [ -z "$sshKey" ] ; then
487 log " ! sub key could not be translated (not RSA or DSA?)."
494 done | sort -t: -k1 -n -r
495 # NOTE: this last sort is important so that the "good" keys (key
496 # flag '0') come last. This is so that they take precedence when
497 # being processed in the key files over "bad" keys (key flag '1')
500 # process a single host in the known_host file
501 process_host_known_hosts() {
511 userID="ssh://${host}"
513 log "processing: $host"
519 for line in $(process_user_id "${userID}") ; do
520 # note that key was found
523 ok=$(echo "$line" | cut -d: -f1)
524 sshKey=$(echo "$line" | cut -d: -f2)
526 if [ -z "$sshKey" ] ; then
530 # remove the old host key line, and note if removed
531 remove_line "$KNOWN_HOSTS" "$sshKey"
533 # if key OK, add new host line
534 if [ "$ok" -eq '0' ] ; then
535 # note that key was found ok
536 nKeysOK=$((nKeysOK+1))
539 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
540 # FIXME: this is really hackish cause ssh-keygen won't
541 # hash from stdin to stdout
543 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
544 ssh-keygen -H -f "$tmpfile" 2> /dev/null
545 cat "$tmpfile" >> "$KNOWN_HOSTS"
546 rm -f "$tmpfile" "${tmpfile}.old"
548 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
553 # if at least one key was found...
554 if [ "$nKeys" -gt 0 ] ; then
555 # if ok keys were found, return 0
556 if [ "$nKeysOK" -gt 0 ] ; then
562 # if no keys were found, return 1
568 # update the known_hosts file for a set of hosts listed on command
570 update_known_hosts() {
577 # the number of hosts specified on command line
583 # set the trap to remove any lockfiles on exit
584 trap "lockfile-remove $KNOWN_HOSTS" EXIT
586 # create a lockfile on known_hosts
587 lockfile-create "$KNOWN_HOSTS"
589 # note pre update file checksum
590 fileCheck="$(file_hash "$KNOWN_HOSTS")"
594 process_host_known_hosts "$host"
598 nHostsOK=$((nHostsOK+1))
601 nHostsBAD=$((nHostsBAD+1))
605 # touch the lockfile, for good measure.
606 lockfile-touch --oneshot "$KNOWN_HOSTS"
609 # remove the lockfile
610 lockfile-remove "$KNOWN_HOSTS"
612 # note if the known_hosts file was updated
613 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
614 log "known_hosts file updated."
617 # if an acceptable host was found, return 0
618 if [ "$nHostsOK" -gt 0 ] ; then
620 # else if no ok hosts were found...
622 # if no bad host were found then no hosts were found at all,
624 if [ "$nHostsBAD" -eq 0 ] ; then
626 # else if at least one bad host was found, return 2
633 # process hosts from a known_hosts file
634 process_known_hosts() {
637 log "processing known_hosts file..."
639 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
641 if [ -z "$hosts" ] ; then
642 log "no hosts to process."
646 # take all the hosts from the known_hosts file (first
647 # field), grep out all the hashed hosts (lines starting
649 update_known_hosts $hosts
652 # process uids for the authorized_keys file
653 process_uid_authorized_keys() {
662 log "processing: $userID"
668 for line in $(process_user_id "$userID") ; do
669 # note that key was found
672 ok=$(echo "$line" | cut -d: -f1)
673 sshKey=$(echo "$line" | cut -d: -f2)
675 if [ -z "$sshKey" ] ; then
679 # remove the old host key line
680 remove_line "$AUTHORIZED_KEYS" "$sshKey"
682 # if key OK, add new host line
683 if [ "$ok" -eq '0' ] ; then
684 # note that key was found ok
685 nKeysOK=$((nKeysOK+1))
687 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
691 # if at least one key was found...
692 if [ "$nKeys" -gt 0 ] ; then
693 # if ok keys were found, return 0
694 if [ "$nKeysOK" -gt 0 ] ; then
700 # if no keys were found, return 1
706 # update the authorized_keys files from a list of user IDs on command
708 update_authorized_keys() {
715 # the number of ids specified on command line
721 # set the trap to remove any lockfiles on exit
722 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
724 # create a lockfile on authorized_keys
725 lockfile-create "$AUTHORIZED_KEYS"
727 # note pre update file checksum
728 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
730 # remove any monkeysphere lines from authorized_keys file
731 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
734 # process the user ID, change return code if key not found for
736 process_uid_authorized_keys "$userID"
744 nIDsBAD=$((nIDsBAD+1))
748 # touch the lockfile, for good measure.
749 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
752 # remove the lockfile
753 lockfile-remove "$AUTHORIZED_KEYS"
755 # note if the authorized_keys file was updated
756 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
757 log "authorized_keys file updated."
760 # if an acceptable id was found, return 0
761 if [ "$nIDsOK" -gt 0 ] ; then
763 # else if no ok ids were found...
765 # if no bad ids were found then no ids were found at all, and
767 if [ "$nIDsBAD" -eq 0 ] ; then
769 # else if at least one bad id was found, return 2
776 # process an authorized_user_ids file for authorized_keys
777 process_authorized_user_ids() {
782 authorizedUserIDs="$1"
784 log "processing authorized_user_ids file..."
786 if ! meat "$authorizedUserIDs" > /dev/null ; then
787 log "no user IDs to process."
793 # extract user IDs from authorized_user_ids file
795 for line in $(meat "$authorizedUserIDs") ; do
796 userIDs["$nline"]="$line"
800 update_authorized_keys "${userIDs[@]}"