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 # if an acceptable user ID was already found, skip
400 if [ "$uidOK" = 'true' ] ; then
403 # if the user ID does matches...
404 if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
405 # and the user ID validity is ok
406 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
407 # mark user ID acceptable
414 # output a line for the primary key
416 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
417 log " * acceptable primary key."
418 if [ -z "$sshKey" ] ; then
419 log " ! primary key could not be translated (not RSA or DSA?)."
424 log " - unacceptable primary key."
425 if [ -z "$sshKey" ] ; then
426 log " ! primary key could not be translated (not RSA or DSA?)."
433 # unset acceptability of last key
438 # don't bother with sub keys if the primary key is not valid
439 if [ "$keyOK" != true ] ; then
443 # don't bother with sub keys if no user ID is acceptable:
444 if [ "$uidOK" != true ] ; then
448 # if sub key validity is not ok, skip
449 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
452 # if sub key capability is not ok, skip
453 if ! check_capability "$usage" $requiredCapability ; then
460 'fpr') # key fingerprint
461 fingerprint="$uidfpr"
463 sshKey=$(gpg2ssh "$fingerprint")
465 # if the last key was the pub key, skip
466 if [ "$lastKey" = pub ] ; then
470 # output a line for the sub key
472 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
473 log " * acceptable sub key."
474 if [ -z "$sshKey" ] ; then
475 log " ! sub key could not be translated (not RSA or DSA?)."
480 log " - unacceptable sub key."
481 if [ -z "$sshKey" ] ; then
482 log " ! sub key could not be translated (not RSA or DSA?)."
489 done | sort -t: -k1 -n -r
490 # NOTE: this last sort is important so that the "good" keys (key
491 # flag '0') come last. This is so that they take precedence when
492 # being processed in the key files over "bad" keys (key flag '1')
495 # process a single host in the known_host file
496 process_host_known_hosts() {
506 userID="ssh://${host}"
508 log "processing: $host"
514 for line in $(process_user_id "${userID}") ; do
515 # note that key was found
518 ok=$(echo "$line" | cut -d: -f1)
519 sshKey=$(echo "$line" | cut -d: -f2)
521 if [ -z "$sshKey" ] ; then
525 # remove the old host key line, and note if removed
526 remove_line "$KNOWN_HOSTS" "$sshKey"
528 # if key OK, add new host line
529 if [ "$ok" -eq '0' ] ; then
530 # note that key was found ok
531 nKeysOK=$((nKeysOK+1))
534 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
535 # FIXME: this is really hackish cause ssh-keygen won't
536 # hash from stdin to stdout
538 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
539 ssh-keygen -H -f "$tmpfile" 2> /dev/null
540 cat "$tmpfile" >> "$KNOWN_HOSTS"
541 rm -f "$tmpfile" "${tmpfile}.old"
543 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
548 # if at least one key was found...
549 if [ "$nKeys" -gt 0 ] ; then
550 # if ok keys were found, return 0
551 if [ "$nKeysOK" -gt 0 ] ; then
557 # if no keys were found, return 1
563 # update the known_hosts file for a set of hosts listed on command
565 update_known_hosts() {
572 # the number of hosts specified on command line
578 # set the trap to remove any lockfiles on exit
579 trap "lockfile-remove $KNOWN_HOSTS" EXIT
581 # create a lockfile on known_hosts
582 lockfile-create "$KNOWN_HOSTS"
584 # note pre update file checksum
585 fileCheck="$(file_hash "$KNOWN_HOSTS")"
589 process_host_known_hosts "$host"
593 nHostsOK=$((nHostsOK+1))
596 nHostsBAD=$((nHostsBAD+1))
600 # touch the lockfile, for good measure.
601 lockfile-touch --oneshot "$KNOWN_HOSTS"
604 # remove the lockfile
605 lockfile-remove "$KNOWN_HOSTS"
607 # note if the known_hosts file was updated
608 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
609 log "known_hosts file updated."
612 # if an acceptable host was found, return 0
613 if [ "$nHostsOK" -gt 0 ] ; then
615 # else if no ok hosts were found...
617 # if no bad host were found then no hosts were found at all,
619 if [ "$nHostsBAD" -eq 0 ] ; then
621 # else if at least one bad host was found, return 2
628 # process hosts from a known_hosts file
629 process_known_hosts() {
632 log "processing known_hosts file..."
634 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
636 if [ -z "$hosts" ] ; then
637 log "no hosts to process."
641 # take all the hosts from the known_hosts file (first
642 # field), grep out all the hashed hosts (lines starting
644 update_known_hosts $hosts
647 # process uids for the authorized_keys file
648 process_uid_authorized_keys() {
657 log "processing: $userID"
663 for line in $(process_user_id "$userID") ; do
664 # note that key was found
667 ok=$(echo "$line" | cut -d: -f1)
668 sshKey=$(echo "$line" | cut -d: -f2)
670 if [ -z "$sshKey" ] ; then
674 # remove the old host key line
675 remove_line "$AUTHORIZED_KEYS" "$sshKey"
677 # if key OK, add new host line
678 if [ "$ok" -eq '0' ] ; then
679 # note that key was found ok
680 nKeysOK=$((nKeysOK+1))
682 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
686 # if at least one key was found...
687 if [ "$nKeys" -gt 0 ] ; then
688 # if ok keys were found, return 0
689 if [ "$nKeysOK" -gt 0 ] ; then
695 # if no keys were found, return 1
701 # update the authorized_keys files from a list of user IDs on command
703 update_authorized_keys() {
710 # the number of ids specified on command line
716 # set the trap to remove any lockfiles on exit
717 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
719 # create a lockfile on authorized_keys
720 lockfile-create "$AUTHORIZED_KEYS"
722 # note pre update file checksum
723 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
725 # remove any monkeysphere lines from authorized_keys file
726 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
729 # process the user ID, change return code if key not found for
731 process_uid_authorized_keys "$userID"
739 nIDsBAD=$((nIDsBAD+1))
743 # touch the lockfile, for good measure.
744 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
747 # remove the lockfile
748 lockfile-remove "$AUTHORIZED_KEYS"
750 # note if the authorized_keys file was updated
751 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
752 log "authorized_keys file updated."
755 # if an acceptable id was found, return 0
756 if [ "$nIDsOK" -gt 0 ] ; then
758 # else if no ok ids were found...
760 # if no bad ids were found then no ids were found at all, and
762 if [ "$nIDsBAD" -eq 0 ] ; then
764 # else if at least one bad id was found, return 2
771 # process an authorized_user_ids file for authorized_keys
772 process_authorized_user_ids() {
777 authorizedUserIDs="$1"
779 log "processing authorized_user_ids file..."
781 if ! meat "$authorizedUserIDs" > /dev/null ; then
782 log "no user IDs to process."
788 # extract user IDs from authorized_user_ids file
790 for line in $(meat "$authorizedUserIDs") ; do
791 userIDs["$nline"]="$line"
795 update_authorized_keys "${userIDs[@]}"