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 ssh-style path variables
107 path=${path/\%u/"$uname"}
108 path=${path/\%h/"$userHome"}
113 ### CONVERTION UTILITIES
115 # output the ssh key for a given key ID
120 # only use last 16 characters until openpgp2ssh can take all 40 #TMP
121 keyID=$(echo "$1" | cut -c 25-) #TMP
123 gpg --export "$keyID" | openpgp2ssh "$keyID" 2> /dev/null
126 # output known_hosts line from ssh key
135 echo -n "$key" | tr -d '\n'
136 echo " MonkeySphere${DATE}"
139 # output authorized_keys line from ssh key
140 ssh2authorized_keys() {
147 echo -n "$key" | tr -d '\n'
148 echo " MonkeySphere${DATE} ${userID}"
151 # convert key from gpg to ssh known_hosts format
159 # NOTE: it seems that ssh-keygen -R removes all comment fields from
160 # all lines in the known_hosts file. why?
161 # NOTE: just in case, the COMMENT can be matched with the
163 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
165 gpg2ssh "$keyID" | tr -d '\n'
166 echo " MonkeySphere${DATE}"
169 # convert key from gpg to ssh authorized_keys format
170 gpg2authorized_keys() {
177 # NOTE: just in case, the COMMENT can be matched with the
179 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
180 gpg2ssh "$keyID" | tr -d '\n'
181 echo " MonkeySphere${DATE} ${userID}"
186 # retrieve all keys with given user id from keyserver
187 # FIXME: need to figure out how to retrieve all matching keys
188 # (not just first N (5 in this case))
194 log -n " checking keyserver $KEYSERVER... "
196 gpg --quiet --batch --with-colons \
197 --command-fd 0 --keyserver "$KEYSERVER" \
198 --search ="$userID" > /dev/null 2>&1
202 # get the full fingerprint of a key ID
203 get_key_fingerprint() {
208 gpg --list-key --with-colons --fixed-list-mode \
209 --with-fingerprint "$keyID" | grep "$keyID" | \
210 grep '^fpr:' | cut -d: -f10
213 ########################################################################
214 ### PROCESSING FUNCTIONS
216 # userid and key policy checking
217 # the following checks policy on the returned keys
218 # - checks that full key has appropriate valididy (u|f)
219 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
220 # - checks that requested user ID has appropriate validity
221 # (see /usr/share/doc/gnupg/DETAILS.gz)
222 # output is one line for every found key, in the following format:
226 # "flag" is an acceptability flag, 0 = ok, 1 = bad
227 # "fingerprint" is the fingerprint of the key
229 # expects global variable: "MODE"
232 local requiredCapability
233 local requiredPubCapability
248 # set the required key capability based on the mode
249 if [ "$MODE" = 'known_hosts' ] ; then
250 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
251 elif [ "$MODE" = 'authorized_keys' ] ; then
252 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
254 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
256 # if CHECK_KEYSERVER variable set, check the keyserver
258 if [ "$CHECK_KEYSERVER" = "true" ] ; then
259 gpg_fetch_userid "$userID"
262 # output gpg info for (exact) userid and store
263 gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
264 --with-fingerprint --with-fingerprint \
265 ="$userID" 2>/dev/null)
267 # if the gpg query return code is not 0, return 1
268 if [ "$?" -ne 0 ] ; then
269 log " - key not found."
273 # loop over all lines in the gpg output and process.
274 # need to do it this way (as opposed to "while read...") so that
275 # variables set in loop will be visible outside of loop
276 echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
277 while IFS=: read -r type validity keyid uidfpr usage ; do
278 # process based on record type
280 'pub') # primary keys
281 # new key, wipe the slate
288 log " primary key found: $keyid"
290 # if overall key is not valid, skip
291 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
292 log " - unacceptable primary key validity ($validity)."
295 # if overall key is disabled, skip
296 if check_capability "$usage" 'D' ; then
297 log " - key disabled."
300 # if overall key capability is not ok, skip
301 if ! check_capability "$usage" $requiredPubCapability ; then
302 log " - unacceptable primary key capability ($usage)."
306 # mark overall key as ok
309 # mark primary key as ok if capability is ok
310 if check_capability "$usage" $requiredCapability ; then
315 # if an acceptable user ID was already found, skip
316 if [ "$uidOK" ] ; then
319 # if the user ID does not match, skip
320 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
323 # if the user ID validity is not ok, skip
324 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
328 # mark user ID acceptable
331 # output a line for the primary key
333 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
334 log " * acceptable key found."
335 echo 0 "$fingerprint"
337 echo 1 "$fingerprint"
341 # unset acceptability of last key
346 # if sub key validity is not ok, skip
347 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
350 # if sub key capability is not ok, skip
351 if ! check_capability "$usage" $requiredCapability ; then
358 'fpr') # key fingerprint
359 fingerprint="$uidfpr"
361 # if the last key was the pub key, skip
362 if [ "$lastKey" = pub ] ; then
366 # output a line for the last subkey
368 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
369 log " * acceptable key found."
370 echo 0 "$fingerprint"
372 echo 1 "$fingerprint"
379 # process a host in known_host file
380 process_host_known_hosts() {
388 userID="ssh://${host}"
390 log "processing host: $host"
392 process_user_id "ssh://${host}" | \
393 while read -r ok keyid ; do
394 sshKey=$(gpg2ssh "$keyid")
395 # remove the old host key line
396 remove_line "$KNOWN_HOSTS" "$sshKey"
397 # if key OK, add new host line
398 if [ "$ok" -eq '0' ] ; then
400 if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
401 # FIXME: this is really hackish cause ssh-keygen won't
402 # hash from stdin to stdout
404 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
405 ssh-keygen -H -f "$tmpfile" 2> /dev/null
406 cat "$tmpfile" >> "$KNOWN_HOSTS"
407 rm -f "$tmpfile" "${tmpfile}.old"
409 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
415 # process a uid in an authorized_keys file
416 process_uid_authorized_keys() {
423 log "processing user ID: $userID"
425 process_user_id "$userID" | \
426 while read -r ok keyid ; do
427 sshKey=$(gpg2ssh "$keyid")
428 # remove the old host key line
429 remove_line "$AUTHORIZED_KEYS" "$sshKey"
430 # if key OK, add new host line
431 if [ "$ok" -eq '0' ] ; then
432 ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
437 # process known_hosts file
438 # go through line-by-line, extract each host, and process with the
439 # host processing function
440 process_known_hosts() {
444 # take all the hosts from the known_hosts file (first field),
445 # grep out all the hashed hosts (lines starting with '|')...
446 cat "$KNOWN_HOSTS" | meat | \
447 cut -d ' ' -f 1 | grep -v '^|.*$' | \
448 while IFS=, read -r -a hosts ; do
449 # and process each host
450 for host in ${hosts[*]} ; do
451 process_host_known_hosts "$host"
456 # process an authorized_user_ids file for authorized_keys
457 process_authorized_user_ids() {
460 authorizedUserIDs="$1"
462 cat "$authorizedUserIDs" | meat | \
463 while read -r userid ; do
464 process_uid_authorized_keys "$userid"
468 # EXPERIMENTAL (unused) process userids found in authorized_keys file
469 # go through line-by-line, extract monkeysphere userids from comment
470 # fields, and process each userid
472 process_authorized_keys() {
478 # take all the monkeysphere userids from the authorized_keys file
479 # comment field (third field) that starts with "MonkeySphere uid:"
480 # FIXME: needs to handle authorized_keys options (field 0)
481 cat "$authorizedKeys" | meat | \
482 while read -r options keytype key comment ; do
483 # if the comment field is empty, assume the third field was
485 if [ -z "$comment" ] ; then
489 if echo "$comment" | egrep -v -q '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}' ; then
492 userID=$(echo "$comment" | awk "{ print $2 }")
493 if [ -z "$userID" ] ; then
498 log "processing userid: '$userID'"
499 process_user_id "$userID" > /dev/null
503 ##################################################
504 ### GPG HELPER FUNCTIONS
506 # retrieve key from web of trust, and set owner trust to "full"
509 # get the key from the key server
510 if ! gpg --keyserver "$KEYSERVER" --recv-key "$keyID" ; then
511 log "could not retrieve key '$keyID'"
515 # get key fingerprint
516 fingerprint=$(get_key_fingerprint "$keyID")
518 # attach a "non-exportable" signature to the key
519 # this is required for the key to have any validity at all
520 # the 'y's on stdin indicates "yes, i really want to sign"
521 echo -e 'y\ny' | gpg --lsign-key --command-fd 0 "$fingerprint"
523 # import "full" trust for fingerprint into gpg
524 echo ${fingerprint}:5: | gpg --import-ownertrust
526 log "owner trust updated."
528 failure "there was a problem changing owner trust."
532 # publish server key to keyserver
533 publish_server_key() {
534 read -p "really publish key to $KEYSERVER? [y|N]: " OK; OK=${OK:=N}
535 if [ ${OK/y/Y} != 'Y' ] ; then
540 # FIXME: need to figure out better way to identify host key
541 # dummy command so as not to publish fakes keys during testing
543 #gpg --keyserver "$KEYSERVER" --send-keys $(hostname -f)
544 echo "NOT PUBLISHED (to avoid permanent publication errors during monkeysphere development).
545 To publish manually, do: gpg --keyserver $KEYSERVER --send-keys $(hostname -f)"