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"
24 ########################################################################
37 # write output to stderr
47 # cut out all comments(#) and blank lines from standard input
49 grep -v -e "^[[:space:]]*#" -e '^$'
52 # cut a specified line from standard input
54 head --line="$1" | tail -1
57 # check that characters are in a string (in an AND fashion).
58 # used for checking key capability
59 # check_capability capability a [b...]
68 if echo "$usage" | grep -q -v "$capcheck" ; then
75 # convert escaped characters from gpg output back into original
77 # FIXME: undo all escape character translation in with-colons gpg output
79 echo "$1" | sed 's/\\x3a/:/'
82 # remove all lines with specified string from specified file
90 if [ "$file" -a "$string" ] ; then
91 grep -v "$string" "$file" | sponge "$file"
95 # translate ssh-style path variables %h and %u
96 translate_ssh_variables() {
103 # get the user's home directory
104 userHome=$(getent passwd "$uname" | cut -d: -f6)
106 # translate '%u' to user name
107 path=${path/\%u/"$uname"}
108 # translate '%h' to user home directory
109 path=${path/\%h/"$userHome"}
114 ### CONVERTION UTILITIES
116 # output the ssh key for a given key ID
121 # only use last 16 characters until openpgp2ssh can take all 40 #TMP
122 keyID=$(echo "$1" | cut -c 25-) #TMP
124 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
127 # output known_hosts line from ssh key
136 echo -n "$key" | tr -d '\n'
137 echo " MonkeySphere${DATE}"
140 # output authorized_keys line from ssh key
141 ssh2authorized_keys() {
148 echo -n "$key" | tr -d '\n'
149 echo " MonkeySphere${DATE} ${userID}"
152 # convert key from gpg to ssh known_hosts format
160 # NOTE: it seems that ssh-keygen -R removes all comment fields from
161 # all lines in the known_hosts file. why?
162 # NOTE: just in case, the COMMENT can be matched with the
164 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
166 gpg2ssh "$keyID" | tr -d '\n'
167 echo " MonkeySphere${DATE}"
170 # convert key from gpg to ssh authorized_keys format
171 gpg2authorized_keys() {
178 # NOTE: just in case, the COMMENT can be matched with the
180 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
181 gpg2ssh "$keyID" | tr -d '\n'
182 echo " MonkeySphere${DATE} ${userID}"
187 # retrieve all keys with given user id from keyserver
188 # FIXME: need to figure out how to retrieve all matching keys
189 # (not just first N (5 in this case))
195 log -n " checking keyserver $KEYSERVER... "
197 gpg --quiet --batch --with-colons \
198 --command-fd 0 --keyserver "$KEYSERVER" \
199 --search ="$userID" > /dev/null 2>&1
203 # get the full fingerprint of a key ID
204 get_key_fingerprint() {
209 gpg --list-key --with-colons --fixed-list-mode \
210 --with-fingerprint "$keyID" | grep "$keyID" | \
211 grep '^fpr:' | cut -d: -f10
214 ########################################################################
215 ### PROCESSING FUNCTIONS
217 # userid and key policy checking
218 # the following checks policy on the returned keys
219 # - checks that full key has appropriate valididy (u|f)
220 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
221 # - checks that requested user ID has appropriate validity
222 # (see /usr/share/doc/gnupg/DETAILS.gz)
223 # output is one line for every found key, in the following format:
227 # "flag" is an acceptability flag, 0 = ok, 1 = bad
228 # "fingerprint" is the fingerprint of the key
230 # expects global variable: "MODE"
233 local requiredCapability
234 local requiredPubCapability
249 # set the required key capability based on the mode
250 if [ "$MODE" = 'known_hosts' ] ; then
251 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
252 elif [ "$MODE" = 'authorized_keys' ] ; then
253 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
255 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
257 # if CHECK_KEYSERVER variable set, check the keyserver
259 if [ "$CHECK_KEYSERVER" = "true" ] ; then
260 gpg_fetch_userid "$userID"
263 # output gpg info for (exact) userid and store
264 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
265 --with-fingerprint --with-fingerprint \
266 ="$userID" 2>/dev/null)
268 # if the gpg query return code is not 0, return 1
269 if [ "$?" -ne 0 ] ; then
270 log " - key not found."
274 # loop over all lines in the gpg output and process.
275 # need to do it this way (as opposed to "while read...") so that
276 # variables set in loop will be visible outside of loop
277 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
278 while IFS=: read -r type validity keyid uidfpr usage ; do
279 # process based on record type
281 'pub') # primary keys
282 # new key, wipe the slate
289 log " primary key found: $keyid"
291 # if overall key is not valid, skip
292 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
293 log " - unacceptable primary key validity ($validity)."
296 # if overall key is disabled, skip
297 if check_capability "$usage" 'D' ; then
298 log " - key disabled."
301 # if overall key capability is not ok, skip
302 if ! check_capability "$usage" $requiredPubCapability ; then
303 log " - unacceptable primary key capability ($usage)."
307 # mark overall key as ok
310 # mark primary key as ok if capability is ok
311 if check_capability "$usage" $requiredCapability ; then
316 # if an acceptable user ID was already found, skip
317 if [ "$uidOK" ] ; then
320 # if the user ID does not match, skip
321 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
324 # if the user ID validity is not ok, skip
325 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
329 # mark user ID acceptable
332 # output a line for the primary key
334 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
335 log " * acceptable key found."
336 echo 0 "$fingerprint"
338 echo 1 "$fingerprint"
342 # unset acceptability of last key
347 # if sub key validity is not ok, skip
348 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
351 # if sub key capability is not ok, skip
352 if ! check_capability "$usage" $requiredCapability ; then
359 'fpr') # key fingerprint
360 fingerprint="$uidfpr"
362 # if the last key was the pub key, skip
363 if [ "$lastKey" = pub ] ; then
367 # output a line for the last subkey
369 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
370 log " * acceptable key found."
371 echo 0 "$fingerprint"
373 echo 1 "$fingerprint"
380 # process hosts in the known_host file
381 process_hosts_known_hosts() {
388 # create a lockfile on known_hosts
389 lockfile-create "$KNOWN_HOSTS"
392 log "processing host: $host"
394 userID="ssh://${host}"
396 process_user_id "ssh://${host}" | \
397 while read -r ok keyid ; do
398 sshKey=$(gpg2ssh "$keyid")
399 # remove the old host key line
400 remove_line "$KNOWN_HOSTS" "$sshKey"
401 # if key OK, add new host line
402 if [ "$ok" -eq '0' ] ; then
404 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
405 # FIXME: this is really hackish cause ssh-keygen won't
406 # hash from stdin to stdout
408 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
409 ssh-keygen -H -f "$tmpfile" 2> /dev/null
410 cat "$tmpfile" >> "$KNOWN_HOSTS"
411 rm -f "$tmpfile" "${tmpfile}.old"
413 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
417 # touch the lockfile, for good measure.
418 lockfile-touch --oneshot "$KNOWN_HOSTS"
421 # remove the lockfile
422 lockfile-remove "$KNOWN_HOSTS"
425 # process uids for the authorized_keys file
426 process_uids_authorized_keys() {
431 # create a lockfile on authorized_keys
432 lockfile-create "$AUTHORIZED_KEYS"
435 log "processing user ID: $userID"
437 process_user_id "$userID" | \
438 while read -r ok keyid ; do
439 sshKey=$(gpg2ssh "$keyid")
440 # remove the old host key line
441 remove_line "$AUTHORIZED_KEYS" "$sshKey"
442 # if key OK, add new host line
443 if [ "$ok" -eq '0' ] ; then
444 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
447 # touch the lockfile, for good measure.
448 lockfile-touch --oneshot "$AUTHORIZED_KEYS"
451 # remove the lockfile
452 lockfile-remove "$AUTHORIZED_KEYS"
455 # process known_hosts file
456 # go through line-by-line, extract each host, and process with the
457 # host processing function
458 process_known_hosts() {
462 # take all the hosts from the known_hosts file (first field),
463 # grep out all the hashed hosts (lines starting with '|')...
464 cat "$KNOWN_HOSTS" | meat | \
465 cut -d ' ' -f 1 | grep -v '^|.*$' | \
466 while IFS=, read -r -a hosts ; do
467 process_hosts_known_hosts ${hosts[@]}
471 # process an authorized_user_ids file for authorized_keys
472 process_authorized_user_ids() {
475 authorizedUserIDs="$1"
477 cat "$authorizedUserIDs" | meat | \
478 while read -r userid ; do
479 process_uids_authorized_keys "$userid"
483 # EXPERIMENTAL (unused) process userids found in authorized_keys file
484 # go through line-by-line, extract monkeysphere userids from comment
485 # fields, and process each userid
487 process_authorized_keys() {
493 # take all the monkeysphere userids from the authorized_keys file
494 # comment field (third field) that starts with "MonkeySphere uid:"
495 # FIXME: needs to handle authorized_keys options (field 0)
496 cat "$authorizedKeys" | meat | \
497 while read -r options keytype key comment ; do
498 # if the comment field is empty, assume the third field was
500 if [ -z "$comment" ] ; then
504 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
507 userID=$(echo "$comment" | awk "{ print $2 }")
508 if [ -z "$userID" ] ; then
513 log "processing userid: '$userID'"
514 process_user_id "$userID" > /dev/null
518 ##################################################
519 ### GPG HELPER FUNCTIONS
521 # retrieve key from web of trust, and set owner trust to "full"
524 # get the key from the key server
525 if ! gpg --keyserver "$KEYSERVER" --recv-key "$keyID" ; then
526 log "could not retrieve key '$keyID'"
530 # get key fingerprint
531 fingerprint=$(get_key_fingerprint "$keyID")
533 # attach a "non-exportable" signature to the key
534 # this is required for the key to have any validity at all
535 # the 'y's on stdin indicates "yes, i really want to sign"
536 echo -e 'y\ny' | gpg --lsign-key --command-fd 0 "$fingerprint"
538 # import "full" trust for fingerprint into gpg
539 echo ${fingerprint}:5: | gpg --import-ownertrust
541 log "owner trust updated."
543 failure "there was a problem changing owner trust."
547 # publish server key to keyserver
548 publish_server_key() {
549 read -p "really publish key to $KEYSERVER? [y|N]: " OK; OK=${OK:=N}
550 if [ ${OK/y/Y} != 'Y' ] ; then
555 # FIXME: need to figure out better way to identify host key
556 # dummy command so as not to publish fakes keys during testing
558 #gpg --keyserver "$KEYSERVER" --send-keys $(hostname -f)
559 echo "NOT PUBLISHED (to avoid permanent publication errors during monkeysphere development).
560 To publish manually, do: gpg --keyserver $KEYSERVER --send-keys $(hostname -f)"