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/:/g'
74 # remove all lines with specified string from specified file
82 if [ -z "$file" -o -z "$string" ] ; then
86 if [ ! -e "$file" ] ; then
90 # if the string is in the file...
91 if grep -q -F "$string" "$file" 2> /dev/null ; then
92 # remove the line with the string, and return 0
93 grep -v -F "$string" "$file" | sponge "$file"
101 # remove all lines with MonkeySphere strings in file
102 remove_monkeysphere_lines() {
107 if [ -z "$file" ] ; then
111 if [ ! -e "$file" ] ; then
115 egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
116 "$file" | sponge "$file"
119 # translate ssh-style path variables %h and %u
120 translate_ssh_variables() {
127 # get the user's home directory
128 userHome=$(getent passwd "$uname" | cut -d: -f6)
130 # translate '%u' to user name
131 path=${path/\%u/"$uname"}
132 # translate '%h' to user home directory
133 path=${path/\%h/"$userHome"}
138 # test that a string to conforms to GPG's expiration format
140 echo "$1" | egrep -q "^[0-9]+[mwy]?$"
143 # check that a file is properly owned, and that all it's parent
144 # directories are not group/other writable
145 check_key_file_permissions() {
152 # function to check that an octal corresponds to writability
154 [ "$1" -eq 2 -o "$1" -eq 3 -o "$1" -eq 6 -o "$1" -eq 7 ]
160 # return 0 is path does not exist
161 [ -e "$path" ] || return 0
163 owner=$(stat --format '%U' "$path")
164 access=$(stat --format '%a' "$path")
165 gAccess=$(echo "$access" | cut -c2)
166 oAccess=$(echo "$access" | cut -c3)
169 if [ "$owner" != "$user" -a "$owner" != 'root' ] ; then
173 # check group/other writability
174 if is_write "$gAccess" || is_write "$oAccess" ; then
178 if [ "$path" = '/' ] ; then
181 check_key_file_permissions $(dirname "$path")
185 ### CONVERSION UTILITIES
187 # output the ssh key for a given key ID
193 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
196 # output known_hosts line from ssh key
205 echo -n "$key" | tr -d '\n'
206 echo " MonkeySphere${DATE}"
209 # output authorized_keys line from ssh key
210 ssh2authorized_keys() {
217 echo -n "$key" | tr -d '\n'
218 echo " MonkeySphere${DATE} ${userID}"
221 # convert key from gpg to ssh known_hosts format
229 # NOTE: it seems that ssh-keygen -R removes all comment fields from
230 # all lines in the known_hosts file. why?
231 # NOTE: just in case, the COMMENT can be matched with the
233 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
235 gpg2ssh "$keyID" | tr -d '\n'
236 echo " MonkeySphere${DATE}"
239 # convert key from gpg to ssh authorized_keys format
240 gpg2authorized_keys() {
247 # NOTE: just in case, the COMMENT can be matched with the
249 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
250 gpg2ssh "$keyID" | tr -d '\n'
251 echo " MonkeySphere${DATE} ${userID}"
256 # retrieve all keys with given user id from keyserver
257 # FIXME: need to figure out how to retrieve all matching keys
258 # (not just first N (5 in this case))
263 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
269 log -n " checking keyserver $KEYSERVER... "
271 gpg --quiet --batch --with-colons \
272 --command-fd 0 --keyserver "$KEYSERVER" \
273 --search ="$userID" > /dev/null 2>&1
277 # if the user is the monkeysphere user, then update the
278 # monkeysphere user's trustdb
279 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
280 gpg_authentication "--check-trustdb" > /dev/null 2>&1
286 ########################################################################
287 ### PROCESSING FUNCTIONS
289 # userid and key policy checking
290 # the following checks policy on the returned keys
291 # - checks that full key has appropriate valididy (u|f)
292 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
293 # - checks that requested user ID has appropriate validity
294 # (see /usr/share/doc/gnupg/DETAILS.gz)
295 # output is one line for every found key, in the following format:
299 # "flag" is an acceptability flag, 0 = ok, 1 = bad
300 # "fingerprint" is the fingerprint of the key
302 # expects global variable: "MODE"
305 local requiredCapability
306 local requiredPubCapability
321 # set the required key capability based on the mode
322 if [ "$MODE" = 'known_hosts' ] ; then
323 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
324 elif [ "$MODE" = 'authorized_keys' ] ; then
325 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
327 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
329 # fetch the user ID if necessary/requested
330 gpg_fetch_userid "$userID"
332 # output gpg info for (exact) userid and store
333 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
334 --with-fingerprint --with-fingerprint \
335 ="$userID" 2>/dev/null)
337 # if the gpg query return code is not 0, return 1
338 if [ "$?" -ne 0 ] ; then
339 log " no primary keys found."
343 # loop over all lines in the gpg output and process.
344 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
345 while IFS=: read -r type validity keyid uidfpr usage ; do
346 # process based on record type
348 'pub') # primary keys
349 # new key, wipe the slate
356 log " primary key found: $keyid"
358 # if overall key is not valid, skip
359 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
360 log " - unacceptable primary key validity ($validity)."
363 # if overall key is disabled, skip
364 if check_capability "$usage" 'D' ; then
365 log " - key disabled."
368 # if overall key capability is not ok, skip
369 if ! check_capability "$usage" $requiredPubCapability ; then
370 log " - unacceptable primary key capability ($usage)."
374 # mark overall key as ok
377 # mark primary key as ok if capability is ok
378 if check_capability "$usage" $requiredCapability ; then
383 if [ "$lastKey" != pub ] ; then
384 log " - got a user ID after a sub key! user IDs should only follow primary keys!"
387 # don't bother with a uid if there is no valid or reasonable primary key.
388 if [ "$keyOK" != true ] ; then
391 # if an acceptable user ID was already found, skip
392 if [ "$uidOK" ] ; then
395 # if the user ID does not match, skip
396 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
399 # if the user ID validity is not ok, skip
400 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
404 # mark user ID acceptable
407 # output a line for the primary key
409 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
410 log " * acceptable primary key."
411 if [ -z "$sshKey" ] ; then
412 log " ! primary key could not be translated (not RSA or DSA?)."
417 log " - unacceptable primary key."
418 if [ -z "$sshKey" ] ; then
419 log " ! primary key could not be translated (not RSA or DSA?)."
426 # unset acceptability of last key
431 # don't bother with sub keys if the primary key is not valid
432 if [ "$keyOK" != true ] ; then
436 # don't bother with sub keys if no user ID is acceptable:
437 if [ "$uidOK" != true ] ; then
441 # if sub key validity is not ok, skip
442 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
445 # if sub key capability is not ok, skip
446 if ! check_capability "$usage" $requiredCapability ; then
453 'fpr') # key fingerprint
454 fingerprint="$uidfpr"
456 sshKey=$(gpg2ssh "$fingerprint")
458 # if the last key was the pub key, skip
459 if [ "$lastKey" = pub ] ; then
463 # output a line for the sub key
465 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
466 log " * acceptable sub key."
467 if [ -z "$sshKey" ] ; then
468 log " ! sub key could not be translated (not RSA or DSA?)."
473 log " - unacceptable sub key."
474 if [ -z "$sshKey" ] ; then
475 log " ! sub key could not be translated (not RSA or DSA?)."
485 # process a single host in the known_host file
486 process_host_known_hosts() {
497 log "processing: $host"
499 userID="ssh://${host}"
505 for line in $(process_user_id "ssh://${host}") ; do
506 # note that key was found
509 ok=$(echo "$line" | cut -d: -f1)
510 sshKey=$(echo "$line" | cut -d: -f2)
512 if [ -z "$sshKey" ] ; then
516 # remove the old host key line, and note if removed
517 remove_line "$KNOWN_HOSTS" "$sshKey"
519 # if key OK, add new host line
520 if [ "$ok" -eq '0' ] ; then
521 # note that key was found ok
522 nKeysOK=$((nKeysOK+1))
525 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
526 # FIXME: this is really hackish cause ssh-keygen won't
527 # hash from stdin to stdout
529 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
530 ssh-keygen -H -f "$tmpfile" 2> /dev/null
531 cat "$tmpfile" >> "$KNOWN_HOSTS"
532 rm -f "$tmpfile" "${tmpfile}.old"
534 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
539 # if at least one key was found...
540 if [ "$nKeys" -gt 0 ] ; then
541 # if ok keys were found, return 0
542 if [ "$nKeysOK" -gt 0 ] ; then
548 # if no keys were found, return 1
554 # update the known_hosts file for a set of hosts listed on command
556 update_known_hosts() {
563 # the number of hosts specified on command line
569 # set the trap to remove any lockfiles on exit
570 trap "lockfile-remove $KNOWN_HOSTS" EXIT
572 # create a lockfile on known_hosts
573 lockfile-create "$KNOWN_HOSTS"
575 # note pre update file checksum
576 fileCheck="$(cat "$KNOWN_HOSTS" | md5sum)"
580 process_host_known_hosts "$host"
584 nHostsOK=$((nHostsOK+1))
587 nHostsBAD=$((nHostsBAD+1))
591 # touch the lockfile, for good measure.
592 lockfile-touch --oneshot "$KNOWN_HOSTS"
595 # remove the lockfile
596 lockfile-remove "$KNOWN_HOSTS"
598 # note if the known_hosts file was updated
599 if [ "$(cat "$KNOWN_HOSTS" | md5sum)" != "$fileCheck" ] ; then
600 log "known_hosts file updated."
603 # if an acceptable host was found, return 0
604 if [ "$nHostsOK" -gt 0 ] ; then
606 # else if no ok hosts were found...
608 # if no bad host were found then no hosts were found at all,
610 if [ "$nHostsBAD" -eq 0 ] ; then
612 # else if at least one bad host was found, return 2
619 # process hosts from a known_hosts file
620 process_known_hosts() {
623 log "processing known_hosts file..."
625 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
627 if [ -z "$hosts" ] ; then
628 log "no hosts to process."
632 # take all the hosts from the known_hosts file (first
633 # field), grep out all the hashed hosts (lines starting
635 update_known_hosts $hosts
638 # process uids for the authorized_keys file
639 process_uid_authorized_keys() {
648 log "processing: $userID"
654 for line in $(process_user_id "$userID") ; do
655 # note that key was found
658 ok=$(echo "$line" | cut -d: -f1)
659 sshKey=$(echo "$line" | cut -d: -f2)
661 if [ -z "$sshKey" ] ; then
665 # remove the old host key line
666 remove_line "$AUTHORIZED_KEYS" "$sshKey"
668 # if key OK, add new host line
669 if [ "$ok" -eq '0' ] ; then
670 # note that key was found ok
671 nKeysOK=$((nKeysOK+1))
673 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
677 # if at least one key was found...
678 if [ "$nKeys" -gt 0 ] ; then
679 # if ok keys were found, return 0
680 if [ "$nKeysOK" -gt 0 ] ; then
686 # if no keys were found, return 1
692 # update the authorized_keys files from a list of user IDs on command
694 update_authorized_keys() {
701 # the number of ids specified on command line
707 # set the trap to remove any lockfiles on exit
708 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
710 # create a lockfile on authorized_keys
711 lockfile-create "$AUTHORIZED_KEYS"
713 # note pre update file checksum
714 fileCheck="$(cat "$AUTHORIZED_KEYS" | md5sum)"
716 # remove any monkeysphere lines from authorized_keys file
717 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
720 # process the user ID, change return code if key not found for
722 process_uid_authorized_keys "$userID"
730 nIDsBAD=$((nIDsBAD+1))
734 # touch the lockfile, for good measure.
735 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
738 # remove the lockfile
739 lockfile-remove "$AUTHORIZED_KEYS"
741 # note if the authorized_keys file was updated
742 if [ "$(cat "$AUTHORIZED_KEYS" | md5sum)" != "$fileCheck" ] ; then
743 log "authorized_keys file updated."
746 # if an acceptable id was found, return 0
747 if [ "$nIDsOK" -gt 0 ] ; then
749 # else if no ok ids were found...
751 # if no bad ids were found then no ids were found at all, and
753 if [ "$nIDsBAD" -eq 0 ] ; then
755 # else if at least one bad id was found, return 2
762 # process an authorized_user_ids file for authorized_keys
763 process_authorized_user_ids() {
768 authorizedUserIDs="$1"
770 log "processing authorized_user_ids file..."
772 if ! meat "$authorizedUserIDs" > /dev/null ; then
773 log "no user IDs to process."
779 # extract user IDs from authorized_user_ids file
781 for line in $(meat "$authorizedUserIDs") ; do
782 userIDs["$nline"]="$line"
786 update_authorized_keys "${userIDs[@]}"