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
67 # convert escaped characters from gpg output back into original
69 # FIXME: undo all escape character translation in with-colons gpg output
71 echo "$1" | sed 's/\\x3a/:/'
74 # remove all lines with specified string from specified file
82 if [ -z "$file" -o -z "$string" ] ; then
86 # if the string is in the file...
87 if grep -q -F "$string" "$file" 2> /dev/null ; then
88 # remove the line with the string, and return 0
89 grep -v -F "$string" "$file" | sponge "$file"
97 # translate ssh-style path variables %h and %u
98 translate_ssh_variables() {
105 # get the user's home directory
106 userHome=$(getent passwd "$uname" | cut -d: -f6)
108 # translate '%u' to user name
109 path=${path/\%u/"$uname"}
110 # translate '%h' to user home directory
111 path=${path/\%h/"$userHome"}
116 # test that a string to conforms to GPG's expiration format
118 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
121 # check that a file is properly owned, and that all it's parent
122 # directories are not group/other writable
123 check_key_file_permissions() {
130 # function to check that an octal corresponds to writability
132 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
138 # return 0 is path does not exist
139 [ -e "$path" ] || return 0
141 owner=$(stat --format '%U' "$path")
142 access=$(stat --format '%a' "$path")
143 gAccess=$(echo "$access" | cut -c2)
144 oAccess=$(echo "$access" | cut -c3)
147 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
151 # check group/other writability
152 if is_write "$gAccess" || is_write "$oAccess" ; then
156 if [ "$path" = '/' ] ; then
159 check_key_file_permissions $(dirname "$path")
163 ### CONVERSION UTILITIES
165 # output the ssh key for a given key ID
171 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
174 # output known_hosts line from ssh key
183 echo -n "$key" | tr -d '\n'
184 echo " MonkeySphere${DATE}"
187 # output authorized_keys line from ssh key
188 ssh2authorized_keys() {
195 echo -n "$key" | tr -d '\n'
196 echo " MonkeySphere${DATE} ${userID}"
199 # convert key from gpg to ssh known_hosts format
207 # NOTE: it seems that ssh-keygen -R removes all comment fields from
208 # all lines in the known_hosts file. why?
209 # NOTE: just in case, the COMMENT can be matched with the
211 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
213 gpg2ssh "$keyID" | tr -d '\n'
214 echo " MonkeySphere${DATE}"
217 # convert key from gpg to ssh authorized_keys format
218 gpg2authorized_keys() {
225 # NOTE: just in case, the COMMENT can be matched with the
227 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
228 gpg2ssh "$keyID" | tr -d '\n'
229 echo " MonkeySphere${DATE} ${userID}"
234 # retrieve all keys with given user id from keyserver
235 # FIXME: need to figure out how to retrieve all matching keys
236 # (not just first N (5 in this case))
241 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
247 log -n " checking keyserver $KEYSERVER... "
249 gpg --quiet --batch --with-colons \
250 --command-fd 0 --keyserver "$KEYSERVER" \
251 --search ="$userID" > /dev/null 2>&1
255 # if the user is the monkeysphere user, then update the
256 # monkeysphere user's trustdb
257 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
258 gpg_authentication "--check-trustdb" > /dev/null 2>&1
264 ########################################################################
265 ### PROCESSING FUNCTIONS
267 # userid and key policy checking
268 # the following checks policy on the returned keys
269 # - checks that full key has appropriate valididy (u|f)
270 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
271 # - checks that requested user ID has appropriate validity
272 # (see /usr/share/doc/gnupg/DETAILS.gz)
273 # output is one line for every found key, in the following format:
277 # "flag" is an acceptability flag, 0 = ok, 1 = bad
278 # "fingerprint" is the fingerprint of the key
280 # expects global variable: "MODE"
283 local requiredCapability
284 local requiredPubCapability
299 # set the required key capability based on the mode
300 if [ "$MODE" = 'known_hosts' ] ; then
301 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
302 elif [ "$MODE" = 'authorized_keys' ] ; then
303 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
305 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
307 # fetch the user ID if necessary/requested
308 gpg_fetch_userid "$userID"
310 # output gpg info for (exact) userid and store
311 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
312 --with-fingerprint --with-fingerprint \
313 ="$userID" 2>/dev/null)
315 # if the gpg query return code is not 0, return 1
316 if [ "$?" -ne 0 ] ; then
317 log " - key not found."
321 # loop over all lines in the gpg output and process.
322 # need to do it this way (as opposed to "while read...") so that
323 # variables set in loop will be visible outside of loop
324 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
325 while IFS=: read -r type validity keyid uidfpr usage ; do
326 # process based on record type
328 'pub') # primary keys
329 # new key, wipe the slate
336 log " primary key found: $keyid"
338 # if overall key is not valid, skip
339 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
340 log " - unacceptable primary key validity ($validity)."
343 # if overall key is disabled, skip
344 if check_capability "$usage" 'D' ; then
345 log " - key disabled."
348 # if overall key capability is not ok, skip
349 if ! check_capability "$usage" $requiredPubCapability ; then
350 log " - unacceptable primary key capability ($usage)."
354 # mark overall key as ok
357 # mark primary key as ok if capability is ok
358 if check_capability "$usage" $requiredCapability ; then
363 # if an acceptable user ID was already found, skip
364 if [ "$uidOK" ] ; then
367 # if the user ID does not match, skip
368 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
371 # if the user ID validity is not ok, skip
372 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
376 # mark user ID acceptable
379 # output a line for the primary key
381 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
382 log " * acceptable key found."
383 echo "0:${fingerprint}"
385 echo "1:${fingerprint}"
389 # unset acceptability of last key
394 # if sub key validity is not ok, skip
395 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
398 # if sub key capability is not ok, skip
399 if ! check_capability "$usage" $requiredCapability ; then
406 'fpr') # key fingerprint
407 fingerprint="$uidfpr"
409 # if the last key was the pub key, skip
410 if [ "$lastKey" = pub ] ; then
414 # output a line for the last subkey
416 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
417 log " * acceptable key found."
418 echo "0:${fingerprint}"
420 echo "1:${fingerprint}"
427 # process a single host in the known_host file
428 process_host_known_hosts() {
439 log "processing host: $host"
441 userID="ssh://${host}"
446 for line in $(process_user_id "ssh://${host}") ; do
447 # note that key was found
450 ok=$(echo "$line" | cut -d: -f1)
451 keyid=$(echo "$line" | cut -d: -f2)
453 sshKey=$(gpg2ssh "$keyid")
454 if [ -z "$sshKey" ] ; then
455 log " ! key could not be translated."
459 # remove the old host key line, and note if removed
460 remove_line "$KNOWN_HOSTS" "$sshKey"
462 # if key OK, add new host line
463 if [ "$ok" -eq '0' ] ; then
464 # note that key was found ok
465 nKeysOK=$((nKeysOK+1))
468 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
469 # FIXME: this is really hackish cause ssh-keygen won't
470 # hash from stdin to stdout
472 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
473 ssh-keygen -H -f "$tmpfile" 2> /dev/null
474 cat "$tmpfile" >> "$KNOWN_HOSTS"
475 rm -f "$tmpfile" "${tmpfile}.old"
477 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
482 # if at least one key was found...
483 if [ "$nKeys" -gt 0 ] ; then
484 # if ok keys were found, return 0
485 if [ "$nKeysOK" -gt 0 ] ; then
491 # if no keys were found, return 1
497 # update the known_hosts file for a set of hosts listed on command
499 update_known_hosts() {
505 # the number of hosts specified on command line
511 # set the trap to remove any lockfiles on exit
512 trap "lockfile-remove $KNOWN_HOSTS" EXIT
514 # create a lockfile on known_hosts
515 lockfile-create "$KNOWN_HOSTS"
519 process_host_known_hosts "$host"
523 nHostsOK=$((nHostsOK+1))
526 nHostsBAD=$((nHostsBAD+1))
530 # touch the lockfile, for good measure.
531 lockfile-touch --oneshot "$KNOWN_HOSTS"
534 # remove the lockfile
535 lockfile-remove "$KNOWN_HOSTS"
537 # note if the known_hosts file was updated
538 if [ "$nHostsOK" -gt 0 -o "$nHostsBAD" -gt 0 ] ; then
539 log "known_hosts file updated."
542 # if an acceptable host was found, return 0
543 if [ "$nHostsOK" -gt 0 ] ; then
545 # else if no ok hosts were found...
547 # if no bad host were found then no hosts were found at all,
549 if [ "$nHostsBAD" -eq 0 ] ; then
551 # else if at least one bad host was found, return 2
558 # process hosts from a known_hosts file
559 process_known_hosts() {
562 log "processing known_hosts file..."
564 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
566 if [ -z "$hosts" ] ; then
567 log "no hosts to process."
571 # take all the hosts from the known_hosts file (first
572 # field), grep out all the hashed hosts (lines starting
574 update_known_hosts $hosts
577 # process uids for the authorized_keys file
578 process_uid_authorized_keys() {
587 log "processing user ID: $userID"
592 for line in $(process_user_id "$userID") ; do
593 # note that key was found
596 ok=$(echo "$line" | cut -d: -f1)
597 keyid=$(echo "$line" | cut -d: -f2)
599 sshKey=$(gpg2ssh "$keyid")
600 if [ -z "$sshKey" ] ; then
601 log " ! key could not be translated."
605 # remove the old host key line
606 remove_line "$AUTHORIZED_KEYS" "$sshKey"
608 # if key OK, add new host line
609 if [ "$ok" -eq '0' ] ; then
610 # note that key was found ok
611 nKeysOK=$((nKeysOK+1))
613 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
617 # if at least one key was found...
618 if [ "$nKeys" -gt 0 ] ; then
619 # if ok keys were found, return 0
620 if [ "$nKeysOK" -gt 0 ] ; then
626 # if no keys were found, return 1
632 # update the authorized_keys files from a list of user IDs on command
634 update_authorized_keys() {
640 # the number of ids specified on command line
646 # set the trap to remove any lockfiles on exit
647 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
649 # create a lockfile on authorized_keys
650 lockfile-create "$AUTHORIZED_KEYS"
653 # process the user ID, change return code if key not found for
655 process_uid_authorized_keys "$userID"
663 nIDsBAD=$((nIDsBAD+1))
667 # touch the lockfile, for good measure.
668 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
671 # remove the lockfile
672 lockfile-remove "$AUTHORIZED_KEYS"
674 # note if the authorized_keys file was updated
675 if [ "$nIDsOK" -gt 0 -o "$nIDsBAD" -gt 0 ] ; then
676 log "authorized_keys file updated."
679 # if an acceptable id was found, return 0
680 if [ "$nIDsOK" -gt 0 ] ; then
682 # else if no ok ids were found...
684 # if no bad ids were found then no ids were found at all, and
686 if [ "$nIDsBAD" -eq 0 ] ; then
688 # else if at least one bad id was found, return 2
695 # process an authorized_user_ids file for authorized_keys
696 process_authorized_user_ids() {
701 authorizedUserIDs="$1"
703 log "processing authorized_user_ids file..."
705 if ! meat "$authorizedUserIDs" ; then
706 log "no user IDs to process."
712 # extract user IDs from authorized_user_ids file
714 for line in $(meat "$authorizedUserIDs") ; do
715 userIDs["$nline"]="$line"
719 update_authorized_keys "${userIDs[@]}"
722 # EXPERIMENTAL (unused) process userids found in authorized_keys file
723 # go through line-by-line, extract monkeysphere userids from comment
724 # fields, and process each userid
726 process_authorized_keys() {
731 # default return code is 0, and is set to 1 if a key for a user
737 # take all the monkeysphere userids from the authorized_keys file
738 # comment field (third field) that starts with "MonkeySphere uid:"
739 # FIXME: needs to handle authorized_keys options (field 0)
740 meat "$authorizedKeys" | \
741 while read -r options keytype key comment ; do
742 # if the comment field is empty, assume the third field was
744 if [ -z "$comment" ] ; then
748 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
751 userID=$(echo "$comment" | awk "{ print $2 }")
752 if [ -z "$userID" ] ; then
757 log "processing userid: '$userID'"
758 process_user_id "$userID" > /dev/null || returnCode=1