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 [ ! -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 an acceptable user ID was already found, skip
384 if [ "$uidOK" ] ; then
387 # if the user ID does not match, skip
388 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
391 # if the user ID validity is not ok, skip
392 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
396 # mark user ID acceptable
399 # output a line for the primary key
401 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
402 log " * acceptable primary key."
403 if [ -z "$sshKey" ] ; then
404 log " ! primary key could not be translated."
409 log " - unacceptable primary key."
410 if [ -z "$sshKey" ] ; then
411 log " ! primary key could not be translated."
418 # unset acceptability of last key
423 # if sub key validity is not ok, skip
424 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
427 # if sub key capability is not ok, skip
428 if ! check_capability "$usage" $requiredCapability ; then
435 'fpr') # key fingerprint
436 fingerprint="$uidfpr"
438 sshKey=$(gpg2ssh "$fingerprint")
440 # if the last key was the pub key, skip
441 if [ "$lastKey" = pub ] ; then
445 # output a line for the primary key
447 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
448 log " * acceptable sub key."
449 if [ -z "$sshKey" ] ; then
450 log " ! sub key could not be translated."
455 log " - unacceptable sub key."
456 if [ -z "$sshKey" ] ; then
457 log " ! sub key could not be translated."
467 # process a single host in the known_host file
468 process_host_known_hosts() {
479 log "processing: $host"
481 userID="ssh://${host}"
487 for line in $(process_user_id "ssh://${host}") ; do
488 # note that key was found
491 ok=$(echo "$line" | cut -d: -f1)
492 sshKey=$(echo "$line" | cut -d: -f2)
494 if [ -z "$sshKey" ] ; then
498 # remove the old host key line, and note if removed
499 remove_line "$KNOWN_HOSTS" "$sshKey"
501 # if key OK, add new host line
502 if [ "$ok" -eq '0' ] ; then
503 # note that key was found ok
504 nKeysOK=$((nKeysOK+1))
507 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
508 # FIXME: this is really hackish cause ssh-keygen won't
509 # hash from stdin to stdout
511 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
512 ssh-keygen -H -f "$tmpfile" 2> /dev/null
513 cat "$tmpfile" >> "$KNOWN_HOSTS"
514 rm -f "$tmpfile" "${tmpfile}.old"
516 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
521 # if at least one key was found...
522 if [ "$nKeys" -gt 0 ] ; then
523 # if ok keys were found, return 0
524 if [ "$nKeysOK" -gt 0 ] ; then
530 # if no keys were found, return 1
536 # update the known_hosts file for a set of hosts listed on command
538 update_known_hosts() {
545 # the number of hosts specified on command line
551 # set the trap to remove any lockfiles on exit
552 trap "lockfile-remove $KNOWN_HOSTS" EXIT
554 # create a lockfile on known_hosts
555 lockfile-create "$KNOWN_HOSTS"
557 # note pre update file checksum
558 fileCheck="$(cat "$KNOWN_HOSTS" | md5sum)"
562 process_host_known_hosts "$host"
566 nHostsOK=$((nHostsOK+1))
569 nHostsBAD=$((nHostsBAD+1))
573 # touch the lockfile, for good measure.
574 lockfile-touch --oneshot "$KNOWN_HOSTS"
577 # remove the lockfile
578 lockfile-remove "$KNOWN_HOSTS"
580 # note if the known_hosts file was updated
581 if [ "$(cat "$KNOWN_HOSTS" | md5sum)" != "$fileCheck" ] ; then
582 log "known_hosts file updated."
585 # if an acceptable host was found, return 0
586 if [ "$nHostsOK" -gt 0 ] ; then
588 # else if no ok hosts were found...
590 # if no bad host were found then no hosts were found at all,
592 if [ "$nHostsBAD" -eq 0 ] ; then
594 # else if at least one bad host was found, return 2
601 # process hosts from a known_hosts file
602 process_known_hosts() {
605 log "processing known_hosts file..."
607 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
609 if [ -z "$hosts" ] ; then
610 log "no hosts to process."
614 # take all the hosts from the known_hosts file (first
615 # field), grep out all the hashed hosts (lines starting
617 update_known_hosts $hosts
620 # process uids for the authorized_keys file
621 process_uid_authorized_keys() {
630 log "processing: $userID"
636 for line in $(process_user_id "$userID") ; do
637 # note that key was found
640 ok=$(echo "$line" | cut -d: -f1)
641 sshKey=$(echo "$line" | cut -d: -f2)
643 if [ -z "$sshKey" ] ; then
647 # remove the old host key line
648 remove_line "$AUTHORIZED_KEYS" "$sshKey"
650 # if key OK, add new host line
651 if [ "$ok" -eq '0' ] ; then
652 # note that key was found ok
653 nKeysOK=$((nKeysOK+1))
655 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
659 # if at least one key was found...
660 if [ "$nKeys" -gt 0 ] ; then
661 # if ok keys were found, return 0
662 if [ "$nKeysOK" -gt 0 ] ; then
668 # if no keys were found, return 1
674 # update the authorized_keys files from a list of user IDs on command
676 update_authorized_keys() {
683 # the number of ids specified on command line
689 # set the trap to remove any lockfiles on exit
690 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
692 # create a lockfile on authorized_keys
693 lockfile-create "$AUTHORIZED_KEYS"
695 # note pre update file checksum
696 fileCheck="$(cat "$AUTHORIZED_KEYS" | md5sum)"
698 # remove any monkeysphere lines from authorized_keys file
699 remove_monkeysphere_lines "$AUTHORIZED_KEYS"
702 # process the user ID, change return code if key not found for
704 process_uid_authorized_keys "$userID"
712 nIDsBAD=$((nIDsBAD+1))
716 # touch the lockfile, for good measure.
717 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
720 # remove the lockfile
721 lockfile-remove "$AUTHORIZED_KEYS"
723 # note if the authorized_keys file was updated
724 if [ "$(cat "$AUTHORIZED_KEYS" | md5sum)" != "$fileCheck" ] ; then
725 log "authorized_keys file updated."
728 # if an acceptable id was found, return 0
729 if [ "$nIDsOK" -gt 0 ] ; then
731 # else if no ok ids were found...
733 # if no bad ids were found then no ids were found at all, and
735 if [ "$nIDsBAD" -eq 0 ] ; then
737 # else if at least one bad id was found, return 2
744 # process an authorized_user_ids file for authorized_keys
745 process_authorized_user_ids() {
750 authorizedUserIDs="$1"
752 log "processing authorized_user_ids file..."
754 if ! meat "$authorizedUserIDs" > /dev/null ; then
755 log "no user IDs to process."
761 # extract user IDs from authorized_user_ids file
763 for line in $(meat "$authorizedUserIDs") ; do
764 userIDs["$nline"]="$line"
768 update_authorized_keys "${userIDs[@]}"