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"
19 CACHE="/var/cache/monkeysphere"
22 ########################################################################
35 # write output to stderr
45 # cut out all comments(#) and blank lines from standard input
47 grep -v -e "^[[:space:]]*#" -e '^$'
50 # cut a specified line from standard input
52 head --line="$1" | tail -1
55 # check that characters are in a string (in an AND fashion).
56 # used for checking key capability
57 # check_capability capability a [b...]
66 if echo "$usage" | grep -q -v "$capcheck" ; then
73 # convert escaped characters from gpg output back into original
75 # FIXME: undo all escape character translation in with-colons gpg output
77 echo "$1" | sed 's/\\x3a/:/'
80 # remove all lines with specified string from specified file
88 if [ "$file" -a "$string" ] ; then
89 grep -v "$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 ### CONVERSION UTILITIES
114 # output the ssh key for a given key ID
120 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
123 # output the ssh key for a given secret key ID
128 # only use last 16 characters until openpgp2ssh can take all 40 #TMP
129 keyID=$(echo "$1" | cut -c 25-) #TMP
131 gpg --export-secret-key "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
134 # output known_hosts line from ssh key
143 echo -n "$key" | tr -d '\n'
144 echo " MonkeySphere${DATE}"
147 # output authorized_keys line from ssh key
148 ssh2authorized_keys() {
155 echo -n "$key" | tr -d '\n'
156 echo " MonkeySphere${DATE} ${userID}"
159 # convert key from gpg to ssh known_hosts format
167 # NOTE: it seems that ssh-keygen -R removes all comment fields from
168 # all lines in the known_hosts file. why?
169 # NOTE: just in case, the COMMENT can be matched with the
171 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
173 gpg2ssh "$keyID" | tr -d '\n'
174 echo " MonkeySphere${DATE}"
177 # convert key from gpg to ssh authorized_keys format
178 gpg2authorized_keys() {
185 # NOTE: just in case, the COMMENT can be matched with the
187 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
188 gpg2ssh "$keyID" | tr -d '\n'
189 echo " MonkeySphere${DATE} ${userID}"
194 # retrieve all keys with given user id from keyserver
195 # FIXME: need to figure out how to retrieve all matching keys
196 # (not just first N (5 in this case))
202 log -n " checking keyserver $KEYSERVER... "
204 gpg --quiet --batch --with-colons \
205 --command-fd 0 --keyserver "$KEYSERVER" \
206 --search ="$userID" > /dev/null 2>&1
210 # get the full fingerprint of a key ID
211 get_key_fingerprint() {
216 gpg --list-key --with-colons --fixed-list-mode \
217 --with-fingerprint --with-fingerprint "$keyID" | \
218 grep '^fpr:' | grep "$keyID" | cut -d: -f10
221 ########################################################################
222 ### PROCESSING FUNCTIONS
224 # userid and key policy checking
225 # the following checks policy on the returned keys
226 # - checks that full key has appropriate valididy (u|f)
227 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
228 # - checks that requested user ID has appropriate validity
229 # (see /usr/share/doc/gnupg/DETAILS.gz)
230 # output is one line for every found key, in the following format:
234 # "flag" is an acceptability flag, 0 = ok, 1 = bad
235 # "fingerprint" is the fingerprint of the key
237 # expects global variable: "MODE"
240 local requiredCapability
241 local requiredPubCapability
256 # set the required key capability based on the mode
257 if [ "$MODE" = 'known_hosts' ] ; then
258 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
259 elif [ "$MODE" = 'authorized_keys' ] ; then
260 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
262 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
264 # if CHECK_KEYSERVER variable set to true, check the keyserver
266 if [ "$CHECK_KEYSERVER" = "true" ] ; then
267 gpg_fetch_userid "$userID"
270 # output gpg info for (exact) userid and store
271 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
272 --with-fingerprint --with-fingerprint \
273 ="$userID" 2>/dev/null)
275 # if the gpg query return code is not 0, return 1
276 if [ "$?" -ne 0 ] ; then
277 log " - key not found."
281 # loop over all lines in the gpg output and process.
282 # need to do it this way (as opposed to "while read...") so that
283 # variables set in loop will be visible outside of loop
284 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
285 while IFS=: read -r type validity keyid uidfpr usage ; do
286 # process based on record type
288 'pub') # primary keys
289 # new key, wipe the slate
296 log " primary key found: $keyid"
298 # if overall key is not valid, skip
299 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
300 log " - unacceptable primary key validity ($validity)."
303 # if overall key is disabled, skip
304 if check_capability "$usage" 'D' ; then
305 log " - key disabled."
308 # if overall key capability is not ok, skip
309 if ! check_capability "$usage" $requiredPubCapability ; then
310 log " - unacceptable primary key capability ($usage)."
314 # mark overall key as ok
317 # mark primary key as ok if capability is ok
318 if check_capability "$usage" $requiredCapability ; then
323 # if an acceptable user ID was already found, skip
324 if [ "$uidOK" ] ; then
327 # if the user ID does not match, skip
328 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
331 # if the user ID validity is not ok, skip
332 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
336 # mark user ID acceptable
339 # output a line for the primary key
341 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
342 log " * acceptable key found."
343 echo "0:${fingerprint}"
345 echo "1:${fingerprint}"
349 # unset acceptability of last key
354 # if sub key validity is not ok, skip
355 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
358 # if sub key capability is not ok, skip
359 if ! check_capability "$usage" $requiredCapability ; then
366 'fpr') # key fingerprint
367 fingerprint="$uidfpr"
369 # if the last key was the pub key, skip
370 if [ "$lastKey" = pub ] ; then
374 # output a line for the last subkey
376 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
377 log " * acceptable key found."
378 echo "0:${fingerprint}"
380 echo "1:${fingerprint}"
387 # process a single host in the known_host file
388 process_host_known_hosts() {
396 # default return code is 1, which assumes no key was found
401 log "processing host: $host"
403 userID="ssh://${host}"
405 for line in $(process_user_id "ssh://${host}") ; do
406 ok=$(echo "$line" | cut -d: -f1)
407 keyid=$(echo "$line" | cut -d: -f2)
409 sshKey=$(gpg2ssh "$keyid")
410 # remove the old host key line
411 remove_line "$KNOWN_HOSTS" "$sshKey"
412 # if key OK, add new host line
413 if [ "$ok" -eq '0' ] ; then
415 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
416 # FIXME: this is really hackish cause ssh-keygen won't
417 # hash from stdin to stdout
419 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
420 ssh-keygen -H -f "$tmpfile" 2> /dev/null
421 cat "$tmpfile" >> "$KNOWN_HOSTS"
422 rm -f "$tmpfile" "${tmpfile}.old"
424 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
426 # set return code to be 0, since a key was found
435 # update the known_hosts file for a set of hosts listed on command
437 update_known_hosts() {
441 # default return code is 0, which assumes a key was found for
442 # every host. code will be set to 1 if a key is not found for at
446 # set the trap to remove any lockfiles on exit
447 trap "lockfile-remove $KNOWN_HOSTS" EXIT
449 # create a lockfile on known_hosts
450 lockfile-create "$KNOWN_HOSTS"
453 # process the host, change return code if host key not found
454 process_host_known_hosts "$host" || returnCode=1
456 # touch the lockfile, for good measure.
457 lockfile-touch --oneshot "$KNOWN_HOSTS"
460 # remove the lockfile
461 lockfile-remove "$KNOWN_HOSTS"
466 # process known_hosts file, going through line-by-line, extract each
467 # host, and process with the host processing function
468 process_known_hosts() {
471 # default return code is 0, which assumes a key was found for
472 # every host. code will be set to 1 if a key is not found for at
476 # take all the hosts from the known_hosts file (first field), grep
477 # out all the hashed hosts (lines starting with '|')...
478 for line in $(cat "$KNOWN_HOSTS" | meat | cut -d ' ' -f 1 | grep -v '^|.*$') ; do
479 # break up hosts into separate words
480 update_known_hosts $(echo "$line" | tr , ' ') || returnCode=1
486 # process uids for the authorized_keys file
487 process_uid_authorized_keys() {
493 # default return code is 1, which assumes no key was found
498 log "processing user ID: $userID"
500 for line in $(process_user_id "$userID") ; do
501 ok=$(echo "$line" | cut -d: -f1)
502 keyid=$(echo "$line" | cut -d: -f2)
504 sshKey=$(gpg2ssh "$keyid")
505 # remove the old host key line
506 remove_line "$AUTHORIZED_KEYS" "$sshKey"
507 # if key OK, add new host line
508 if [ "$ok" -eq '0' ] ; then
509 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
511 # set return code to be 0, since a key was found
519 # update the authorized_keys files from a list of user IDs on command
521 update_authorized_keys() {
525 # default return code is 0, which assumes a key was found for
526 # every user ID. code will be set to 1 if a key is not found for
527 # at least one user ID
530 # set the trap to remove any lockfiles on exit
531 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
533 # create a lockfile on authorized_keys
534 lockfile-create "$AUTHORIZED_KEYS"
537 # process the user ID, change return code if key not found for
539 process_uid_authorized_keys "$userID" || returnCode=1
541 # touch the lockfile, for good measure.
542 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
545 # remove the lockfile
546 lockfile-remove "$AUTHORIZED_KEYS"
551 # process an authorized_user_ids file for authorized_keys
552 process_authorized_user_ids() {
556 # default return code is 0, and is set to 1 if a key for a user ID
560 authorizedUserIDs="$1"
562 # set the IFS to be newline for parsing the authorized_user_ids
563 # file. can't find it in BASH(1) (found it on the net), but it
566 for userid in $(cat "$authorizedUserIDs" | meat) ; do
567 update_authorized_keys "$userid" || returnCode=1
573 # EXPERIMENTAL (unused) process userids found in authorized_keys file
574 # go through line-by-line, extract monkeysphere userids from comment
575 # fields, and process each userid
577 process_authorized_keys() {
582 # default return code is 0, and is set to 1 if a key for a user
588 # take all the monkeysphere userids from the authorized_keys file
589 # comment field (third field) that starts with "MonkeySphere uid:"
590 # FIXME: needs to handle authorized_keys options (field 0)
591 cat "$authorizedKeys" | meat | \
592 while read -r options keytype key comment ; do
593 # if the comment field is empty, assume the third field was
595 if [ -z "$comment" ] ; then
599 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
602 userID=$(echo "$comment" | awk "{ print $2 }")
603 if [ -z "$userID" ] ; then
608 log "processing userid: '$userID'"
609 process_user_id "$userID" > /dev/null || returnCode=1
615 ##################################################
616 ### GPG HELPER FUNCTIONS
618 # retrieve key from web of trust, and set owner trust to "full"
627 if [ -z "$keyID" ] ; then
628 failure "You must specify key to trust."
631 # get the key from the key server
632 if ! gpg --keyserver "$KEYSERVER" --recv-key "$keyID" ; then
633 failure "Could not retrieve key '$keyID'."
636 # get key fingerprint
637 fingerprint=$(get_key_fingerprint "$keyID")
640 gpg --fingerprint "$fingerprint"
642 while [ -z "$trustLevel" ] ; do
644 Please decide how far you trust this user to correctly verify other users' keys
645 (by looking at passports, checking fingerprints from different sources, etc.)
647 1 = I don't know or won't say
649 3 = I trust marginally
651 5 = I trust ultimately
654 read -p "Your decision? " trustLevel
655 if echo "$trustLevel" | grep -v "[1-5]" ; then
656 echo "Unknown trust level '$trustLevel'."
658 elif [ "$trustLevel" = 'q' ] ; then
663 # attach a "non-exportable" signature to the key
664 # this is required for the key to have any validity at all
665 # the 'y's on stdin indicates "yes, i really want to sign"
666 echo -e 'y\ny' | gpg --quiet --lsign-key --command-fd 0 "$fingerprint"
668 # index trustLevel by one to difference between level in ui and level
670 trustLevel=$((trustLevel+1))
672 # import new owner trust level for key
673 echo "${fingerprint}:${trustLevel}:" | gpg --import-ownertrust
675 log "Owner trust updated."
677 failure "There was a problem changing owner trust."
681 # publish server key to keyserver
682 publish_server_key() {
683 read -p "really publish key to $KEYSERVER? [y|N]: " OK; OK=${OK:=N}
684 if [ ${OK/y/Y} != 'Y' ] ; then
689 # FIXME: need to figure out better way to identify host key
690 # dummy command so as not to publish fakes keys during testing
692 #gpg --keyserver "$KEYSERVER" --send-keys $(hostname -f)
693 failure "NOT PUBLISHED (to avoid permanent publication errors during monkeysphere development).
694 To publish manually, do: gpg --keyserver $KEYSERVER --send-keys $(hostname -f)"