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 string is in the file and removed, return 0
87 if grep -q -F "$string" "$file" 2> /dev/null ; then
88 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 ### CONVERSION UTILITIES
123 # output the ssh key for a given key ID
129 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
132 # output known_hosts line from ssh key
141 echo -n "$key" | tr -d '\n'
142 echo " MonkeySphere${DATE}"
145 # output authorized_keys line from ssh key
146 ssh2authorized_keys() {
153 echo -n "$key" | tr -d '\n'
154 echo " MonkeySphere${DATE} ${userID}"
157 # convert key from gpg to ssh known_hosts format
165 # NOTE: it seems that ssh-keygen -R removes all comment fields from
166 # all lines in the known_hosts file. why?
167 # NOTE: just in case, the COMMENT can be matched with the
169 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
171 gpg2ssh "$keyID" | tr -d '\n'
172 echo " MonkeySphere${DATE}"
175 # convert key from gpg to ssh authorized_keys format
176 gpg2authorized_keys() {
183 # NOTE: just in case, the COMMENT can be matched with the
185 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
186 gpg2ssh "$keyID" | tr -d '\n'
187 echo " MonkeySphere${DATE} ${userID}"
192 # retrieve all keys with given user id from keyserver
193 # FIXME: need to figure out how to retrieve all matching keys
194 # (not just first N (5 in this case))
199 if [ "$CHECK_KEYSERVER" != 'true' ] ; then
205 log -n " checking keyserver $KEYSERVER... "
207 gpg --quiet --batch --with-colons \
208 --command-fd 0 --keyserver "$KEYSERVER" \
209 --search ="$userID" > /dev/null 2>&1
213 # if the user is the monkeysphere user, then update the
214 # monkeysphere user's trustdb
215 if [ $(id -un) = "$MONKEYSPHERE_USER" ] ; then
216 gpg_authentication "--check-trustdb" > /dev/null 2>&1
222 ########################################################################
223 ### PROCESSING FUNCTIONS
225 # userid and key policy checking
226 # the following checks policy on the returned keys
227 # - checks that full key has appropriate valididy (u|f)
228 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
229 # - checks that requested user ID has appropriate validity
230 # (see /usr/share/doc/gnupg/DETAILS.gz)
231 # output is one line for every found key, in the following format:
235 # "flag" is an acceptability flag, 0 = ok, 1 = bad
236 # "fingerprint" is the fingerprint of the key
238 # expects global variable: "MODE"
241 local requiredCapability
242 local requiredPubCapability
257 # set the required key capability based on the mode
258 if [ "$MODE" = 'known_hosts' ] ; then
259 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
260 elif [ "$MODE" = 'authorized_keys' ] ; then
261 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
263 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
265 # fetch the user ID if necessary/requested
266 gpg_fetch_userid "$userID"
268 # output gpg info for (exact) userid and store
269 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
270 --with-fingerprint --with-fingerprint \
271 ="$userID" 2>/dev/null)
273 # if the gpg query return code is not 0, return 1
274 if [ "$?" -ne 0 ] ; then
275 log " - key not found."
279 # loop over all lines in the gpg output and process.
280 # need to do it this way (as opposed to "while read...") so that
281 # variables set in loop will be visible outside of loop
282 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
283 while IFS=: read -r type validity keyid uidfpr usage ; do
284 # process based on record type
286 'pub') # primary keys
287 # new key, wipe the slate
294 log " primary key found: $keyid"
296 # if overall key is not valid, skip
297 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
298 log " - unacceptable primary key validity ($validity)."
301 # if overall key is disabled, skip
302 if check_capability "$usage" 'D' ; then
303 log " - key disabled."
306 # if overall key capability is not ok, skip
307 if ! check_capability "$usage" $requiredPubCapability ; then
308 log " - unacceptable primary key capability ($usage)."
312 # mark overall key as ok
315 # mark primary key as ok if capability is ok
316 if check_capability "$usage" $requiredCapability ; then
321 # if an acceptable user ID was already found, skip
322 if [ "$uidOK" ] ; then
325 # if the user ID does not match, skip
326 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
329 # if the user ID validity is not ok, skip
330 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
334 # mark user ID acceptable
337 # output a line for the primary key
339 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
340 log " * acceptable key found."
341 echo "0:${fingerprint}"
343 echo "1:${fingerprint}"
347 # unset acceptability of last key
352 # if sub key validity is not ok, skip
353 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
356 # if sub key capability is not ok, skip
357 if ! check_capability "$usage" $requiredCapability ; then
364 'fpr') # key fingerprint
365 fingerprint="$uidfpr"
367 # if the last key was the pub key, skip
368 if [ "$lastKey" = pub ] ; then
372 # output a line for the last subkey
374 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
375 log " * acceptable key found."
376 echo "0:${fingerprint}"
378 echo "1:${fingerprint}"
385 # process a single host in the known_host file
386 process_host_known_hosts() {
397 log "processing host: $host"
399 userID="ssh://${host}"
404 for line in $(process_user_id "ssh://${host}") ; do
405 # note that key was found
408 ok=$(echo "$line" | cut -d: -f1)
409 keyid=$(echo "$line" | cut -d: -f2)
411 sshKey=$(gpg2ssh "$keyid")
413 # remove the old host key line, and note if removed
414 remove_line "$KNOWN_HOSTS" "$sshKey"
416 # if key OK, add new host line
417 if [ "$ok" -eq '0' ] ; then
418 # note that key was found ok
419 nKeysOK=$((nKeysOK+1))
422 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
423 # FIXME: this is really hackish cause ssh-keygen won't
424 # hash from stdin to stdout
426 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
427 ssh-keygen -H -f "$tmpfile" 2> /dev/null
428 cat "$tmpfile" >> "$KNOWN_HOSTS"
429 rm -f "$tmpfile" "${tmpfile}.old"
431 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
436 # if at least one key was found...
437 if [ "$nKeys" -gt 0 ] ; then
438 # if ok keys were found, return 0
439 if [ "$nKeysOK" -gt 0 ] ; then
445 # if no keys were found, return 1
451 # update the known_hosts file for a set of hosts listed on command
453 update_known_hosts() {
459 # the number of hosts specified on command line
465 # set the trap to remove any lockfiles on exit
466 trap "lockfile-remove $KNOWN_HOSTS" EXIT
468 # create a lockfile on known_hosts
469 lockfile-create "$KNOWN_HOSTS"
473 process_host_known_hosts "$host"
477 nHostsOK=$((nHostsOK+1))
480 nHostsBAD=$((nHostsBAD+1))
484 # touch the lockfile, for good measure.
485 lockfile-touch --oneshot "$KNOWN_HOSTS"
488 # remove the lockfile
489 lockfile-remove "$KNOWN_HOSTS"
491 # note if the known_hosts file was updated
492 if [ "$nHostsOK" -gt 0 -o "$nHostsBAD" -gt 0 ] ; then
493 log "known_hosts file updated."
496 # if an acceptable host was found, return 0
497 if [ "$nHostsOK" -gt 0 ] ; then
499 # else if no ok hosts were found...
501 # if no bad host were found then no hosts were found at all,
503 if [ "$nHostsBAD" -eq 0 ] ; then
505 # else if at least one bad host was found, return 2
512 # process hosts from a known_hosts file
513 process_known_hosts() {
516 log "processing known_hosts file..."
518 hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
520 # take all the hosts from the known_hosts file (first
521 # field), grep out all the hashed hosts (lines starting
523 update_known_hosts $hosts
526 # process uids for the authorized_keys file
527 process_uid_authorized_keys() {
536 log "processing user ID: $userID"
541 for line in $(process_user_id "$userID") ; do
542 # note that key was found
545 ok=$(echo "$line" | cut -d: -f1)
546 keyid=$(echo "$line" | cut -d: -f2)
548 sshKey=$(gpg2ssh "$keyid")
550 # remove the old host key line
551 remove_line "$AUTHORIZED_KEYS" "$sshKey"
553 # if key OK, add new host line
554 if [ "$ok" -eq '0' ] ; then
555 # note that key was found ok
556 nKeysOK=$((nKeysOK+1))
558 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
562 # if at least one key was found...
563 if [ "$nKeys" -gt 0 ] ; then
564 # if ok keys were found, return 0
565 if [ "$nKeysOK" -gt 0 ] ; then
571 # if no keys were found, return 1
577 # update the authorized_keys files from a list of user IDs on command
579 update_authorized_keys() {
585 # the number of ids specified on command line
591 # set the trap to remove any lockfiles on exit
592 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
594 # create a lockfile on authorized_keys
595 lockfile-create "$AUTHORIZED_KEYS"
598 # process the user ID, change return code if key not found for
600 process_uid_authorized_keys "$userID"
608 nIDsBAD=$((nIDsBAD+1))
612 # touch the lockfile, for good measure.
613 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
616 # remove the lockfile
617 lockfile-remove "$AUTHORIZED_KEYS"
619 # note if the authorized_keys file was updated
620 if [ "$nIDsOK" -gt 0 -o "$nIDsBAD" -gt 0 ] ; then
621 log "authorized_keys file updated."
624 # if an acceptable id was found, return 0
625 if [ "$nIDsOK" -gt 0 ] ; then
627 # else if no ok ids were found...
629 # if no bad ids were found then no ids were found at all, and
631 if [ "$nIDsBAD" -eq 0 ] ; then
633 # else if at least one bad id was found, return 2
640 # process an authorized_user_ids file for authorized_keys
641 process_authorized_user_ids() {
645 authorizedUserIDs="$1"
647 log "processing authorized_user_ids file..."
649 # extract user IDs from authorized_user_ids file
650 for line in $(seq 1 $(meat "$authorizedUserIDs" | wc -l)) ; do
651 userIDs[$((line-1))]=$(cutline "$line" "$authorizedUserIDs")
654 update_authorized_keys "${userIDs[@]}"
657 # EXPERIMENTAL (unused) process userids found in authorized_keys file
658 # go through line-by-line, extract monkeysphere userids from comment
659 # fields, and process each userid
661 process_authorized_keys() {
666 # default return code is 0, and is set to 1 if a key for a user
672 # take all the monkeysphere userids from the authorized_keys file
673 # comment field (third field) that starts with "MonkeySphere uid:"
674 # FIXME: needs to handle authorized_keys options (field 0)
675 meat "$authorizedKeys" | \
676 while read -r options keytype key comment ; do
677 # if the comment field is empty, assume the third field was
679 if [ -z "$comment" ] ; then
683 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
686 userID=$(echo "$comment" | awk "{ print $2 }")
687 if [ -z "$userID" ] ; then
692 log "processing userid: '$userID'"
693 process_user_id "$userID" > /dev/null || returnCode=1