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 ########################################################################
33 # write output to stderr
43 # cut out all comments(#) and blank lines from standard input
45 grep -v -e "^[[:space:]]*#" -e '^$' "$1"
48 # cut a specified line from standard input
50 head --line="$1" "$2" | tail -1
53 # check that characters are in a string (in an AND fashion).
54 # used for checking key capability
55 # check_capability capability a [b...]
64 if echo "$usage" | grep -q -v "$capcheck" ; then
71 # convert escaped characters from gpg output back into original
73 # FIXME: undo all escape character translation in with-colons gpg output
75 echo "$1" | sed 's/\\x3a/:/'
78 # remove all lines with specified string from specified file
86 # if the line is there are removed, return 0
87 if [ "$file" -a "$string" ] ; then
88 grep -v "$string" "$file" | sponge "$file"
96 # translate ssh-style path variables %h and %u
97 translate_ssh_variables() {
104 # get the user's home directory
105 userHome=$(getent passwd "$uname" | cut -d: -f6)
107 # translate '%u' to user name
108 path=${path/\%u/"$uname"}
109 # translate '%h' to user home directory
110 path=${path/\%h/"$userHome"}
115 ### CONVERSION UTILITIES
117 # output the ssh key for a given key ID
123 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
126 # output known_hosts line from ssh key
135 echo -n "$key" | tr -d '\n'
136 echo " MonkeySphere${DATE}"
139 # output authorized_keys line from ssh key
140 ssh2authorized_keys() {
147 echo -n "$key" | tr -d '\n'
148 echo " MonkeySphere${DATE} ${userID}"
151 # convert key from gpg to ssh known_hosts format
159 # NOTE: it seems that ssh-keygen -R removes all comment fields from
160 # all lines in the known_hosts file. why?
161 # NOTE: just in case, the COMMENT can be matched with the
163 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
165 gpg2ssh "$keyID" | tr -d '\n'
166 echo " MonkeySphere${DATE}"
169 # convert key from gpg to ssh authorized_keys format
170 gpg2authorized_keys() {
177 # NOTE: just in case, the COMMENT can be matched with the
179 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
180 gpg2ssh "$keyID" | tr -d '\n'
181 echo " MonkeySphere${DATE} ${userID}"
186 # retrieve all keys with given user id from keyserver
187 # FIXME: need to figure out how to retrieve all matching keys
188 # (not just first N (5 in this case))
193 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
199 log -n " checking keyserver $KEYSERVER... "
201 gpg --quiet --batch --with-colons \
202 --command-fd 0 --keyserver "$KEYSERVER" \
203 --search ="$userID" > /dev/null 2>&1
207 # if the user is the monkeysphere user, then update the
208 # monkeysphere user's trustdb
209 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
210 gpg_authentication "--check-trustdb" > /dev/null 2>&1
216 ########################################################################
217 ### PROCESSING FUNCTIONS
219 # userid and key policy checking
220 # the following checks policy on the returned keys
221 # - checks that full key has appropriate valididy (u|f)
222 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
223 # - checks that requested user ID has appropriate validity
224 # (see /usr/share/doc/gnupg/DETAILS.gz)
225 # output is one line for every found key, in the following format:
229 # "flag" is an acceptability flag, 0 = ok, 1 = bad
230 # "fingerprint" is the fingerprint of the key
232 # expects global variable: "MODE"
235 local requiredCapability
236 local requiredPubCapability
251 # set the required key capability based on the mode
252 if [ "$MODE" = 'known_hosts' ] ; then
253 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
254 elif [ "$MODE" = 'authorized_keys' ] ; then
255 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
257 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
259 # output gpg info for (exact) userid and store
260 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
261 --with-fingerprint --with-fingerprint \
262 ="$userID" 2>/dev/null)
264 # fetch the user ID if necessary/requested
265 gpg_fetch_userid "$userID"
267 # if the gpg query return code is not 0, return 1
268 if [ "$?" -ne 0 ] ; then
269 log " - key not found."
273 # loop over all lines in the gpg output and process.
274 # need to do it this way (as opposed to "while read...") so that
275 # variables set in loop will be visible outside of loop
276 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
277 while IFS=: read -r type validity keyid uidfpr usage ; do
278 # process based on record type
280 'pub') # primary keys
281 # new key, wipe the slate
288 log " primary key found: $keyid"
290 # if overall key is not valid, skip
291 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
292 log " - unacceptable primary key validity ($validity)."
295 # if overall key is disabled, skip
296 if check_capability "$usage" 'D' ; then
297 log " - key disabled."
300 # if overall key capability is not ok, skip
301 if ! check_capability "$usage" $requiredPubCapability ; then
302 log " - unacceptable primary key capability ($usage)."
306 # mark overall key as ok
309 # mark primary key as ok if capability is ok
310 if check_capability "$usage" $requiredCapability ; then
315 # if an acceptable user ID was already found, skip
316 if [ "$uidOK" ] ; then
319 # if the user ID does not match, skip
320 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
323 # if the user ID validity is not ok, skip
324 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
328 # mark user ID acceptable
331 # output a line for the primary key
333 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
334 log " * acceptable key found."
335 echo "0:${fingerprint}"
337 echo "1:${fingerprint}"
341 # unset acceptability of last key
346 # if sub key validity is not ok, skip
347 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
350 # if sub key capability is not ok, skip
351 if ! check_capability "$usage" $requiredCapability ; then
358 'fpr') # key fingerprint
359 fingerprint="$uidfpr"
361 # if the last key was the pub key, skip
362 if [ "$lastKey" = pub ] ; then
366 # output a line for the last subkey
368 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
369 log " * acceptable key found."
370 echo "0:${fingerprint}"
372 echo "1:${fingerprint}"
379 # process a single host in the known_host file
380 process_host_known_hosts() {
391 log "processing host: $host"
393 userID="ssh://${host}"
395 for line in $(process_user_id "ssh://${host}") ; do
396 ok=$(echo "$line" | cut -d: -f1)
397 keyid=$(echo "$line" | cut -d: -f2)
399 sshKey=$(gpg2ssh "$keyid")
401 # remove the old host key line, and note if removed
402 remove_line "$KNOWN_HOSTS" "$sshKey" && idRemoved=true
404 # if key OK, add new host line
405 if [ "$ok" -eq '0' ] ; then
407 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
408 # FIXME: this is really hackish cause ssh-keygen won't
409 # hash from stdin to stdout
411 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
412 ssh-keygen -H -f "$tmpfile" 2> /dev/null
413 cat "$tmpfile" >> "$KNOWN_HOSTS"
414 rm -f "$tmpfile" "${tmpfile}.old"
416 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
419 # note that at least one ok id was found
424 # if at least one ok id was found, return 0
425 if [ "$idOK" ] ; then
428 # if ids were only removed, return 2
429 elif [ "$idRemoved" ] ; then
432 # else return 1, to indicate nothing happened
438 # update the known_hosts file for a set of hosts listed on command
440 update_known_hosts() {
446 # the number of hosts specified on command line
452 # set the trap to remove any lockfiles on exit
453 trap "lockfile-remove $KNOWN_HOSTS" EXIT
455 # create a lockfile on known_hosts
456 lockfile-create "$KNOWN_HOSTS"
460 process_host_known_hosts "$host"
464 nHostsOK=$((nHostsOK+1))
467 nHostsBAD=$((nHostsBAD+1))
471 # touch the lockfile, for good measure.
472 lockfile-touch --oneshot "$KNOWN_HOSTS"
475 # remove the lockfile
476 lockfile-remove "$KNOWN_HOSTS"
478 # note if the known_hosts file was updated
479 if [ "$nHostsOK" -gt 0 -o "$nHostsBAD" -gt 0 ] ; then
480 log "known_hosts file updated."
483 # if all hosts were OK, return 0
484 if [ "$nHostsOK" -eq "$nHosts" ] ; then
487 # if all hosts were BAD, return 2
488 elif [ "$nHostsBAD" -eq "$nHosts" ] ; then
497 # process hosts from a known_hosts file
498 process_known_hosts() {
501 log "processing known_hosts file..."
503 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
505 # take all the hosts from the known_hosts file (first
506 # field), grep out all the hashed hosts (lines starting
508 update_known_hosts $hosts
511 # process uids for the authorized_keys file
512 process_uid_authorized_keys() {
521 log "processing user ID: $userID"
523 for line in $(process_user_id "$userID") ; do
524 ok=$(echo "$line" | cut -d: -f1)
525 keyid=$(echo "$line" | cut -d: -f2)
527 sshKey=$(gpg2ssh "$keyid")
529 # remove the old host key line
530 remove_line "$AUTHORIZED_KEYS" "$sshKey" && idRemoved=true
532 # if key OK, add new host line
533 if [ "$ok" -eq '0' ] ; then
534 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
536 # note that at least one ok id was found
541 # if at least one ok id was found, return 0
542 if [ "$idOK" ] ; then
545 # if ids were only removed, return 2
546 elif [ "$idRemoved" ] ; then
549 # else return 1, to indicate nothing happened
555 # update the authorized_keys files from a list of user IDs on command
557 update_authorized_keys() {
563 # the number of ids specified on command line
569 # set the trap to remove any lockfiles on exit
570 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
572 # create a lockfile on authorized_keys
573 lockfile-create "$AUTHORIZED_KEYS"
576 # process the user ID, change return code if key not found for
578 process_uid_authorized_keys "$userID"
586 nIDsBAD=$((nIDsBAD+1))
590 # touch the lockfile, for good measure.
591 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
594 # remove the lockfile
595 lockfile-remove "$AUTHORIZED_KEYS"
597 # note if the authorized_keys file was updated
598 if [ "$nIDsOK" -gt 0 -o "$nIDsBAD" -gt 0 ] ; then
599 log "authorized_keys file updated."
602 # if all ids were OK, return 0
603 if [ "$nIDsOK" -eq "$nIDs" ] ; then
606 # if all ids were BAD, return 2
607 elif [ "$nIDsBAD" -eq "$nIDs" ] ; then
616 # process an authorized_user_ids file for authorized_keys
617 process_authorized_user_ids() {
621 authorizedUserIDs="$1"
623 log "processing authorized_user_ids file..."
625 # extract user IDs from authorized_user_ids file
626 for line in $(seq 1 $(meat "$authorizedUserIDs" | wc -l)) ; do
627 userIDs[$((line-1))]=$(cutline "$line" "$authorizedUserIDs")
630 update_authorized_keys "${userIDs[@]}"
633 # EXPERIMENTAL (unused) process userids found in authorized_keys file
634 # go through line-by-line, extract monkeysphere userids from comment
635 # fields, and process each userid
637 process_authorized_keys() {
642 # default return code is 0, and is set to 1 if a key for a user
648 # take all the monkeysphere userids from the authorized_keys file
649 # comment field (third field) that starts with "MonkeySphere uid:"
650 # FIXME: needs to handle authorized_keys options (field 0)
651 meat "$authorizedKeys" | \
652 while read -r options keytype key comment ; do
653 # if the comment field is empty, assume the third field was
655 if [ -z "$comment" ] ; then
659 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
662 userID=$(echo "$comment" | awk "{ print $2 }")
663 if [ -z "$userID" ] ; then
668 log "processing userid: '$userID'"
669 process_user_id "$userID" > /dev/null || returnCode=1