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 ########################################################################
15 ETC="/etc/monkeysphere"
17 CACHE="/var/cache/monkeysphere"
19 ########################################################################
26 # write output to stderr
32 # cut out all comments(#) and blank lines from standard input
34 grep -v -e "^[[:space:]]*#" -e '^$'
37 # cut a specified line from standard input
39 head --line="$1" | tail -1
42 # retrieve all keys with given user id from keyserver
43 # FIXME: need to figure out how to retrieve all matching keys
50 # if CHECK_KEYSERVER variable set, check the keyserver
52 if [ "CHECK_KEYSERVER" ] ; then
54 gpg --quiet --batch --command-fd 0 --with-colons \
55 --keyserver "$KEYSERVER" \
56 --search ="$userID" >/dev/null 2>&1
58 # otherwise just return true
64 # check that characters are in a string (in an AND fashion).
65 # used for checking key capability
66 # check_capability capability a [b...]
75 if echo "$capability" | grep -q -v "$capcheck" ; then
82 # get the full fingerprint of a key ID
83 get_key_fingerprint() {
88 gpg --list-key --with-colons --fixed-list-mode \
89 --with-fingerprint "$keyID" | grep "$keyID" | \
90 grep '^fpr:' | cut -d: -f10
94 # convert escaped characters from gpg output back into original
96 # FIXME: undo all escape character translation in with-colons gpg output
98 echo "$1" | sed 's/\\x3a/:/'
101 # convert key from gpg to ssh known_hosts format
107 host=$(echo "$2" | sed -e "s|ssh://||")
109 # NOTE: it seems that ssh-keygen -R removes all comment fields from
110 # all lines in the known_hosts file. why?
111 # NOTE: just in case, the COMMENT can be matched with the
113 # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
115 gpg --export "$keyID" | \
116 openpgp2ssh "$keyID" | tr -d '\n'
117 echo " MonkeySphere${DATE}"
120 # convert key from gpg to ssh authorized_keys format
121 gpg2authorized_keys() {
128 gpg --export "$keyID" | \
129 openpgp2ssh "$keyID" | tr -d '\n'
130 echo " MonkeySphere${DATE}: ${userID}"
133 # userid and key policy checking
134 # the following checks policy on the returned keys
135 # - checks that full key has appropriate valididy (u|f)
136 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
137 # - checks that particular desired user id has appropriate validity
138 # see /usr/share/doc/gnupg/DETAILS.gz
139 # expects global variable: "MODE"
143 local requiredCapability
144 local requiredPubCapability
162 # set the required key capability based on the mode
163 if [ "$MODE" = 'known_hosts' ] ; then
164 requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
165 elif [ "$MODE" = 'authorized_keys' ] ; then
166 requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"
168 requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
170 # fetch keys from keyserver, return 1 if none found
171 gpg_fetch_userid "$userID" || return 1
173 # output gpg info for (exact) userid and store
174 gpgOut=$(gpg --fixed-list-mode --list-key --with-colons \
175 ="$userID" 2> /dev/null)
177 # return 1 if there only "tru" lines are output from gpg
178 if [ -z "$(echo "$gpgOut" | grep -v '^tru:')" ] ; then
179 log " key not found."
183 # loop over all lines in the gpg output and process.
184 # need to do it this way (as opposed to "while read...") so that
185 # variables set in loop will be visible outside of loop
186 for line in $(seq 1 $(echo "$gpgOut" | wc -l)) ; do
188 # read the contents of the line
189 type=$(echo "$gpgOut" | cutline "$line" | cut -d: -f1)
190 validity=$(echo "$gpgOut" | cutline "$line" | cut -d: -f2)
191 keyid=$(echo "$gpgOut" | cutline "$line" | cut -d: -f5)
192 uidfpr=$(echo "$gpgOut" | cutline "$line" | cut -d: -f10)
193 capability=$(echo "$gpgOut" | cutline "$line" | cut -d: -f12)
195 # process based on record type
197 'pub') # primary keys
198 # new key, wipe the slate
206 # check primary key validity
207 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
208 log " unacceptable primary key validity ($validity)."
211 # check capability is not Disabled...
212 if check_capability "$capability" 'D' ; then
216 # check overall key capability
217 # must be Encryption and Authentication
218 if ! check_capability "$capability" $requiredPubCapability ; then
219 log " unacceptable primary key capability ($capability)."
223 # mark if primary key is acceptable
226 # add primary key ID to key list if it has required capability
227 if check_capability "$capability" $requiredCapability ; then
228 keyIDs[${#keyIDs[*]}]="$keyid"
232 # check key ok and we have key fingerprint
233 if [ -z "$keyOK" ] ; then
237 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
240 # check the uid matches
241 if [ "$(unescape "$uidfpr")" != "$userID" ] ; then
245 # mark if uid acceptable
249 # add sub key ID to key list if it has required capability
250 if check_capability "$capability" $requiredCapability ; then
251 keyIDs[${#keyIDs[*]}]="$keyid"
257 # hash userid for cache file name
258 userIDHash=$(echo "$userID" | sha1sum | awk '{ print $1 }')
260 # make sure the cache directory exists
263 # touch/clear key cache file
264 # (will be left empty if there are noacceptable keys)
265 > "$cacheDir"/"$userIDHash"."$pubKeyID"
267 # for each acceptable key, write an ssh key line to the
269 if [ "$keyOK" -a "$uidOK" -a "${keyIDs[*]}" ] ; then
270 for keyID in ${keyIDs[@]} ; do
271 log " acceptable key/uid found."
273 if [ "$MODE" = 'known_hosts' ] ; then
275 gpg2known_hosts "$keyID" "$userID" >> \
276 "$cacheDir"/"$userIDHash"."$pubKeyID"
277 # hash the cache file if specified
278 if [ "$HASH_KNOWN_HOSTS" = "true" ] ; then
279 ssh-keygen -H -f "$cacheDir"/"$userIDHash"."$pubKeyID" > /dev/null 2>&1
280 rm "$cacheDir"/"$userIDHash"."$pubKeyID".old
282 elif [ "$MODE" = 'authorized_keys' ] ; then
284 # FIXME: needs to apply extra options for authorized_keys
286 gpg2authorized_keys "$keyID" "$userID" >> \
287 "$cacheDir"/"$userIDHash"."$pubKeyID"
292 # echo the path to the key cache file
293 echo "$cacheDir"/"$userIDHash"."$pubKeyID"
296 # update the cache for userid, and prompt to add file to
297 # authorized_user_ids file if the userid is found in gpg
298 # and not already in file.
307 log "processing userid: '$userID'"
309 # return 1 if there is no output of the user ID processing
310 # ie. no key was found
311 keyCachePath=$(process_user_id "$userID" "$cacheDir")
312 if [ -z "$keyCachePath" ] ; then
316 # check if user ID is in the authorized_user_ids file
317 if ! grep -q "^${userID}\$" "$AUTHORIZED_USER_IDS" ; then
318 read -p "user ID not currently authorized. authorize? [Y|n]: " OK; OK=${OK:=Y}
319 if [ ${OK/y/Y} = 'Y' ] ; then
321 log -n "adding user ID to authorized_user_ids file... "
322 echo "$userID" >> "$AUTHORIZED_USER_IDS"
326 log "authorized_user_ids file untouched."
331 # remove a userid from the authorized_user_ids file
337 log "processing userid: '$userID'"
339 if ! grep -q "^${userID}\$" "$AUTHORIZED_USER_IDS" ; then
340 log "user ID not currently authorized."
344 log -n "removing user ID '$userID'... "
345 grep -v "$userID" "$AUTHORIZED_USER_IDS" | sponge "$AUTHORIZED_USER_IDS"
349 # process a host for addition to a known_host file
358 log "processing host: $host"
360 keyCachePath=$(process_user_id "ssh://${host}" "$cacheDir")
362 ssh-keygen -R "$host" -f "$USER_KNOWN_HOSTS"
363 cat "$keyCachePath" >> "$USER_KNOWN_HOSTS"
367 # process known_hosts file
368 # go through line-by-line, extract each host, and process with the
369 # host processing function
370 process_known_hosts() {
377 # take all the hosts from the known_hosts file (first field),
378 # grep out all the hashed hosts (lines starting with '|')...
379 meat "$USER_KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | \
380 while IFS=, read -r -a hosts ; do
381 # ...and process each host
382 for host in ${hosts[*]} ; do
383 process_host "$host" "$cacheDir"
388 # update an authorized_keys file after first processing the
389 # authorized_user_ids file
390 update_authorized_keys() {
391 local msAuthorizedKeys
392 local userAuthorizedKeys
395 msAuthorizedKeys="$1"
396 userAuthorizedKeys="$2"
399 process_authorized_ids "$AUTHORIZED_USER_IDS" "$cacheDir"
401 # write output key file
402 log "writing monkeysphere authorized_keys file... "
403 touch "$msAuthorizedKeys"
404 if [ "$(ls "$cacheDir")" ] ; then
405 log -n "adding gpg keys... "
406 cat "$cacheDir"/* > "$msAuthorizedKeys"
409 log "no gpg keys to add."
411 if [ "$userAuthorizedKeys" != "-" -a -s "$userAuthorizedKeys" ] ; then
412 log -n "adding user authorized_keys file... "
413 cat "$userAuthorizedKeys" >> "$msAuthorizedKeys"
416 log "monkeysphere authorized_keys file generated:"
417 log "$msAuthorizedKeys"
420 # process an authorized_*_ids file
421 # go through line-by-line, extract each userid, and process
422 process_authorized_ids() {
430 # clean out keys file and remake keys directory
434 # loop through all user ids in file
435 # FIXME: needs to handle authorized_keys options
436 cat "$authorizedIDs" | meat | \
437 while read -r userID ; do
439 log "processing userid: '$userID'"
440 process_user_id "$userID" "$cacheDir" > /dev/null
444 # EXPERIMENTAL (unused) process userids found in authorized_keys file
445 # go through line-by-line, extract monkeysphere userids from comment
446 # fields, and process each userid
447 process_authorized_keys() {
455 # take all the monkeysphere userids from the authorized_keys file
456 # comment field (third field) that starts with "MonkeySphere uid:"
457 # FIXME: needs to handle authorized_keys options (field 0)
458 cat "$authorizedKeys" | \
459 while read -r options keytype key comment ; do
460 # if the comment field is empty, assume the third field was
462 if [ -z "$comment" ] ; then
465 if ! echo "$comment" | grep '^MonkeySphere userID:.*$' ; then
468 userID=$(echo "$comment" | sed -e "/^MonkeySphere userID://")
469 if [ -z "$userID" ] ; then
473 log "processing userid: '$userID'"
474 process_user_id "$userID" "$cacheDir" > /dev/null
478 # retrieve key from web of trust, and set owner trust to "full"
481 # get the key from the key server
482 if ! gpg --keyserver "$KEYSERVER" --recv-key "$keyID" ; then
483 log "could not retrieve key '$keyID'"
487 # get key fingerprint
488 fingerprint=$(get_key_fingerprint "$keyID")
490 # attach a "non-exportable" signature to the key
491 # this is required for the key to have any validity at all
492 # the 'y's on stdin indicates "yes, i really want to sign"
493 echo -e 'y\ny' | gpg --lsign-key --command-fd 0 "$fingerprint"
495 # import "full" trust for fingerprint into gpg
496 echo ${fingerprint}:5: | gpg --import-ownertrust
498 log "owner trust updated."
500 failure "there was a problem changing owner trust."
504 # publish server key to keyserver
505 publish_server_key() {
506 read -p "really publish key to $KEYSERVER? [y|N]: " OK; OK=${OK:=N}
507 if [ ${OK/y/Y} != 'Y' ] ; then
512 # FIXME: need to figure out better way to identify host key
513 # dummy command so as not to publish fakes keys during testing
515 #gpg --send-keys --keyserver "$KEYSERVER" $(hostname -f)
516 echo "NOT PUBLISHED: gpg --send-keys --keyserver $KEYSERVER $(hostname -f)"