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 the string is in the file and removed, return 0
83 if grep -q -F "$string" "$file" 2> /dev/null ; then
84 grep -v -F "$string" "$file" | sponge "$file"
93 # translate ssh-style path variables %h and %u
94 translate_ssh_variables() {
101 # get the user's home directory
102 userHome=$(getent passwd "$uname" | cut -d: -f6)
104 # translate '%u' to user name
105 path=${path/\%u/"$uname"}
106 # translate '%h' to user home directory
107 path=${path/\%h/"$userHome"}
112 # test that a string to conforms to GPG's expiration format
114 echo "$1" | egrep -q "^[0-9][mwy]?$"
117 ### CONVERSION UTILITIES
119 # output the ssh key for a given key ID
125 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
128 # output known_hosts line from ssh key
137 echo -n "$key" | tr -d '\n'
138 echo " MonkeySphere${DATE}"
141 # output authorized_keys line from ssh key
142 ssh2authorized_keys() {
149 echo -n "$key" | tr -d '\n'
150 echo " MonkeySphere${DATE} ${userID}"
153 # convert key from gpg to ssh known_hosts format
161 # NOTE: it seems that ssh-keygen -R removes all comment fields from
162 # all lines in the known_hosts file. why?
163 # NOTE: just in case, the COMMENT can be matched with the
165 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
167 gpg2ssh "$keyID" | tr -d '\n'
168 echo " MonkeySphere${DATE}"
171 # convert key from gpg to ssh authorized_keys format
172 gpg2authorized_keys() {
179 # NOTE: just in case, the COMMENT can be matched with the
181 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
182 gpg2ssh "$keyID" | tr -d '\n'
183 echo " MonkeySphere${DATE} ${userID}"
188 # retrieve all keys with given user id from keyserver
189 # FIXME: need to figure out how to retrieve all matching keys
190 # (not just first N (5 in this case))
195 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
201 log -n " checking keyserver $KEYSERVER... "
203 gpg --quiet --batch --with-colons \
204 --command-fd 0 --keyserver "$KEYSERVER" \
205 --search ="$userID" > /dev/null 2>&1
209 # if the user is the monkeysphere user, then update the
210 # monkeysphere user's trustdb
211 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
212 gpg_authentication "--check-trustdb" > /dev/null 2>&1
218 ########################################################################
219 ### PROCESSING FUNCTIONS
221 # userid and key policy checking
222 # the following checks policy on the returned keys
223 # - checks that full key has appropriate valididy (u|f)
224 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
225 # - checks that requested user ID has appropriate validity
226 # (see /usr/share/doc/gnupg/DETAILS.gz)
227 # output is one line for every found key, in the following format:
231 # "flag" is an acceptability flag, 0 = ok, 1 = bad
232 # "fingerprint" is the fingerprint of the key
234 # expects global variable: "MODE"
237 local requiredCapability
238 local requiredPubCapability
253 # set the required key capability based on the mode
254 if [ "$MODE" = 'known_hosts' ] ; then
255 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
256 elif [ "$MODE" = 'authorized_keys' ] ; then
257 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
259 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
261 # fetch the user ID if necessary/requested
262 gpg_fetch_userid "$userID"
264 # output gpg info for (exact) userid and store
265 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
266 --with-fingerprint --with-fingerprint \
267 ="$userID" 2>/dev/null)
269 # if the gpg query return code is not 0, return 1
270 if [ "$?" -ne 0 ] ; then
271 log " - key not found."
275 # loop over all lines in the gpg output and process.
276 # need to do it this way (as opposed to "while read...") so that
277 # variables set in loop will be visible outside of loop
278 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
279 while IFS=: read -r type validity keyid uidfpr usage ; do
280 # process based on record type
282 'pub') # primary keys
283 # new key, wipe the slate
290 log " primary key found: $keyid"
292 # if overall key is not valid, skip
293 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
294 log " - unacceptable primary key validity ($validity)."
297 # if overall key is disabled, skip
298 if check_capability "$usage" 'D' ; then
299 log " - key disabled."
302 # if overall key capability is not ok, skip
303 if ! check_capability "$usage" $requiredPubCapability ; then
304 log " - unacceptable primary key capability ($usage)."
308 # mark overall key as ok
311 # mark primary key as ok if capability is ok
312 if check_capability "$usage" $requiredCapability ; then
317 # if an acceptable user ID was already found, skip
318 if [ "$uidOK" ] ; then
321 # if the user ID does not match, skip
322 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
325 # if the user ID validity is not ok, skip
326 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
330 # mark user ID acceptable
333 # output a line for the primary key
335 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
336 log " * acceptable key found."
337 echo "0:${fingerprint}"
339 echo "1:${fingerprint}"
343 # unset acceptability of last key
348 # if sub key validity is not ok, skip
349 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
352 # if sub key capability is not ok, skip
353 if ! check_capability "$usage" $requiredCapability ; then
360 'fpr') # key fingerprint
361 fingerprint="$uidfpr"
363 # if the last key was the pub key, skip
364 if [ "$lastKey" = pub ] ; then
368 # output a line for the last subkey
370 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
371 log " * acceptable key found."
372 echo "0:${fingerprint}"
374 echo "1:${fingerprint}"
381 # process a single host in the known_host file
382 process_host_known_hosts() {
393 log "processing host: $host"
395 userID="ssh://${host}"
400 for line in $(process_user_id "ssh://${host}") ; do
401 # note that key was found
404 ok=$(echo "$line" | cut -d: -f1)
405 keyid=$(echo "$line" | cut -d: -f2)
407 sshKey=$(gpg2ssh "$keyid")
409 # remove the old host key line, and note if removed
410 remove_line "$KNOWN_HOSTS" "$sshKey"
412 # if key OK, add new host line
413 if [ "$ok" -eq '0' ] ; then
414 # note that key was found ok
415 nKeysOK=$((nKeysOK+1))
418 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
419 # FIXME: this is really hackish cause ssh-keygen won't
420 # hash from stdin to stdout
422 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
423 ssh-keygen -H -f "$tmpfile" 2> /dev/null
424 cat "$tmpfile" >> "$KNOWN_HOSTS"
425 rm -f "$tmpfile" "${tmpfile}.old"
427 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
432 # if at least one key was found...
433 if [ "$nKeys" -gt 0 ] ; then
434 # if ok keys were found, return 0
435 if [ "$nKeysOK" -gt 0 ] ; then
441 # if no keys were found, return 1
447 # update the known_hosts file for a set of hosts listed on command
449 update_known_hosts() {
455 # the number of hosts specified on command line
461 # set the trap to remove any lockfiles on exit
462 trap "lockfile-remove $KNOWN_HOSTS" EXIT
464 # create a lockfile on known_hosts
465 lockfile-create "$KNOWN_HOSTS"
469 process_host_known_hosts "$host"
473 nHostsOK=$((nHostsOK+1))
476 nHostsBAD=$((nHostsBAD+1))
480 # touch the lockfile, for good measure.
481 lockfile-touch --oneshot "$KNOWN_HOSTS"
484 # remove the lockfile
485 lockfile-remove "$KNOWN_HOSTS"
487 # note if the known_hosts file was updated
488 if [ "$nHostsOK" -gt 0 -o "$nHostsBAD" -gt 0 ] ; then
489 log "known_hosts file updated."
492 # if an acceptable host was found, return 0
493 if [ "$nHostsOK" -gt 0 ] ; then
495 # else if no ok hosts were found...
497 # if no bad host were found then no hosts were found at all,
499 if [ "$nHostsBAD" -eq 0 ] ; then
501 # else if at least one bad host was found, return 2
508 # process hosts from a known_hosts file
509 process_known_hosts() {
512 log "processing known_hosts file..."
514 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
516 # take all the hosts from the known_hosts file (first
517 # field), grep out all the hashed hosts (lines starting
519 update_known_hosts $hosts
522 # process uids for the authorized_keys file
523 process_uid_authorized_keys() {
532 log "processing user ID: $userID"
537 for line in $(process_user_id "$userID") ; do
538 # note that key was found
541 ok=$(echo "$line" | cut -d: -f1)
542 keyid=$(echo "$line" | cut -d: -f2)
544 sshKey=$(gpg2ssh "$keyid")
546 # remove the old host key line
547 remove_line "$AUTHORIZED_KEYS" "$sshKey"
549 # if key OK, add new host line
550 if [ "$ok" -eq '0' ] ; then
551 # note that key was found ok
552 nKeysOK=$((nKeysOK+1))
554 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
558 # if at least one key was found...
559 if [ "$nKeys" -gt 0 ] ; then
560 # if ok keys were found, return 0
561 if [ "$nKeysOK" -gt 0 ] ; then
567 # if no keys were found, return 1
573 # update the authorized_keys files from a list of user IDs on command
575 update_authorized_keys() {
581 # the number of ids specified on command line
587 # set the trap to remove any lockfiles on exit
588 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
590 # create a lockfile on authorized_keys
591 lockfile-create "$AUTHORIZED_KEYS"
594 # process the user ID, change return code if key not found for
596 process_uid_authorized_keys "$userID"
604 nIDsBAD=$((nIDsBAD+1))
608 # touch the lockfile, for good measure.
609 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
612 # remove the lockfile
613 lockfile-remove "$AUTHORIZED_KEYS"
615 # note if the authorized_keys file was updated
616 if [ "$nIDsOK" -gt 0 -o "$nIDsBAD" -gt 0 ] ; then
617 log "authorized_keys file updated."
620 # if an acceptable id was found, return 0
621 if [ "$nIDsOK" -gt 0 ] ; then
623 # else if no ok ids were found...
625 # if no bad ids were found then no ids were found at all, and
627 if [ "$nIDsBAD" -eq 0 ] ; then
629 # else if at least one bad id was found, return 2
636 # process an authorized_user_ids file for authorized_keys
637 process_authorized_user_ids() {
641 authorizedUserIDs="$1"
643 log "processing authorized_user_ids file..."
645 # extract user IDs from authorized_user_ids file
646 for line in $(seq 1 $(meat "$authorizedUserIDs" | wc -l)) ; do
647 userIDs[$((line-1))]=$(cutline "$line" "$authorizedUserIDs")
650 update_authorized_keys "${userIDs[@]}"
653 # EXPERIMENTAL (unused) process userids found in authorized_keys file
654 # go through line-by-line, extract monkeysphere userids from comment
655 # fields, and process each userid
657 process_authorized_keys() {
662 # default return code is 0, and is set to 1 if a key for a user
668 # take all the monkeysphere userids from the authorized_keys file
669 # comment field (third field) that starts with "MonkeySphere uid:"
670 # FIXME: needs to handle authorized_keys options (field 0)
671 meat "$authorizedKeys" | \
672 while read -r options keytype key comment ; do
673 # if the comment field is empty, assume the third field was
675 if [ -z "$comment" ] ; then
679 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
682 userID=$(echo "$comment" | awk "{ print $2 }")
683 if [ -z "$userID" ] ; then
688 log "processing userid: '$userID'"
689 process_user_id "$userID" > /dev/null || returnCode=1