avoid noisy warning message when ssh-askpass not available
[monkeysphere.git] / src / share / common
1 # -*-shell-script-*-
2 # This should be sourced by bash (though we welcome changes to make it POSIX sh compliant)
3
4 # Shared sh functions for the monkeysphere
5 #
6 # Written by
7 # Jameson Rollins <jrollins@finestructure.net>
8 # Jamie McClelland <jm@mayfirst.org>
9 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
10 #
11 # Copyright 2008-2009, released under the GPL, version 3 or later
12
13 # all-caps variables are meant to be user supplied (ie. from config
14 # file) and are considered global
15
16 ########################################################################
17 ### UTILITY FUNCTIONS
18
19 # output version info
20 version() {
21     cat "${SYSSHAREDIR}/VERSION"
22 }
23
24 # failure function.  exits with code 255, unless specified otherwise.
25 failure() {
26     [ "$1" ] && echo "$1" >&2
27     exit ${2:-'255'}
28 }
29
30 # write output to stderr based on specified LOG_LEVEL the first
31 # parameter is the priority of the output, and everything else is what
32 # is echoed to stderr.  If there is nothing else, then output comes
33 # from stdin, and is not prefaced by log prefix.
34 log() {
35     local priority
36     local level
37     local output
38     local alllevels
39     local found=
40
41     # don't include SILENT in alllevels: it's handled separately
42     # list in decreasing verbosity (all caps).
43     # separate with $IFS explicitly, since we do some fancy footwork
44     # elsewhere.
45     alllevels="DEBUG${IFS}VERBOSE${IFS}INFO${IFS}ERROR"
46
47     # translate lowers to uppers in global log level
48     LOG_LEVEL=$(echo "$LOG_LEVEL" | tr "[:lower:]" "[:upper:]")
49
50     # just go ahead and return if the log level is silent
51     if [ "$LOG_LEVEL" = 'SILENT' ] ; then
52         return
53     fi
54
55     for level in $alllevels ; do 
56         if [ "$LOG_LEVEL" = "$level" ] ; then
57             found=true
58         fi
59     done
60     if [ -z "$found" ] ; then
61         # default to INFO:
62         LOG_LEVEL=INFO
63     fi
64
65     # get priority from first parameter, translating all lower to
66     # uppers
67     priority=$(echo "$1" | tr "[:lower:]" "[:upper:]")
68     shift
69
70     # scan over available levels
71     for level in $alllevels ; do
72         # output if the log level matches, set output to true
73         # this will output for all subsequent loops as well.
74         if [ "$LOG_LEVEL" = "$level" ] ; then
75             output=true
76         fi
77         if [ "$priority" = "$level" -a "$output" = 'true' ] ; then
78             if [ "$1" ] ; then
79                 echo "$@"
80             else
81                 cat
82             fi | sed 's/^/'"${LOG_PREFIX}"'/' >&2
83         fi
84     done
85 }
86
87 # run command as monkeysphere user
88 su_monkeysphere_user() {
89     # our main goal here is to run the given command as the the
90     # monkeysphere user, but without prompting for any sort of
91     # authentication.  If this is not possible, we should just fail.
92
93     # FIXME: our current implementation is overly restrictive, because
94     # there may be some su PAM configurations that would allow su
95     # "$MONKEYSPHERE_USER" -c "$@" to Just Work without prompting,
96     # allowing specific users to invoke commands which make use of
97     # this user.
98
99     # chpst (from runit) would be nice to use, but we don't want to
100     # introduce an extra dependency just for this.  This may be a
101     # candidate for re-factoring if we switch implementation languages.
102
103     case $(id -un) in
104         # if monkeysphere user, run the command under bash
105         "$MONKEYSPHERE_USER")
106             bash -c "$@"
107             ;;
108
109          # if root, su command as monkeysphere user
110         'root')
111             su "$MONKEYSPHERE_USER" -c "$@"
112             ;;
113
114         # otherwise, fail
115         *)
116             log error "non-privileged user."
117             ;;
118     esac
119 }
120
121 # cut out all comments(#) and blank lines from standard input
122 meat() {
123     grep -v -e "^[[:space:]]*#" -e '^$' "$1"
124 }
125
126 # cut a specified line from standard input
127 cutline() {
128     head --line="$1" "$2" | tail -1
129 }
130
131 # make a temporary directory
132 msmktempdir() {
133     mktemp -d ${TMPDIR:-/tmp}/monkeysphere.XXXXXXXXXX
134 }
135
136 # make a temporary file
137 msmktempfile() {
138     mktemp ${TMPDIR:-/tmp}/monkeysphere.XXXXXXXXXX
139 }
140
141 # this is a wrapper for doing lock functions.
142 #
143 # it lets us depend on either lockfile-progs (preferred) or procmail's
144 # lockfile, and should
145 lock() {
146     local use_lockfileprogs=true
147     local action="$1"
148     local file="$2"
149
150     if ! ( type lockfile-create &>/dev/null ) ; then
151         if ! ( type lockfile &>/dev/null ); then
152             failure "Neither lockfile-create nor lockfile are in the path!"
153         fi
154         use_lockfileprogs=
155     fi
156     
157     case "$action" in
158         create)
159             if [ -n "$use_lockfileprogs" ] ; then
160                 lockfile-create "$file" || failure "unable to lock '$file'"
161             else
162                 lockfile -r 20 "${file}.lock" || failure "unable to lock '$file'"
163             fi
164             log debug "lock created on '$file'."
165             ;;
166         touch)  
167             if [ -n "$use_lockfileprogs" ] ; then
168                 lockfile-touch --oneshot "$file"
169             else
170                 : Nothing to do here
171             fi
172             log debug "lock touched on '$file'."
173             ;;
174         remove)
175             if [ -n "$use_lockfileprogs" ] ; then
176                 lockfile-remove "$file"
177             else
178                 rm -f "${file}.lock"
179             fi
180             log debug "lock removed on '$file'."
181             ;;
182         *)
183             failure "bad argument for lock subfunction '$action'"
184     esac
185 }
186
187
188 # for portability, between gnu date and BSD date.
189 # arguments should be:  number longunits format
190
191 # e.g. advance_date 20 seconds +%F
192 advance_date() {
193     local gnutry
194     local number="$1"
195     local longunits="$2"
196     local format="$3"
197     local shortunits
198
199     # try things the GNU way first 
200     if date -d "$number $longunits" "$format" &>/dev/null; then
201         date -d "$number $longunits" "$format"
202     else
203         # otherwise, convert to (a limited version of) BSD date syntax:
204         case "$longunits" in
205             years)
206                 shortunits=y
207                 ;;
208             months)
209                 shortunits=m
210                 ;;
211             weeks)
212                 shortunits=w
213                 ;;
214             days)
215                 shortunits=d
216                 ;;
217             hours)
218                 shortunits=H
219                 ;;
220             minutes)
221                 shortunits=M
222                 ;;
223             seconds)
224                 shortunits=S
225                 ;;
226             *)
227                 # this is a longshot, and will likely fail; oh well.
228                 shortunits="$longunits"
229         esac
230         date "-v+${number}${shortunits}" "$format"
231     fi
232 }
233
234
235 # check that characters are in a string (in an AND fashion).
236 # used for checking key capability
237 # check_capability capability a [b...]
238 check_capability() {
239     local usage
240     local capcheck
241
242     usage="$1"
243     shift 1
244
245     for capcheck ; do
246         if echo "$usage" | grep -q -v "$capcheck" ; then
247             return 1
248         fi
249     done
250     return 0
251 }
252
253 # hash of a file
254 file_hash() {
255     if type md5sum &>/dev/null ; then
256         md5sum "$1"
257     elif type md5 &>/dev/null ; then
258         md5 "$1"
259     else
260         failure "Neither md5sum nor md5 are in the path!"
261     fi
262 }
263
264 # convert escaped characters in pipeline from gpg output back into
265 # original character
266 # FIXME: undo all escape character translation in with-colons gpg
267 # output
268 gpg_unescape() {
269     sed 's/\\x3a/:/g'
270 }
271
272 # convert nasty chars into gpg-friendly form in pipeline
273 # FIXME: escape everything, not just colons!
274 gpg_escape() {
275     sed 's/:/\\x3a/g'
276 }
277
278 # prompt for GPG-formatted expiration, and emit result on stdout
279 get_gpg_expiration() {
280     local keyExpire
281
282     keyExpire="$1"
283
284     if [ -z "$keyExpire" -a "$PROMPT" = 'true' ]; then
285         cat >&2 <<EOF
286 Please specify how long the key should be valid.
287          0 = key does not expire
288       <n>  = key expires in n days
289       <n>w = key expires in n weeks
290       <n>m = key expires in n months
291       <n>y = key expires in n years
292 EOF
293         while [ -z "$keyExpire" ] ; do
294             printf "Key is valid for? (0) " >&2
295             read keyExpire
296             if ! test_gpg_expire ${keyExpire:=0} ; then
297                 echo "invalid value" >&2
298                 unset keyExpire
299             fi
300         done
301     elif ! test_gpg_expire "$keyExpire" ; then
302         failure "invalid key expiration value '$keyExpire'."
303     fi
304         
305     echo "$keyExpire"
306 }
307
308 passphrase_prompt() {
309     local prompt="$1"
310     local fifo="$2"
311     local PASS
312
313     if [ "$DISPLAY" ] && type "${SSH_ASKPASS:-ssh-askpass}" >/dev/null 2>/dev/null; then
314         printf 'Launching "%s"\n' "${SSH_ASKPASS:-ssh-askpass}" | log info
315         printf '(with prompt "%s")\n' "$prompt" | log debug
316         "${SSH_ASKPASS:-ssh-askpass}" "$prompt" > "$fifo"
317     else
318         read -s -p "$prompt" PASS
319         # Uses the builtin echo, so should not put the passphrase into
320         # the process table.  I think. --dkg
321         echo "$PASS" > "$fifo"
322     fi
323 }
324
325 # remove all lines with specified string from specified file
326 remove_line() {
327     local file
328     local string
329     local tempfile
330
331     file="$1"
332     string="$2"
333
334     if [ -z "$file" -o -z "$string" ] ; then
335         return 1
336     fi
337
338     if [ ! -e "$file" ] ; then
339         return 1
340     fi
341
342     # if the string is in the file...
343     if grep -q -F "$string" "$file" 2>/dev/null ; then
344         tempfile=$(mktemp "${file}.XXXXXXX") || \
345             failure "Unable to make temp file '${file}.XXXXXXX'"
346         
347         # remove the line with the string, and return 0
348         grep -v -F "$string" "$file" >"$tempfile"
349         cat "$tempfile" > "$file"
350         rm "$tempfile"
351         return 0
352     # otherwise return 1
353     else
354         return 1
355     fi
356 }
357
358 # remove all lines with MonkeySphere strings in file
359 remove_monkeysphere_lines() {
360     local file
361     local tempfile
362
363     file="$1"
364
365     # return error if file does not exist
366     if [ ! -e "$file" ] ; then
367         return 1
368     fi
369
370     # just return ok if the file is empty, since there aren't any
371     # lines to remove
372     if [ ! -s "$file" ] ; then
373         return 0
374     fi
375
376     tempfile=$(mktemp "${file}.XXXXXXX") || \
377         failure "Could not make temporary file '${file}.XXXXXXX'."
378
379     egrep -v '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$' \
380         "$file" >"$tempfile"
381     cat "$tempfile" > "$file"
382     rm "$tempfile"
383 }
384
385 # translate ssh-style path variables %h and %u
386 translate_ssh_variables() {
387     local uname
388     local home
389
390     uname="$1"
391     path="$2"
392
393     # get the user's home directory
394     userHome=$(get_homedir "$uname")
395
396     # translate '%u' to user name
397     path=${path/\%u/"$uname"}
398     # translate '%h' to user home directory
399     path=${path/\%h/"$userHome"}
400
401     echo "$path"
402 }
403
404 # test that a string to conforms to GPG's expiration format
405 test_gpg_expire() {
406     echo "$1" | egrep -q "^[0-9]+[mwy]?$"
407 }
408
409 # check that a file is properly owned, and that all it's parent
410 # directories are not group/other writable
411 check_key_file_permissions() {
412     local uname
413     local path
414
415     uname="$1"
416     path="$2"
417
418     if [ "$STRICT_MODES" = 'false' ] ; then
419         log debug "skipping path permission check for '$path' because STRICT_MODES is false..."
420         return 0
421     fi
422     log debug "checking path permission '$path'..."
423     "${SYSSHAREDIR}/checkperms" "$uname" "$path"
424 }
425
426 # return a list of all users on the system
427 list_users() {
428     if type getent &>/dev/null ; then
429         # for linux and FreeBSD systems
430         getent passwd | cut -d: -f1
431     elif type dscl &>/dev/null ; then
432         # for Darwin systems
433         dscl localhost -list /Search/Users
434     else
435         failure "Neither getent or dscl is in the path!  Could not determine list of users."
436     fi
437 }
438
439 # return the path to the home directory of a user
440 get_homedir() {
441     local uname=${1:-`whoami`}
442     eval "echo ~${uname}"
443 }
444
445 # return the primary group of a user
446 get_primary_group() {
447     local uname=${1:-`whoami`}
448     groups "$uname" | sed 's/^..* : //' | awk '{ print $1 }'
449 }
450
451 ### CONVERSION UTILITIES
452
453 # output the ssh key for a given key ID
454 gpg2ssh() {
455     local keyID
456     
457     keyID="$1"
458
459     gpg --export "$keyID" | openpgp2ssh "$keyID" 2>/dev/null
460 }
461
462 # output known_hosts line from ssh key
463 ssh2known_hosts() {
464     local host
465     local port
466     local key
467
468     # FIXME this does not properly deal with IPv6 hosts using the
469     # standard port (because it's unclear whether their final
470     # colon-delimited address section is a port number or an address
471     # string)
472     host=${1%:*}
473     port=${1##*:}
474     key="$2"
475
476     # specify the host and port properly for new ssh known_hosts
477     # format
478     if [ "$port" != "$host" ] ; then
479         host="[${host}]:${port}"
480     fi
481     printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
482 }
483
484 # output authorized_keys line from ssh key
485 ssh2authorized_keys() {
486     local userID
487     local key
488     
489     userID="$1"
490     key="$2"
491
492     printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
493 }
494
495 # convert key from gpg to ssh known_hosts format
496 gpg2known_hosts() {
497     local host
498     local keyID
499     local key
500
501     host="$1"
502     keyID="$2"
503
504     key=$(gpg2ssh "$keyID")
505
506     # NOTE: it seems that ssh-keygen -R removes all comment fields from
507     # all lines in the known_hosts file.  why?
508     # NOTE: just in case, the COMMENT can be matched with the
509     # following regexp:
510     # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
511     printf "%s %s MonkeySphere%s\n" "$host" "$key" "$DATE"
512 }
513
514 # convert key from gpg to ssh authorized_keys format
515 gpg2authorized_keys() {
516     local userID
517     local keyID
518     local key
519
520     userID="$1"
521     keyID="$2"
522
523     key=$(gpg2ssh "$keyID")
524
525     # NOTE: just in case, the COMMENT can be matched with the
526     # following regexp:
527     # '^MonkeySphere[[:digit:]]{4}(-[[:digit:]]{2}){2}T[[:digit:]]{2}(:[[:digit:]]{2}){2}$'
528     printf "%s MonkeySphere%s %s\n" "$key" "$DATE" "$userID"
529 }
530
531 ### GPG UTILITIES
532
533 # retrieve all keys with given user id from keyserver
534 # FIXME: need to figure out how to retrieve all matching keys
535 # (not just first N (5 in this case))
536 gpg_fetch_userid() {
537     local returnCode=0
538     local userID
539
540     if [ "$CHECK_KEYSERVER" != 'true' ] ; then
541         return 0
542     fi
543
544     userID="$1"
545
546     log verbose " checking keyserver $KEYSERVER... "
547     echo 1,2,3,4,5 | \
548         gpg --quiet --batch --with-colons \
549         --command-fd 0 --keyserver "$KEYSERVER" \
550         --search ="$userID" &>/dev/null
551     returnCode="$?"
552
553     return "$returnCode"
554 }
555
556 ########################################################################
557 ### PROCESSING FUNCTIONS
558
559 # userid and key policy checking
560 # the following checks policy on the returned keys
561 # - checks that full key has appropriate valididy (u|f)
562 # - checks key has specified capability (REQUIRED_*_KEY_CAPABILITY)
563 # - checks that requested user ID has appropriate validity
564 # (see /usr/share/doc/gnupg/DETAILS.gz)
565 # output is one line for every found key, in the following format:
566 #
567 # flag:sshKey
568 #
569 # "flag" is an acceptability flag, 0 = ok, 1 = bad
570 # "sshKey" is the translated gpg key
571 #
572 # all log output must go to stderr, as stdout is used to pass the
573 # flag:sshKey to the calling function.
574 #
575 # expects global variable: "MODE"
576 process_user_id() {
577     local returnCode=0
578     local userID
579     local requiredCapability
580     local requiredPubCapability
581     local gpgOut
582     local type
583     local validity
584     local keyid
585     local uidfpr
586     local usage
587     local keyOK
588     local uidOK
589     local lastKey
590     local lastKeyOK
591     local fingerprint
592
593     userID="$1"
594
595     # set the required key capability based on the mode
596     if [ "$MODE" = 'known_hosts' ] ; then
597         requiredCapability="$REQUIRED_HOST_KEY_CAPABILITY"
598     elif [ "$MODE" = 'authorized_keys' ] ; then
599         requiredCapability="$REQUIRED_USER_KEY_CAPABILITY"      
600     fi
601     requiredPubCapability=$(echo "$requiredCapability" | tr "[:lower:]" "[:upper:]")
602
603     # fetch the user ID if necessary/requested
604     gpg_fetch_userid "$userID"
605
606     # output gpg info for (exact) userid and store
607     gpgOut=$(gpg --list-key --fixed-list-mode --with-colon \
608         --with-fingerprint --with-fingerprint \
609         ="$userID" 2>/dev/null) || returnCode="$?"
610
611     # if the gpg query return code is not 0, return 1
612     if [ "$returnCode" -ne 0 ] ; then
613         log verbose " no primary keys found."
614         return 1
615     fi
616
617     # loop over all lines in the gpg output and process.
618     echo "$gpgOut" | cut -d: -f1,2,5,10,12 | \
619     while IFS=: read -r type validity keyid uidfpr usage ; do
620         # process based on record type
621         case $type in
622             'pub') # primary keys
623                 # new key, wipe the slate
624                 keyOK=
625                 uidOK=
626                 lastKey=pub
627                 lastKeyOK=
628                 fingerprint=
629
630                 log verbose " primary key found: $keyid"
631
632                 # if overall key is not valid, skip
633                 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
634                     log debug "  - unacceptable primary key validity ($validity)."
635                     continue
636                 fi
637                 # if overall key is disabled, skip
638                 if check_capability "$usage" 'D' ; then
639                     log debug "  - key disabled."
640                     continue
641                 fi
642                 # if overall key capability is not ok, skip
643                 if ! check_capability "$usage" $requiredPubCapability ; then
644                     log debug "  - unacceptable primary key capability ($usage)."
645                     continue
646                 fi
647
648                 # mark overall key as ok
649                 keyOK=true
650
651                 # mark primary key as ok if capability is ok
652                 if check_capability "$usage" $requiredCapability ; then
653                     lastKeyOK=true
654                 fi
655                 ;;
656             'uid') # user ids
657                 if [ "$lastKey" != pub ] ; then
658                     log verbose " ! got a user ID after a sub key?!  user IDs should only follow primary keys!"
659                     continue
660                 fi
661                 # if an acceptable user ID was already found, skip
662                 if [ "$uidOK" = 'true' ] ; then
663                     continue
664                 fi
665                 # if the user ID does matches...
666                 if [ "$(echo "$uidfpr" | gpg_unescape)" = "$userID" ] ; then
667                     # and the user ID validity is ok
668                     if [ "$validity" = 'u' -o "$validity" = 'f' ] ; then
669                         # mark user ID acceptable
670                         uidOK=true
671                     else
672                         log debug "  - unacceptable user ID validity ($validity)."
673                     fi
674                 else
675                     continue
676                 fi
677
678                 # output a line for the primary key
679                 # 0 = ok, 1 = bad
680                 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
681                     log verbose "  * acceptable primary key."
682                     if [ -z "$sshKey" ] ; then
683                         log error "    ! primary key could not be translated (not RSA?)."
684                     else
685                         echo "0:${sshKey}"
686                     fi
687                 else
688                     log debug "  - unacceptable primary key."
689                     if [ -z "$sshKey" ] ; then
690                         log debug "    ! primary key could not be translated (not RSA?)."
691                     else
692                         echo "1:${sshKey}"
693                     fi
694                 fi
695                 ;;
696             'sub') # sub keys
697                 # unset acceptability of last key
698                 lastKey=sub
699                 lastKeyOK=
700                 fingerprint=
701                 
702                 # don't bother with sub keys if the primary key is not valid
703                 if [ "$keyOK" != true ] ; then
704                     continue
705                 fi
706
707                 # don't bother with sub keys if no user ID is acceptable:
708                 if [ "$uidOK" != true ] ; then
709                     continue
710                 fi
711                 
712                 # if sub key validity is not ok, skip
713                 if [ "$validity" != 'u' -a "$validity" != 'f' ] ; then
714                     log debug "  - unacceptable sub key validity ($validity)."
715                     continue
716                 fi
717                 # if sub key capability is not ok, skip
718                 if ! check_capability "$usage" $requiredCapability ; then
719                     log debug "  - unacceptable sub key capability ($usage)."
720                     continue
721                 fi
722
723                 # mark sub key as ok
724                 lastKeyOK=true
725                 ;;
726             'fpr') # key fingerprint
727                 fingerprint="$uidfpr"
728
729                 sshKey=$(gpg2ssh "$fingerprint")
730
731                 # if the last key was the pub key, skip
732                 if [ "$lastKey" = pub ] ; then
733                     continue
734                 fi
735
736                 # output a line for the sub key
737                 # 0 = ok, 1 = bad
738                 if [ "$keyOK" -a "$uidOK" -a "$lastKeyOK" ] ; then
739                     log verbose "  * acceptable sub key."
740                     if [ -z "$sshKey" ] ; then
741                         log error "    ! sub key could not be translated (not RSA?)."
742                     else
743                         echo "0:${sshKey}"
744                     fi
745                 else
746                     log debug "  - unacceptable sub key."
747                     if [ -z "$sshKey" ] ; then
748                         log debug "    ! sub key could not be translated (not RSA?)."
749                     else
750                         echo "1:${sshKey}"
751                     fi
752                 fi
753                 ;;
754         esac
755     done | sort -t: -k1 -n -r
756     # NOTE: this last sort is important so that the "good" keys (key
757     # flag '0') come last.  This is so that they take precedence when
758     # being processed in the key files over "bad" keys (key flag '1')
759 }
760
761 # process a single host in the known_host file
762 process_host_known_hosts() {
763     local host
764     local userID
765     local noKey=
766     local nKeys
767     local nKeysOK
768     local ok
769     local sshKey
770     local tmpfile
771
772     # set the key processing mode
773     export MODE='known_hosts'
774
775     host="$1"
776     userID="ssh://${host}"
777
778     log verbose "processing: $host"
779
780     nKeys=0
781     nKeysOK=0
782
783     IFS=$'\n'
784     for line in $(process_user_id "${userID}") ; do
785         # note that key was found
786         nKeys=$((nKeys+1))
787
788         ok=$(echo "$line" | cut -d: -f1)
789         sshKey=$(echo "$line" | cut -d: -f2)
790
791         if [ -z "$sshKey" ] ; then
792             continue
793         fi
794
795         # remove any old host key line, and note if removed nothing is
796         # removed
797         remove_line "$KNOWN_HOSTS" "$sshKey" || noKey=true
798
799         # if key OK, add new host line
800         if [ "$ok" -eq '0' ] ; then
801             # note that key was found ok
802             nKeysOK=$((nKeysOK+1))
803
804             # hash if specified
805             if [ "$HASH_KNOWN_HOSTS" = 'true' ] ; then
806                 # FIXME: this is really hackish cause ssh-keygen won't
807                 # hash from stdin to stdout
808                 tmpfile=$(mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXX)
809                 ssh2known_hosts "$host" "$sshKey" > "$tmpfile"
810                 ssh-keygen -H -f "$tmpfile" 2>/dev/null
811                 cat "$tmpfile" >> "$KNOWN_HOSTS"
812                 rm -f "$tmpfile" "${tmpfile}.old"
813             else
814                 ssh2known_hosts "$host" "$sshKey" >> "$KNOWN_HOSTS"
815             fi
816
817             # log if this is a new key to the known_hosts file
818             if [ "$noKey" ] ; then
819                 log info "* new key for $host added to known_hosts file."
820             fi
821         fi
822     done
823
824     # if at least one key was found...
825     if [ "$nKeys" -gt 0 ] ; then
826         # if ok keys were found, return 0
827         if [ "$nKeysOK" -gt 0 ] ; then
828             return 0
829         # else return 2
830         else
831             return 2
832         fi
833     # if no keys were found, return 1
834     else
835         return 1
836     fi
837 }
838
839 # update the known_hosts file for a set of hosts listed on command
840 # line
841 update_known_hosts() {
842     local returnCode=0
843     local nHosts
844     local nHostsOK
845     local nHostsBAD
846     local fileCheck
847     local host
848     local newUmask
849
850     # the number of hosts specified on command line
851     nHosts="$#"
852
853     nHostsOK=0
854     nHostsBAD=0
855
856     # touch the known_hosts file so that the file permission check
857     # below won't fail upon not finding the file
858     if [ ! -f "$KNOWN_HOSTS" ]; then
859         # make sure to create any files or directories with the appropriate write bits turned off:
860         newUmask=$(printf "%04o" $(( 0$(umask) | 0022 )) )
861         [ -d $(dirname "$KNOWN_HOSTS") ] \
862             || (umask "$newUmask" && mkdir -p -m 0700 $(dirname "$KNOWN_HOSTS") ) \
863             || failure "Could not create path to known_hosts file '$KNOWN_HOSTS'"
864         # make sure to create this file with the appropriate bits turned off:
865         (umask "$newUmask" && touch "$KNOWN_HOSTS") \
866             || failure "Unable to create known_hosts file '$KNOWN_HOSTS'"
867     fi
868
869     # check permissions on the known_hosts file path
870     check_key_file_permissions $(whoami) "$KNOWN_HOSTS" \
871         || failure "Bad permissions governing known_hosts file '$KNOWN_HOSTS'"
872
873     # create a lockfile on known_hosts:
874     lock create "$KNOWN_HOSTS"
875     # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
876     trap "lock remove $KNOWN_HOSTS" EXIT
877
878     # note pre update file checksum
879     fileCheck=$(file_hash "$KNOWN_HOSTS")
880
881     for host ; do
882         # process the host
883         process_host_known_hosts "$host" || returnCode="$?"
884         # note the result
885         case "$returnCode" in
886             0)
887                 nHostsOK=$((nHostsOK+1))
888                 ;;
889             2)
890                 nHostsBAD=$((nHostsBAD+1))
891                 ;;
892         esac
893
894         # touch the lockfile, for good measure.
895         lock touch "$KNOWN_HOSTS"
896     done
897
898     # remove the lockfile and the trap
899     lock remove "$KNOWN_HOSTS"
900     trap - EXIT
901
902     # note if the known_hosts file was updated
903     if [ "$(file_hash "$KNOWN_HOSTS")" != "$fileCheck" ] ; then
904         log debug "known_hosts file updated."
905     fi
906
907     # if an acceptable host was found, return 0
908     if [ "$nHostsOK" -gt 0 ] ; then
909         return 0
910     # else if no ok hosts were found...
911     else
912         # if no bad host were found then no hosts were found at all,
913         # and return 1
914         if [ "$nHostsBAD" -eq 0 ] ; then
915             return 1
916         # else if at least one bad host was found, return 2
917         else
918             return 2
919         fi
920     fi
921 }
922
923 # process hosts from a known_hosts file
924 process_known_hosts() {
925     local hosts
926
927     # exit if the known_hosts file does not exist
928     if [ ! -e "$KNOWN_HOSTS" ] ; then
929         failure "known_hosts file '$KNOWN_HOSTS' does not exist."
930     fi
931
932     log debug "processing known_hosts file:"
933     log debug " $KNOWN_HOSTS"
934
935     hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
936
937     if [ -z "$hosts" ] ; then
938         log debug "no hosts to process."
939         return
940     fi
941
942     # take all the hosts from the known_hosts file (first
943     # field), grep out all the hashed hosts (lines starting
944     # with '|')...
945     update_known_hosts $hosts
946 }
947
948 # process uids for the authorized_keys file
949 process_uid_authorized_keys() {
950     local userID
951     local nKeys
952     local nKeysOK
953     local ok
954     local sshKey
955
956     # set the key processing mode
957     export MODE='authorized_keys'
958
959     userID="$1"
960
961     log verbose "processing: $userID"
962
963     nKeys=0
964     nKeysOK=0
965
966     IFS=$'\n'
967     for line in $(process_user_id "$userID") ; do
968         # note that key was found
969         nKeys=$((nKeys+1))
970
971         ok=$(echo "$line" | cut -d: -f1)
972         sshKey=$(echo "$line" | cut -d: -f2)
973
974         if [ -z "$sshKey" ] ; then
975             continue
976         fi
977
978         # remove the old host key line
979         remove_line "$AUTHORIZED_KEYS" "$sshKey"
980
981         # if key OK, add new host line
982         if [ "$ok" -eq '0' ] ; then
983             # note that key was found ok
984             nKeysOK=$((nKeysOK+1))
985
986             ssh2authorized_keys "$userID" "$sshKey" >> "$AUTHORIZED_KEYS"
987         fi
988     done
989
990     # if at least one key was found...
991     if [ "$nKeys" -gt 0 ] ; then
992         # if ok keys were found, return 0
993         if [ "$nKeysOK" -gt 0 ] ; then
994             return 0
995         # else return 2
996         else
997             return 2
998         fi
999     # if no keys were found, return 1
1000     else
1001         return 1
1002     fi
1003 }
1004
1005 # update the authorized_keys files from a list of user IDs on command
1006 # line
1007 update_authorized_keys() {
1008     local returnCode=0
1009     local userID
1010     local nIDs
1011     local nIDsOK
1012     local nIDsBAD
1013     local fileCheck
1014
1015     # the number of ids specified on command line
1016     nIDs="$#"
1017
1018     nIDsOK=0
1019     nIDsBAD=0
1020
1021     log debug "updating authorized_keys file:"
1022     log debug " $AUTHORIZED_KEYS"
1023
1024     # check permissions on the authorized_keys file path
1025     check_key_file_permissions $(whoami) "$AUTHORIZED_KEYS" || failure
1026
1027     # create a lockfile on authorized_keys
1028     lock create "$AUTHORIZED_KEYS"
1029     # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
1030     trap "lock remove $AUTHORIZED_KEYS" EXIT
1031
1032     # note pre update file checksum
1033     fileCheck="$(file_hash "$AUTHORIZED_KEYS")"
1034
1035     # remove any monkeysphere lines from authorized_keys file
1036     remove_monkeysphere_lines "$AUTHORIZED_KEYS"
1037
1038     for userID ; do
1039         # process the user ID, change return code if key not found for
1040         # user ID
1041         process_uid_authorized_keys "$userID" || returnCode="$?"
1042
1043         # note the result
1044         case "$returnCode" in
1045             0)
1046                 nIDsOK=$((nIDsOK+1))
1047                 ;;
1048             2)
1049                 nIDsBAD=$((nIDsBAD+1))
1050                 ;;
1051         esac
1052
1053         # touch the lockfile, for good measure.
1054         lock touch "$AUTHORIZED_KEYS"
1055     done
1056
1057     # remove the lockfile and the trap
1058     lock remove "$AUTHORIZED_KEYS"
1059
1060     # remove the trap
1061     trap - EXIT
1062
1063     # note if the authorized_keys file was updated
1064     if [ "$(file_hash "$AUTHORIZED_KEYS")" != "$fileCheck" ] ; then
1065         log debug "authorized_keys file updated."
1066     fi
1067
1068     # if an acceptable id was found, return 0
1069     if [ "$nIDsOK" -gt 0 ] ; then
1070         return 0
1071     # else if no ok ids were found...
1072     else
1073         # if no bad ids were found then no ids were found at all, and
1074         # return 1
1075         if [ "$nIDsBAD" -eq 0 ] ; then
1076             return 1
1077         # else if at least one bad id was found, return 2
1078         else
1079             return 2
1080         fi
1081     fi
1082 }
1083
1084 # process an authorized_user_ids file for authorized_keys
1085 process_authorized_user_ids() {
1086     local line
1087     local nline
1088     local userIDs
1089
1090     authorizedUserIDs="$1"
1091
1092     # exit if the authorized_user_ids file is empty
1093     if [ ! -e "$authorizedUserIDs" ] ; then
1094         failure "authorized_user_ids file '$authorizedUserIDs' does not exist."
1095     fi
1096
1097     log debug "processing authorized_user_ids file:"
1098     log debug " $authorizedUserIDs"
1099
1100     # check permissions on the authorized_user_ids file path
1101     check_key_file_permissions $(whoami) "$authorizedUserIDs" || failure
1102
1103     if ! meat "$authorizedUserIDs" >/dev/null ; then
1104         log debug " no user IDs to process."
1105         return
1106     fi
1107
1108     nline=0
1109
1110     # extract user IDs from authorized_user_ids file
1111     IFS=$'\n'
1112     for line in $(meat "$authorizedUserIDs") ; do
1113         userIDs["$nline"]="$line"
1114         nline=$((nline+1))
1115     done
1116
1117     update_authorized_keys "${userIDs[@]}"
1118 }
1119
1120 # takes a gpg key or keys on stdin, and outputs a list of
1121 # fingerprints, one per line:
1122 list_primary_fingerprints() {
1123     local fake=$(msmktempdir)
1124     GNUPGHOME="$fake" gpg --no-tty --quiet --import
1125     GNUPGHOME="$fake" gpg --with-colons --fingerprint --list-keys | \
1126         awk -F: '/^fpr:/{ print $10 }'
1127     rm -rf "$fake"
1128 }
1129
1130
1131 check_cruft_file() {
1132     local loc="$1"
1133     local version="$2"
1134     
1135     if [ -e "$loc" ] ; then
1136         printf "! The file '%s' is no longer used by\n  monkeysphere (as of version %s), and can be removed.\n\n" "$loc" "$version" | log info
1137     fi
1138 }
1139
1140 check_upgrade_dir() {
1141     local loc="$1"
1142     local version="$2"
1143
1144     if [ -d "$loc" ] ; then
1145         printf "The presence of directory '%s' indicates that you have\nnot yet completed a monkeysphere upgrade.\nYou should probably run the following script:\n  %s/transitions/%s\n\n" "$loc" "$SYSSHAREDIR" "$version" | log info
1146     fi
1147 }
1148
1149 ## look for cruft from old versions of the monkeysphere, and notice if
1150 ## upgrades have not been run:
1151 report_cruft() {
1152     check_upgrade_dir "${SYSCONFIGDIR}/gnupg-host" 0.23
1153     check_upgrade_dir "${SYSCONFIGDIR}/gnupg-authentication" 0.23
1154
1155     check_cruft_file "${SYSCONFIGDIR}/gnupg-authentication.conf" 0.23
1156     check_cruft_file "${SYSCONFIGDIR}/gnupg-host.conf" 0.23
1157
1158     local found=
1159     for foo in "${SYSDATADIR}/backup-from-"*"-transition"  ; do
1160         if [ -d "$foo" ] ; then
1161             printf "! %s\n" "$foo" | log info
1162             found=true
1163         fi
1164     done
1165     if [ "$found" ] ; then
1166         printf "The directories above are backups left over from a monkeysphere transition.\nThey may contain copies of sensitive data (host keys, certifier lists), but\nthey are no longer needed by monkeysphere.\nYou may remove them at any time.\n\n" | log info
1167     fi
1168 }