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/:/'
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?)."
490 # process a single host in the known_host file
491 process_host_known_hosts() {
502 log "processing: $host"
504 userID="ssh://${host}"
510 for line in $(process_user_id "ssh://${host}") ; do
511 # note that key was found
514 ok=$(echo "$line" | cut -d: -f1)
515 sshKey=$(echo "$line" | cut -d: -f2)
517 if [ -z "$sshKey" ] ; then
521 # remove the old host key line, and note if removed
522 remove_line "$KNOWN_HOSTS" "$sshKey"
524 # if key OK, add new host line
525 if [ "$ok" -eq '0' ] ; then
526 # note that key was found ok
527 nKeysOK=$((nKeysOK+1))
530 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
531 # FIXME: this is really hackish cause ssh-keygen won't
532 # hash from stdin to stdout
534 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
535 ssh-keygen -H -f "$tmpfile" 2> /dev/null
536 cat "$tmpfile" >> "$KNOWN_HOSTS"
537 rm -f "$tmpfile" "${tmpfile}.old"
539 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
544 # if at least one key was found...
545 if [ "$nKeys" -gt 0 ] ; then
546 # if ok keys were found, return 0
547 if [ "$nKeysOK" -gt 0 ] ; then
553 # if no keys were found, return 1
559 # update the known_hosts file for a set of hosts listed on command
561 update_known_hosts() {
568 # the number of hosts specified on command line
574 # set the trap to remove any lockfiles on exit
575 trap "lockfile-remove $KNOWN_HOSTS" EXIT
577 # create a lockfile on known_hosts
578 lockfile-create "$KNOWN_HOSTS"
580 # note pre update file checksum
581 fileCheck="$(file_hash "$KNOWN_HOSTS")"
585 process_host_known_hosts "$host"
589 nHostsOK=$((nHostsOK+1))
592 nHostsBAD=$((nHostsBAD+1))
596 # touch the lockfile, for good measure.
597 lockfile-touch --oneshot "$KNOWN_HOSTS"
600 # remove the lockfile
601 lockfile-remove "$KNOWN_HOSTS"
603 # note if the known_hosts file was updated
604 if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
605 log "known_hosts file updated."
608 # if an acceptable host was found, return 0
609 if [ "$nHostsOK" -gt 0 ] ; then
611 # else if no ok hosts were found...
613 # if no bad host were found then no hosts were found at all,
615 if [ "$nHostsBAD" -eq 0 ] ; then
617 # else if at least one bad host was found, return 2
624 # process hosts from a known_hosts file
625 process_known_hosts() {
628 log "processing known_hosts file..."
630 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
632 if [ -z "$hosts" ] ; then
633 log "no hosts to process."
637 # take all the hosts from the known_hosts file (first
638 # field), grep out all the hashed hosts (lines starting
640 update_known_hosts $hosts
643 # process uids for the authorized_keys file
644 process_uid_authorized_keys() {
653 log "processing: $userID"
659 for line in $(process_user_id "$userID") ; do
660 # note that key was found
663 ok=$(echo "$line" | cut -d: -f1)
664 sshKey=$(echo "$line" | cut -d: -f2)
666 if [ -z "$sshKey" ] ; then
670 # remove the old host key line
671 remove_line "$AUTHORIZED_KEYS" "$sshKey"
673 # if key OK, add new host line
674 if [ "$ok" -eq '0' ] ; then
675 # note that key was found ok
676 nKeysOK=$((nKeysOK+1))
678 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
682 # if at least one key was found...
683 if [ "$nKeys" -gt 0 ] ; then
684 # if ok keys were found, return 0
685 if [ "$nKeysOK" -gt 0 ] ; then
691 # if no keys were found, return 1
697 # update the authorized_keys files from a list of user IDs on command
699 update_authorized_keys() {
706 # the number of ids specified on command line
712 # set the trap to remove any lockfiles on exit
713 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
715 # create a lockfile on authorized_keys
716 lockfile-create "$AUTHORIZED_KEYS"
718 # note pre update file checksum
719 fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
721 # remove any monkeysphere lines from authorized_keys file
722 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
725 # process the user ID, change return code if key not found for
727 process_uid_authorized_keys "$userID"
735 nIDsBAD=$((nIDsBAD+1))
739 # touch the lockfile, for good measure.
740 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
743 # remove the lockfile
744 lockfile-remove "$AUTHORIZED_KEYS"
746 # note if the authorized_keys file was updated
747 if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
748 log "authorized_keys file updated."
751 # if an acceptable id was found, return 0
752 if [ "$nIDsOK" -gt 0 ] ; then
754 # else if no ok ids were found...
756 # if no bad ids were found then no ids were found at all, and
758 if [ "$nIDsBAD" -eq 0 ] ; then
760 # else if at least one bad id was found, return 2
767 # process an authorized_user_ids file for authorized_keys
768 process_authorized_user_ids() {
773 authorizedUserIDs="$1"
775 log "processing authorized_user_ids file..."
777 if ! meat "$authorizedUserIDs" > /dev/null ; then
778 log "no user IDs to process."
784 # extract user IDs from authorized_user_ids file
786 for line in $(meat "$authorizedUserIDs") ; do
787 userIDs["$nline"]="$line"
791 update_authorized_keys "${userIDs[@]}"