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