chiark / gitweb /
keys.new-recov, keys.reveal, keyfunc.sh.in: Don't put @bindir@ on the PATH.
[distorted-keys] / keyfunc.sh.in
1 ### -*-sh-*-
2 ###
3 ### Common key management functions.
4 ###
5 ### (c) 2011 Mark Wooding
6 ###
7
8 ###----- Licensing notice ---------------------------------------------------
9 ###
10 ### This file is part of the distorted.org.uk key management suite.
11 ###
12 ### distorted-keys is free software; you can redistribute it and/or modify
13 ### it under the terms of the GNU General Public License as published by
14 ### the Free Software Foundation; either version 2 of the License, or
15 ### (at your option) any later version.
16 ###
17 ### distorted-keys is distributed in the hope that it will be useful,
18 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ### GNU General Public License for more details.
21 ###
22 ### You should have received a copy of the GNU General Public License
23 ### along with distorted-keys; if not, write to the Free Software Foundation,
24 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 quis=${0##*/}
27
28 ###--------------------------------------------------------------------------
29 ### Configuration variables.
30
31 PACKAGE="@PACKAGE@" VERSION="@VERSION@"
32 bindir="@bindir@"
33
34 if [ -f $ETC/keys.conf ]; then . $ETC/keys.conf; fi
35
36 case "${KEYS_DEBUG+t}" in t) set -x ;; esac
37
38 ###--------------------------------------------------------------------------
39 ### Cleanup handling.
40
41 cleanups=""
42 cleanup () { cleanups=${cleanups+$cleanups }$1; }
43 runcleanups () { for i in $cleanups; do $i; done; }
44 trap 'rc=$?; runcleanups; exit $rc' EXIT
45 trap 'trap "" EXIT; runcleanups; exit 127' INT TERM
46
47 ###--------------------------------------------------------------------------
48 ### Utility functions.
49
50 reqsafe () {
51   ## Fail unless a safe directory is set.
52
53   err="$quis: (CONFIGURATION ERROR)"
54   case ${SAFE+t} in
55     t) ;;
56     *) echo >&2 "$err: no SAFE directory"; exit 1 ;;
57   esac
58   if [ ! -d "$SAFE" ]; then
59     echo >&2 "$err: SAFE path \`$SAFE' isn't a directory"
60     exit 1
61   fi
62   case "$SAFE" in
63     [!/]* | *[][[:space:]*?]*)
64       echo >&2 "$err: SAFE path \`$SAFE' contains bad characters"
65       exit 1
66       ;;
67   esac
68   ls -ld "$SAFE" | {
69     me=$(id -un)
70     read perm _ user stuff
71     case "$perm:$user" in
72       d???------:"$me") ;;
73       *)
74         echo >&2 "$err: SAFE path \`$SAFE' has bad owner or permissions"
75         exit 1
76         ;;
77     esac
78   }
79 }
80
81 ## Temporary directory.
82 unset tmp
83 rmtmp () { case ${tmp+t} in t) cd /; rm -rf $tmp ;; esac; }
84 cleanup rmtmp
85 mktmp () {
86   ## Make a temporary directory and store its name in `tmp'.
87
88   case "${tmp+t}" in t) return ;; esac
89   reqsafe
90   tmp="$SAFE/keys.tmp.$$"
91   rm -rf "$tmp"
92   mkdir -m700 "$tmp"
93 }
94
95 reqtmp () {
96   ## Fail unless a temporary directory is set.
97
98   case ${tmp+t} in
99     t) ;;
100     *) echo >&2 "$quis (INTERNAL): no tmp directory set"; exit 127 ;;
101   esac
102 }
103
104 parse_keylabel () {
105   key=$1
106   ## Parse the key label string KEY.  Set `kdir' to the base path to use for
107   ## the key's storage, and `kowner' to the key owner's name.
108
109   case "$key" in
110     *:*) kowner=${key%%:*} klabel=${key#*:} ;;
111     *) kowner=$USERV_USER klabel=$key ;;
112   esac
113   checkword "key owner name" "$kowner"
114   checklabel "key" "$klabel"
115   kdir=$KEYS/store/$kowner/$klabel
116   knub=$KEYS/nub/$kowner/$klabel
117 }
118
119 ###--------------------------------------------------------------------------
120 ### Input validation functions.
121
122 nl="
123 "
124 check () {
125   ckwhat=$1 ckpat=$2 thing=$3
126   ## Verify that THING matches the (anchored, basic) regular expression
127   ## CKPAT.  Since matching newlines is hard to do portably, also check that
128   ## THING doesn't contain any.  If the checks fail, report an error and
129   ## exit.
130
131   validp=t
132   case "$thing" in
133     *"$nl"*) validp=nil ;;
134     *) if ! expr >/dev/null "$thing" : "$ckpat\$"; then validp=nil; fi ;;
135   esac
136   case $validp in
137     nil) echo >&2 "$quis: bad $ckwhat \`$thing'"; exit 1 ;;
138   esac
139 }
140
141 ## Regular expressions for validating input.
142 R_IDENTCHARS="A-Za-z0-9_"
143 R_WORDCHARS="-$R_IDENTCHARS!%@+="
144 R_IDENT="[$R_IDENTCHARS][$R_IDENTCHARS]*"
145 R_WORD="[$R_WORDCHARS][$R_WORDCHARS]*"
146 R_WORDSEQ="[$R_WORDCHARS[:space:]][$R_WORDCHARS[:space:]]*"
147 R_NUMERIC='\(\([1-9][0-9]*\)\{0,1\}0\{0,1\}\)'
148 R_LABEL="\($R_WORD\(/$R_WORD\)*\)"
149 R_LINE=".*"
150
151 ## Various validation functions.
152 checknumber () { check "$1" "$R_NUMERIC" "$2"; }
153 checkident () { check "$1" "$R_IDENT" "$2"; }
154 checkword () { check "$1" "$R_WORD" "$2"; }
155 checklabel () { check "$1 label" "$R_LABEL" "$2"; }
156
157 ###--------------------------------------------------------------------------
158 ### Key storage and properties.
159
160 getsysprofile () {
161   profile=$1
162   ## Write the named system PROFILE to standard output.
163
164   $bindir/extract-profile "$profile" $ETC/profile.d/
165 }
166
167 setprops () {
168   what=$1 prefix=$2; shift 2
169   ## Set variables based on the NAME=VALUE assignments in the arguments.  The
170   ## value for property NAME is stored in the shell variable PREFIX_NAME.
171
172   for assg in "$@"; do
173     goodp=t
174     case "$assg" in
175       *\=*) name=${assg%%=*} value=${assg#*=} ;;
176       *) goodp=nil ;;
177     esac
178     case "$goodp,$name" in t,*[!0-9A-Za-z_]*=*) goodp=nil ;; esac
179     case "$goodp" in
180       nil) echo >&2 "$quis: bad $what assignment \`$assg'"; exit 1 ;;
181     esac
182     eval "$prefix$name=\$value"
183   done
184 }
185
186 checkprops () {
187   whatprop=$1 prefix=$2; shift 2
188   ## Check that property variables are set in accordance with the remaining
189   ## TABLE arguments.  Each row of TABLE has the form
190   ##
191   ##    NAME OMIT PAT
192   ##
193   ## A table row is satisfied if there is a variable PREFIXNAME whose value
194   ## matces the (basic) regular expression PAT, or if the variable is unset
195   ## and OMIT is `t'.
196
197   for table in "$@"; do
198     case "$table" in ?*) ;; *) continue ;; esac
199     while read -r name omit pat; do
200       eval foundp=\${$prefix$name+t}
201       case "$foundp,$omit" in
202         ,t) continue ;;
203         ,nil)
204           echo >&2 "$quis: missing $whatprop \`$name' required"
205           exit 1
206           ;;
207       esac
208       eval value=\$$prefix$name
209       check "value for $whatprop \`$name'" "$pat" "$value"
210     done <<EOF
211 $table
212 EOF
213   done
214 }
215
216 defprops () {
217   name=$1
218   ## Define a properties table NAME.
219
220   table=$(cat)
221   eval $name=\$table
222 }
223
224 defprops g_props <<EOF
225 type                    nil     $R_IDENT
226 recovery                t       $R_WORDSEQ
227 random                  t       $R_WORD
228 nub_hash                t       $R_WORD
229 nubid_hash              t       $R_WORD
230 nub_random_bytes        t       $R_NUMERIC
231 EOF
232
233 readprops () {
234   file=$1
235   ## Read a profile from a file.  This doesn't check the form of the
236   ## filename, so it's not suitable for unchecked input.  Properties are set
237   ## using `setprops' with prefix `kprop_'.
238
239   ## Parse the settings from the file.
240   exec 3<"$file"
241   while read line; do
242     case "$line" in "" | \#*) continue ;; esac
243     setprops "property" kprop_ "$line"
244   done <&3
245   exec 3>&-
246   checkprops "property" kprop_ "$g_props"
247
248   ## Fetch the key-type handling library.
249   if [ ! -f $KEYSLIB/ktype.$kprop_type ]; then
250     echo >&2 "$quis: unknown key type \`$kprop_type'"
251     exit 1
252   fi
253   . $KEYSLIB/ktype.$kprop_type
254   checkprops "property" kprop_ "$k_props"
255 }
256
257 readmeta () {
258   kdir=$1
259   ## Read key metadata from KDIR.
260
261   { read profile; } <"$kdir"/meta
262 }
263
264 makenub () {
265   ## Generate a key nub in the default way, and write it to standard output.
266   ## The properties `random', `nub_random_bytes' and `nub_hash' are referred
267   ## to.
268
269   dd 2>/dev/null \
270     if=/dev/${kprop_random-random} bs=1 count=${kprop_nub_random_bytes-64} |
271   openssl dgst -${kprop_nub_hash-sha256} -binary |
272   openssl base64
273 }
274
275 nubid () {
276   ## Compute a hash of the key nub in stdin, and write it to stdout in hex.
277   ## The property `nubid_hash' is used.
278
279   { echo "distorted-keys nubid"; cat -; } |
280   openssl dgst -${kprop_nubid_hash-sha256}
281 }
282
283 subst () {
284   what=$1 templ=$2 prefix=$3 pat=$4
285   ## Substitute option values into the template TEMPL.  Each occurrence of
286   ## %{VAR} is replaced by the value of the variable PREFIXVAR.  Finally, an
287   ## error is reported unless the final value matches the regular expression
288   ## PAT.
289
290   out=""
291   rest=$templ
292   while :; do
293
294     ## If there are no more markers to substitute, then finish.
295     case "$rest" in *"%{"*"}"*) ;; *) out=$out$rest; break ;; esac
296
297     ## Split the template into three parts.
298     left=${rest%%\%\{*} right=${rest#*\%\{}
299     var=${right%%\}*} rest=${right#*\}}
300     case "$var" in
301       *-*) default=${var#*-} var=${var%%-*} defaultp=t ;;
302       *) defaultp=nil ;;
303     esac
304
305     ## Find the variable value.
306     checkident "template variable name" "$var"
307     eval foundp=\${$prefix$var+t}
308     case $foundp,$defaultp in
309       t,*) eval value=\$$prefix$var ;;
310       ,t) value=$default ;;
311       *)
312         echo >&2 "$quis: option \`$var' unset, used in template \`$templ'"
313         exit 1
314         ;;
315     esac
316
317     ## Do the substitution.
318     out=$out$left$value
319   done
320
321   ## Check the final result.
322   check "$what" "$pat" "$out"
323
324   ## Done.
325   echo "$out"
326 }
327
328 read_profile () {
329   profile=$1
330   ## Read property settings from a profile.  The PROFILE name has the form
331   ## [USER:]LABEL.  Properties are set using `setprops' with prefix `kprop_'.
332
333   reqtmp
334   case "$profile" in
335     :*)
336       label=${profile#:} uservp=nil
337       ;;
338     *)
339       user=$USERV_USER label=$profile uservp=t
340       ;;
341     *:*)
342       user=${profile%%:*} label=${profile#*:} uservp=t
343       ;;
344   esac
345   checkword "profile label" "$label"
346
347   ## Fetch the profile settings from the user.
348   reqtmp
349   case $uservp in
350     t)
351       checkword "profile user" "$user"
352       userv "$user" cryptop-profile "$label" >$tmp/profile
353       ;;
354     nil)
355       $bindir/extract-profile "$label" $ETC/profile.d/ >$tmp/profile
356       ;;
357   esac
358
359   ## Read the file.
360   readprops $tmp/profile
361 }
362
363 ###--------------------------------------------------------------------------
364 ### General crypto operations.
365
366 c_genkey () {
367   profile=$1 kdir=$2 knub=$3 hook=$4; shift 4
368   ## Generate a key, and associate it with the named PROFILE (which is
369   ## assumed already to have been read!); store the main data in KDIR, and
370   ## the nub separately in the file KNUB; run HOOK after generation, passing
371   ## it the working key directory and nub file.  Remaining arguments are
372   ## options to the key type.
373
374   ## Set options and check them.
375   setprops "option" kopt_ "$@"
376   checkprops "option" kopt_ "$k_genopts"
377
378   ## Create directory structure and start writing metadata.
379   rm -rf "$kdir.new"
380   mkdir -m755 -p "$kdir.new"
381   case "$knub" in */*) mkdir -m700 -p "${knub%/*}" ;; esac
382   cat >"$kdir.new/meta" <<EOF
383 $profile
384 EOF
385
386   ## Generate the key.
387   umask=$(umask); umask 077; >"$knub.new"; umask $umask
388   k_generate "$kdir.new" "$knub.new"
389   $hook "$kdir.new" "$knub.new"
390
391   ## Hash the nub.
392   nubid <"$knub.new" >"$kdir.new/nubid"
393
394   ## Juggle everything into place.  Doing this atomically is very difficult,
395   ## and requires more machinery than I can really justify here.  If
396   ## something goes wrong halfway, it should always be possible to fix it,
397   ## either by backing out (if $kdir.new still exists) or pressing on
398   ## forwards (if not).
399   rm -rf "$kdir.old"
400   if [ -e "$kdir" ]; then mv "$kdir" "$kdir.old"; fi
401   mv "$kdir.new" "$kdir"
402   mv "$knub.new" "$knub"
403   rm -rf "$kdir.old"
404 }
405
406 c_encrypt () { k_encrypt "$@"; }
407 c_decrypt () {
408   if k_decrypt "$@" >$tmp/plain; then cat $tmp/plain
409   else return $?
410   fi
411 }
412 c_sign () { k_sign "$@"; }
413 c_verify () { k_verify "$@"; }
414
415 ## Stub implementations.
416 notsupp () { op=$1; echo >&2 "$quis: operation \`$op' not supported"; }
417 k_info () { :; }
418 k_encrypt () { notsupp encrypt; }
419 k_decrypt () { notsupp decrypt; }
420 k_sign () { notsupp sign; }
421 k_verify () { notsupp verify; }
422
423 prepare () {
424   key=$1 op=$2
425   ## Prepare for a crypto operation OP, using the KEY.  This validates the
426   ## key label, reads the profile, and checks the access-control list.
427
428   ## Find the key properties.
429   parse_keylabel "$key"
430   if [ ! -d $kdir ]; then echo >&2 "$quis: unknown key \`$key'"; exit 1; fi
431   readmeta $kdir
432   read_profile "$profile"
433
434   ## Check whether we're allowed to do this thing.  This is annoyingly
435   ## fiddly.
436   eval acl=\${kprop_acl_$op-!owner}
437   verdict=forbid
438   while :; do
439
440     ## Remove leading whitespace.
441     while :; do
442       case "$acl" in
443         [[:space:]]*) acl=${acl#?} ;;
444         *) break ;;
445       esac
446     done
447
448     ## If there's nothing left, leave.
449     case "$acl" in ?*) ;; *) break ;; esac
450
451     ## Split off the leading word.
452     case "$acl" in
453       *[[:space:]]*) word=${acl%%[[:space:]]*} acl=${acl#*[[:space:]]} ;;
454       *) word=$acl acl="" ;;
455     esac
456
457     ## See what sense it has if it matches.
458     case "$word" in
459       -*) sense=forbid rest=${word#-} ;;
460       *) sense=allow rest=$word ;;
461     esac
462
463     ## See whether the calling user matches.
464     case "$rest" in
465       !owner) pat=$kowner list=$USERV_USER ;;
466       !*) echo >&2 "$quis: unknown ACL token \`$word'" ;;
467       %*) pat=${rest#%} list="$USERV_GROUP $USERV_GID" ;;
468       *) pat=$rest list="$USERV_USER $USERV_UID" ;;
469     esac
470     matchp=nil
471     for i in $list; do case "$i" in $pat) matchp=t; break ;; esac; done
472     case $matchp in t) verdict=$sense; break ;; esac
473   done
474
475   case $verdict in
476     forbid) echo >&2 "$quis: $op access to key \`$key' forbidden"; exit 1 ;;
477   esac
478 }
479
480 ###--------------------------------------------------------------------------
481 ### Crypto operations for infrastructure purposes.
482
483 c_sysprofile () {
484   profile=$1
485   ## Select the profile in FILE for future crypto operations.
486
487   unset $(set | sed -n '/^kprop_/s/=.*$//p')
488   reqtmp
489   getsysprofile "$profile" >$tmp/profile
490   readprops $tmp/profile
491 }
492
493 c_gensyskey () {
494   profile=$1 kdir=$2 knub=$3; shift 3
495   ## Generate a system key using PROFILE; store the data in KDIR and the nub
496   ## in KNUB.  Remaining arguments are options.
497
498   c_sysprofile "$profile"
499   c_genkey "$profile" "$kdir" "$knub" : "$@"
500 }
501
502 c_sysprepare () {
503   kdir=$1
504   readmeta "$kdir"
505   c_sysprofile "$profile"
506 }
507
508 c_sysop () {
509   op=$1 kdir=$2; shift 1
510   c_sysprepare "$kdir"
511   c_$op "$@"
512 }
513
514 c_sysencrypt () { c_sysop encrypt "$1" /dev/null; }
515 c_sysdecrypt () { c_sysop decrypt "$1" "$2"; }
516 c_syssign () { c_sysop sign "$1" "$2"; }
517 c_sysverify () { c_sysop verify "$1" /dev/null; }
518
519 ###--------------------------------------------------------------------------
520 ### Recovery operations.
521
522 stash () {
523   recov=$1 label=$2
524   ## Stash a copy of stdin encrypted under the recovery key RECOV, with a
525   ## given LABEL.
526   checkword "recovery key label" "$recov"
527   checklabel "secret" "$label"
528
529   rdir=$KEYS/recov/$recov/current
530   if [ ! -d $rdir/store ]; then
531     echo >&2 "$quis: unknown recovery key \`$recov'"
532     exit 1
533   fi
534   case $label in */*) mkdir -m755 -p $rdir/${label%/*} ;; esac
535   (c_sysencrypt $rdir/store >$rdir/$label.new)
536   mv $rdir/$label.new $rdir/$label.recov
537 }
538
539 recover () {
540   recov=$1 label=$2
541   ## Recover a stashed secret, protected by RECOV and stored as LABEL, and
542   ## write it to stdout.
543   checkword "recovery key label" "$recov"
544   checklabel "secret" "$label"
545
546   rdir=$KEYS/recov/$recov/current
547   if [ ! -f $rdir/$label.recov ]; then
548     echo >&2 "$quis: no blob for \`$label' under recovery key \`$recov'"
549     exit 1
550   fi
551   reqsafe
552   nub=$SAFE/keys.reveal/$recov.current/nub
553   if [ ! -f $nub ]; then
554     echo >&2 "$quis: current recovery key \`$recov' not revealed"
555     exit 1;
556   fi
557   mktmp
558   c_sysdecrypt $rdir/store $nub <$rdir/$label.recov
559 }
560
561 ###--------------------------------------------------------------------------
562 ### Help text.
563
564 defhelp () {
565   read umsg
566   usage="usage: $quis${umsg+ }$umsg"
567   help=$(cat)
568   case "$KEYS_HELP" in t) help; exit ;; esac
569 }
570
571 help () { showhelp; }
572 showhelp () {
573   cat <<EOF
574 $usage
575
576 $help
577 EOF
578 }
579
580 usage_err () { echo >&2 "$usage"; exit 1; }
581
582 ###--------------------------------------------------------------------------
583 ### Subcommand handling.
584
585 version () {
586   echo "$PACKAGE version $VERSION"
587 }
588
589 cmd_help () {
590   rc=0
591   version
592   case $# in
593     0)
594       cat <<EOF
595
596 $usage
597
598 Options:
599   -h            Show this help text.
600   -v            Show the program version number.
601
602 Commands installed:
603 EOF
604       cd "$KEYSLIB"
605       for i in $prefix.*; do
606         if [ ! -x "$i" ]; then continue; fi
607         sed -n "/<<HELP/{n;s/^/ ${i#$prefix.} /;p;q;}" "$i"
608       done
609       ;;
610     *)
611       for i in "$@"; do
612         echo
613         if [ ! -x "$KEYSLIB/$prefix.$i" ]; then
614           echo >&2 "$quis: unrecognized command \`$i'"
615           rc=1
616           continue
617         elif ! KEYS_HELP=t "$KEYSLIB/$prefix.$i"; then
618           rc=1
619         fi
620       done
621       ;;
622   esac
623   return $rc
624 }
625
626 dispatch () {
627   case $# in 0) echo >&2 "$usage"; exit 1 ;; esac
628   cmd=$1; shift
629   case "$cmd" in help) cmd_help "$@"; exit ;; esac
630   if [ ! -x "$KEYSLIB/$prefix.$cmd" ]; then
631     echo >&2 "$quis: unrecognized command \`$cmd'"
632     exit 1
633   fi
634
635   unset KEYS_HELP
636   exec "$KEYSLIB/$prefix.$cmd" "$@"
637 }
638
639 ###----- That's all, folks --------------------------------------------------