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 '^$'
48 # cut a specified line from standard input
50 head --line="$1" | 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 [ "$file" -a "$string" ] ; then
87 grep -v "$string" "$file" | sponge "$file"
91 # translate ssh-style path variables %h and %u
92 translate_ssh_variables() {
99 # get the user's home directory
100 userHome=$(getent passwd "$uname" | cut -d: -f6)
102 # translate '%u' to user name
103 path=${path/\%u/"$uname"}
104 # translate '%h' to user home directory
105 path=${path/\%h/"$userHome"}
110 ### CONVERSION UTILITIES
112 # output the ssh key for a given key ID
118 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
121 # output the ssh key for a given secret key ID
126 # only use last 16 characters until openpgp2ssh can take all 40 #TMP
127 keyID=$(echo "$1" | cut -c 25-) #TMP
129 gpg --export-secret-key "$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))
200 log -n " checking keyserver $KEYSERVER... "
202 gpg --quiet --batch --with-colons \
203 --command-fd 0 --keyserver "$KEYSERVER" \
204 --search ="$userID" > /dev/null 2>&1
208 # get the full fingerprint of a key ID
209 get_key_fingerprint() {
214 gpg --list-key --with-colons --fixed-list-mode \
215 --with-fingerprint --with-fingerprint "$keyID" | \
216 grep '^fpr:' | grep "$keyID" | cut -d: -f10
219 ########################################################################
220 ### PROCESSING FUNCTIONS
222 # userid and key policy checking
223 # the following checks policy on the returned keys
224 # - checks that full key has appropriate valididy (u|f)
225 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
226 # - checks that requested user ID has appropriate validity
227 # (see /usr/share/doc/gnupg/DETAILS.gz)
228 # output is one line for every found key, in the following format:
232 # "flag" is an acceptability flag, 0 = ok, 1 = bad
233 # "fingerprint" is the fingerprint of the key
235 # expects global variable: "MODE"
238 local requiredCapability
239 local requiredPubCapability
254 # set the required key capability based on the mode
255 if [ "$MODE" = 'known_hosts' ] ; then
256 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
257 elif [ "$MODE" = 'authorized_keys' ] ; then
258 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
260 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
262 # if CHECK_KEYSERVER variable set to true, check the keyserver
264 if [ "$CHECK_KEYSERVER" = "true" ] ; then
265 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() {
394 # default return code is 1, which assumes no key was found
399 log "processing host: $host"
401 userID="ssh://${host}"
403 for line in $(process_user_id "ssh://${host}") ; do
404 ok=$(echo "$line" | cut -d: -f1)
405 keyid=$(echo "$line" | cut -d: -f2)
407 sshKey=$(gpg2ssh "$keyid")
408 # remove the old host key line
409 remove_line "$KNOWN_HOSTS" "$sshKey"
410 # if key OK, add new host line
411 if [ "$ok" -eq '0' ] ; then
413 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
414 # FIXME: this is really hackish cause ssh-keygen won't
415 # hash from stdin to stdout
417 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
418 ssh-keygen -H -f "$tmpfile" 2> /dev/null
419 cat "$tmpfile" >> "$KNOWN_HOSTS"
420 rm -f "$tmpfile" "${tmpfile}.old"
422 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
424 # set return code to be 0, since a key was found
433 # update the known_hosts file for a set of hosts listed on command
435 update_known_hosts() {
439 # default return code is 0, which assumes a key was found for
440 # every host. code will be set to 1 if a key is not found for at
444 # set the trap to remove any lockfiles on exit
445 trap "lockfile-remove $KNOWN_HOSTS" EXIT
447 # create a lockfile on known_hosts
448 lockfile-create "$KNOWN_HOSTS"
451 # process the host, change return code if host key not found
452 process_host_known_hosts "$host" || returnCode=1
454 # touch the lockfile, for good measure.
455 lockfile-touch --oneshot "$KNOWN_HOSTS"
458 # remove the lockfile
459 lockfile-remove "$KNOWN_HOSTS"
464 # process known_hosts file, going through line-by-line, extract each
465 # host, and process with the host processing function
466 process_known_hosts() {
469 # default return code is 0, which assumes a key was found for
470 # every host. code will be set to 1 if a key is not found for at
474 # take all the hosts from the known_hosts file (first field), grep
475 # out all the hashed hosts (lines starting with '|')...
476 for line in $(cat "$KNOWN_HOSTS" | meat | cut -d ' ' -f 1 | grep -v '^|.*$') ; do
477 # break up hosts into separate words
478 update_known_hosts $(echo "$line" | tr , ' ') || returnCode=1
484 # process uids for the authorized_keys file
485 process_uid_authorized_keys() {
491 # default return code is 1, which assumes no key was found
496 log "processing user ID: $userID"
498 for line in $(process_user_id "$userID") ; do
499 ok=$(echo "$line" | cut -d: -f1)
500 keyid=$(echo "$line" | cut -d: -f2)
502 sshKey=$(gpg2ssh "$keyid")
503 # remove the old host key line
504 remove_line "$AUTHORIZED_KEYS" "$sshKey"
505 # if key OK, add new host line
506 if [ "$ok" -eq '0' ] ; then
507 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
509 # set return code to be 0, since a key was found
517 # update the authorized_keys files from a list of user IDs on command
519 update_authorized_keys() {
523 # default return code is 0, which assumes a key was found for
524 # every user ID. code will be set to 1 if a key is not found for
525 # at least one user ID
528 # set the trap to remove any lockfiles on exit
529 trap "lockfile-remove $AUTHORIZED_KEYS" EXIT
531 # create a lockfile on authorized_keys
532 lockfile-create "$AUTHORIZED_KEYS"
535 # process the user ID, change return code if key not found for
537 process_uid_authorized_keys "$userID" || returnCode=1
539 # touch the lockfile, for good measure.
540 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
543 # remove the lockfile
544 lockfile-remove "$AUTHORIZED_KEYS"
549 # process an authorized_user_ids file for authorized_keys
550 process_authorized_user_ids() {
554 # default return code is 0, and is set to 1 if a key for a user ID
558 authorizedUserIDs="$1"
560 # set the IFS to be newline for parsing the authorized_user_ids
561 # file. can't find it in BASH(1) (found it on the net), but it
564 for userid in $(cat "$authorizedUserIDs" | meat) ; do
565 update_authorized_keys "$userid" || returnCode=1
571 # EXPERIMENTAL (unused) process userids found in authorized_keys file
572 # go through line-by-line, extract monkeysphere userids from comment
573 # fields, and process each userid
575 process_authorized_keys() {
580 # default return code is 0, and is set to 1 if a key for a user
586 # take all the monkeysphere userids from the authorized_keys file
587 # comment field (third field) that starts with "MonkeySphere uid:"
588 # FIXME: needs to handle authorized_keys options (field 0)
589 cat "$authorizedKeys" | meat | \
590 while read -r options keytype key comment ; do
591 # if the comment field is empty, assume the third field was
593 if [ -z "$comment" ] ; then
597 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
600 userID=$(echo "$comment" | awk "{ print $2 }")
601 if [ -z "$userID" ] ; then
606 log "processing userid: '$userID'"
607 process_user_id "$userID" > /dev/null || returnCode=1
613 ##################################################
614 ### GPG HELPER FUNCTIONS
616 # retrieve key from web of trust, and set owner trust to "full"
625 if [ -z "$keyID" ] ; then
626 failure "You must specify key to trust."
629 # get the key from the key server
630 if ! gpg --keyserver "$KEYSERVER" --recv-key "$keyID" ; then
631 failure "Could not retrieve key '$keyID'."
634 # get key fingerprint
635 fingerprint=$(get_key_fingerprint "$keyID")
638 gpg --fingerprint "$fingerprint"
640 while [ -z "$trustLevel" ] ; do
642 Please decide how far you trust this user to correctly verify other users' keys
643 (by looking at passports, checking fingerprints from different sources, etc.)
645 1 = I don't know or won't say
647 3 = I trust marginally
649 5 = I trust ultimately
652 read -p "Your decision? " trustLevel
653 if echo "$trustLevel" | grep -v "[1-5]" ; then
654 echo "Unknown trust level '$trustLevel'."
656 elif [ "$trustLevel" = 'q' ] ; then
661 # attach a "non-exportable" signature to the key
662 # this is required for the key to have any validity at all
663 # the 'y's on stdin indicates "yes, i really want to sign"
664 echo -e 'y\ny' | gpg --quiet --lsign-key --command-fd 0 "$fingerprint"
666 # index trustLevel by one to difference between level in ui and level
668 trustLevel=$((trustLevel+1))
670 # import new owner trust level for key
671 echo "${fingerprint}:${trustLevel}:" | gpg --import-ownertrust
673 log "Owner trust updated."
675 failure "There was a problem changing owner trust."
679 # publish server key to keyserver
680 publish_server_key() {
681 read -p "really publish key to $KEYSERVER? [y|N]: " OK; OK=${OK:=N}
682 if [ ${OK/y/Y} != 'Y' ] ; then
687 # FIXME: need to figure out better way to identify host key
688 # dummy command so as not to publish fakes keys during testing
690 #gpg --keyserver "$KEYSERVER" --send-keys $(hostname -f)
691 failure "NOT PUBLISHED (to avoid permanent publication errors during monkeysphere development).
692 To publish manually, do: gpg --keyserver $KEYSERVER --send-keys $(hostname -f)"