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