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 # remove all lines with specified string from specified file
88 if [ -z "$file" -o -z "$string" ] ; then
92 if [ ! -e "$file" ] ; then
96 # if the string is in the file...
97 if grep -q -F "$string" "$file" 2> /dev/null ; then
98 # remove the line with the string, and return 0
99 grep -v -F "$string" "$file" | sponge "$file"
107 # remove all lines with MonkeySphere strings in file
108 remove_monkeysphere_lines() {
113 if [ -z "$file" ] ; then
117 if [ ! -e "$file" ] ; then
121 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
122 "$file" | sponge "$file"
125 # translate ssh-style path variables %h and %u
126 translate_ssh_variables() {
133 # get the user's home directory
134 userHome=$(getent passwd "$uname" | cut -d: -f6)
136 # translate '%u' to user name
137 path=${path/\%u/"$uname"}
138 # translate '%h' to user home directory
139 path=${path/\%h/"$userHome"}
144 # test that a string to conforms to GPG's expiration format
146 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
149 # check that a file is properly owned, and that all it's parent
150 # directories are not group/other writable
151 check_key_file_permissions() {
158 # function to check that an octal corresponds to writability
160 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
166 # return 0 is path does not exist
167 [ -e "$path" ] || return 0
169 owner=$(stat --format '%U' "$path")
170 access=$(stat --format '%a' "$path")
171 gAccess=$(echo "$access" | cut -c2)
172 oAccess=$(echo "$access" | cut -c3)
175 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
179 # check group/other writability
180 if is_write "$gAccess" || is_write "$oAccess" ; then
184 if [ "$path" = '/' ] ; then
187 check_key_file_permissions $(dirname "$path")
191 ### CONVERSION UTILITIES
193 # output the ssh key for a given key ID
199 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
202 # output known_hosts line from ssh key
211 echo -n "$key" | tr -d '\n'
212 echo " MonkeySphere${DATE}"
215 # output authorized_keys line from ssh key
216 ssh2authorized_keys() {
223 echo -n "$key" | tr -d '\n'
224 echo " MonkeySphere${DATE} ${userID}"
227 # convert key from gpg to ssh known_hosts format
235 # NOTE: it seems that ssh-keygen -R removes all comment fields from
236 # all lines in the known_hosts file. why?
237 # NOTE: just in case, the COMMENT can be matched with the
239 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
241 gpg2ssh "$keyID" | tr -d '\n'
242 echo " MonkeySphere${DATE}"
245 # convert key from gpg to ssh authorized_keys format
246 gpg2authorized_keys() {
253 # NOTE: just in case, the COMMENT can be matched with the
255 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
256 gpg2ssh "$keyID" | tr -d '\n'
257 echo " MonkeySphere${DATE} ${userID}"
262 # retrieve all keys with given user id from keyserver
263 # FIXME: need to figure out how to retrieve all matching keys
264 # (not just first N (5 in this case))
269 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
275 log -n " checking keyserver $KEYSERVER... "
277 gpg --quiet --batch --with-colons \
278 --command-fd 0 --keyserver "$KEYSERVER" \
279 --search ="$userID" > /dev/null 2>&1
283 # if the user is the monkeysphere user, then update the
284 # monkeysphere user's trustdb
285 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
286 gpg_authentication "--check-trustdb" > /dev/null 2>&1
292 ########################################################################
293 ### PROCESSING FUNCTIONS
295 # userid and key policy checking
296 # the following checks policy on the returned keys
297 # - checks that full key has appropriate valididy (u|f)
298 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
299 # - checks that requested user ID has appropriate validity
300 # (see /usr/share/doc/gnupg/DETAILS.gz)
301 # output is one line for every found key, in the following format:
305 # "flag" is an acceptability flag, 0 = ok, 1 = bad
306 # "fingerprint" is the fingerprint of the key
308 # expects global variable: "MODE"
311 local requiredCapability
312 local requiredPubCapability
327 # set the required key capability based on the mode
328 if [ "$MODE" = 'known_hosts' ] ; then
329 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
330 elif [ "$MODE" = 'authorized_keys' ] ; then
331 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
333 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
335 # fetch the user ID if necessary/requested
336 gpg_fetch_userid "$userID"
338 # output gpg info for (exact) userid and store
339 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
340 --with-fingerprint --with-fingerprint \
341 ="$userID" 2>/dev/null)
343 # if the gpg query return code is not 0, return 1
344 if [ "$?" -ne 0 ] ; then
345 log " no primary keys found."
349 # loop over all lines in the gpg output and process.
350 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
351 while IFS=: read -r type validity keyid uidfpr usage ; do
352 # process based on record type
354 'pub') # primary keys
355 # new key, wipe the slate
362 log " primary key found: $keyid"
364 # if overall key is not valid, skip
365 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
366 log " - unacceptable primary key validity ($validity)."
369 # if overall key is disabled, skip
370 if check_capability "$usage" 'D' ; then
371 log " - key disabled."
374 # if overall key capability is not ok, skip
375 if ! check_capability "$usage" $requiredPubCapability ; then
376 log " - unacceptable primary key capability ($usage)."
380 # mark overall key as ok
383 # mark primary key as ok if capability is ok
384 if check_capability "$usage" $requiredCapability ; then
389 if [ "$lastKey" != pub ] ; then
390 log " - got a user ID after a sub key! user IDs should only follow primary keys!"
393 # don't bother with a uid if there is no valid or reasonable primary key.
394 if [ "$keyOK" != true ] ; then
397 # if an acceptable user ID was already found, skip
398 if [ "$uidOK" ] ; then
401 # if the user ID does not match, skip
402 if [ "$(echo "$uidfpr" | gpg_unescape)" != "$userID" ] ; then
405 # if the user ID validity is not ok, skip
406 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
410 # mark user ID acceptable
413 # output a line for the primary key
415 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
416 log " * acceptable primary key."
417 if [ -z "$sshKey" ] ; then
418 log " ! primary key could not be translated (not RSA or DSA?)."
423 log " - unacceptable primary key."
424 if [ -z "$sshKey" ] ; then
425 log " ! primary key could not be translated (not RSA or DSA?)."
432 # unset acceptability of last key
437 # don't bother with sub keys if the primary key is not valid
438 if [ "$keyOK" != true ] ; then
442 # don't bother with sub keys if no user ID is acceptable:
443 if [ "$uidOK" != true ] ; then
447 # if sub key validity is not ok, skip
448 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
451 # if sub key capability is not ok, skip
452 if ! check_capability "$usage" $requiredCapability ; then
459 'fpr') # key fingerprint
460 fingerprint="$uidfpr"
462 sshKey=$(gpg2ssh "$fingerprint")
464 # if the last key was the pub key, skip
465 if [ "$lastKey" = pub ] ; then
469 # output a line for the sub key
471 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
472 log " * acceptable sub key."
473 if [ -z "$sshKey" ] ; then
474 log " ! sub key could not be translated (not RSA or DSA?)."
479 log " - unacceptable sub key."
480 if [ -z "$sshKey" ] ; then
481 log " ! sub key could not be translated (not RSA or DSA?)."
488 done | sort -t: -k1 -n -r
489 # NOTE: this last sort is important so that the "good" keys (key
490 # flag '0') come last. This is so that they take precedence when
491 # being processed in the key files over "bad" keys (key flag '1')
494 # process a single host in the known_host file
495 process_host_known_hosts() {
505 userID="ssh://${host}"
507 log "processing: $host"
513 for line in $(process_user_id "${userID}") ; do
514 # note that key was found
517 ok=$(echo "$line" | cut -d: -f1)
518 sshKey=$(echo "$line" | cut -d: -f2)
520 if [ -z "$sshKey" ] ; then
524 # remove the old host key line, and note if removed
525 remove_line "$KNOWN_HOSTS" "$sshKey"
527 # if key OK, add new host line
528 if [ "$ok" -eq '0' ] ; then
529 # note that key was found ok
530 nKeysOK=$((nKeysOK+1))
533 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
534 # FIXME: this is really hackish cause ssh-keygen won't
535 # hash from stdin to stdout
537 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
538 ssh-keygen -H -f "$tmpfile" 2> /dev/null
539 cat "$tmpfile" >> "$KNOWN_HOSTS"
540 rm -f "$tmpfile" "${tmpfile}.old"
542 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
547 # if at least one key was found...
548 if [ "$nKeys" -gt 0 ] ; then
549 # if ok keys were found, return 0
550 if [ "$nKeysOK" -gt 0 ] ; then
556 # if no keys were found, return 1
562 # update the known_hosts file for a set of hosts listed on command
564 update_known_hosts() {
571 # the number of hosts specified on command line
577 # set the trap to remove any lockfiles on exit
578 trap "lockfile-remove $KNOWN_HOSTS" EXIT
580 # create a lockfile on known_hosts
581 lockfile-create "$KNOWN_HOSTS"
583 # note pre update file checksum
584 fileCheck="$(file_hash "$KNOWN_HOSTS")"
588 process_host_known_hosts "$host"
592 nHostsOK=$((nHostsOK+1))
595 nHostsBAD=$((nHostsBAD+1))
599 # touch the lockfile, for good measure.
600 lockfile-touch --oneshot "$KNOWN_HOSTS"
603 # remove the lockfile
604 lockfile-remove "$KNOWN_HOSTS"
606 # note if the known_hosts file was updated
607 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
608 log "known_hosts file updated."
611 # if an acceptable host was found, return 0
612 if [ "$nHostsOK" -gt 0 ] ; then
614 # else if no ok hosts were found...
616 # if no bad host were found then no hosts were found at all,
618 if [ "$nHostsBAD" -eq 0 ] ; then
620 # else if at least one bad host was found, return 2
627 # process hosts from a known_hosts file
628 process_known_hosts() {
631 log "processing known_hosts file..."
633 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
635 if [ -z "$hosts" ] ; then
636 log "no hosts to process."
640 # take all the hosts from the known_hosts file (first
641 # field), grep out all the hashed hosts (lines starting
643 update_known_hosts $hosts
646 # process uids for the authorized_keys file
647 process_uid_authorized_keys() {
656 log "processing: $userID"
662 for line in $(process_user_id "$userID") ; do
663 # note that key was found
666 ok=$(echo "$line" | cut -d: -f1)
667 sshKey=$(echo "$line" | cut -d: -f2)
669 if [ -z "$sshKey" ] ; then
673 # remove the old host key line
674 remove_line "$AUTHORIZED_KEYS" "$sshKey"
676 # if key OK, add new host line
677 if [ "$ok" -eq '0' ] ; then
678 # note that key was found ok
679 nKeysOK=$((nKeysOK+1))
681 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
685 # if at least one key was found...
686 if [ "$nKeys" -gt 0 ] ; then
687 # if ok keys were found, return 0
688 if [ "$nKeysOK" -gt 0 ] ; then
694 # if no keys were found, return 1
700 # update the authorized_keys files from a list of user IDs on command
702 update_authorized_keys() {
709 # the number of ids specified on command line
715 # set the trap to remove any lockfiles on exit
716 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
718 # create a lockfile on authorized_keys
719 lockfile-create "$AUTHORIZED_KEYS"
721 # note pre update file checksum
722 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
724 # remove any monkeysphere lines from authorized_keys file
725 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
728 # process the user ID, change return code if key not found for
730 process_uid_authorized_keys "$userID"
738 nIDsBAD=$((nIDsBAD+1))
742 # touch the lockfile, for good measure.
743 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
746 # remove the lockfile
747 lockfile-remove "$AUTHORIZED_KEYS"
749 # note if the authorized_keys file was updated
750 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
751 log "authorized_keys file updated."
754 # if an acceptable id was found, return 0
755 if [ "$nIDsOK" -gt 0 ] ; then
757 # else if no ok ids were found...
759 # if no bad ids were found then no ids were found at all, and
761 if [ "$nIDsBAD" -eq 0 ] ; then
763 # else if at least one bad id was found, return 2
770 # process an authorized_user_ids file for authorized_keys
771 process_authorized_user_ids() {
776 authorizedUserIDs="$1"
778 log "processing authorized_user_ids file..."
780 if ! meat "$authorizedUserIDs" > /dev/null ; then
781 log "no user IDs to process."
787 # extract user IDs from authorized_user_ids file
789 for line in $(meat "$authorizedUserIDs") ; do
790 userIDs["$nline"]="$line"
794 update_authorized_keys "${userIDs[@]}"