chiark / gitweb /
Multiple key types, key profiles, and user key storage.
[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 $ETC/profile.d/ "$profile"
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 nubhash                 t       $R_WORD
231 nubidhash               t       $R_WORD
232 nubsz                   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', `nubsz' and `nubhash' are referred to.
269
270   dd 2>/dev/null \
271     if=/dev/${kprop_random-random} bs=1 count=${kprop_nubsz-512} |
272   openssl dgst -${kprop_nubhash-sha384} -binary |
273   openssl base64
274 }
275
276 nubid () {
277   ## Compute a hash of the key nub in stdin, and write it to stdout in hex.
278   ## The property `nubidhash' is used.
279
280   { echo "distorted-keys nubid"; cat -; } |
281   openssl dgst -${kprop_nubidhash-sha256}
282 }
283
284 subst () {
285   what=$1 templ=$2 prefix=$3 pat=$4
286   ## Substitute option values into the template TEMPL.  Each occurrence of
287   ## %{VAR} is replaced by the value of the variable PREFIXVAR.  Finally, an
288   ## error is reported unless the final value matches the regular expression
289   ## PAT.
290
291   out=""
292   rest=$templ
293   while :; do
294
295     ## If there are no more markers to substitute, then finish.
296     case "$rest" in *"%{"*"}"*) ;; *) out=$out$rest; break ;; esac
297
298     ## Split the template into three parts.
299     left=${rest%%\%\{*} right=${rest#*\%\{}
300     var=${right%%\}*} rest=${right#*\}}
301     case "$var" in
302       *-*) default=${var#*-} var=${var%%-*} defaultp=t ;;
303       *) defaultp=nil ;;
304     esac
305
306     ## Find the variable value.
307     checkident "template variable name" "$var"
308     eval foundp=\${$prefix$var+t}
309     case $foundp,$defaultp in
310       t,*) eval value=\$$prefix$var ;;
311       ,t) value=$default ;;
312       *)
313         echo >&2 "$quis: option \`$var' unset, used in template \`$templ'"
314         exit 1
315         ;;
316     esac
317
318     ## Do the substitution.
319     out=$out$left$value
320   done
321
322   ## Check the final result.
323   check "$what" "$pat" "$out"
324
325   ## Done.
326   echo "$out"
327 }
328
329 read_profile () {
330   profile=$1
331   ## Read property settings from a profile.  The PROFILE name has the form
332   ## [USER:]LABEL.  Properties are set using `setprops' with prefix `kprop_'.
333
334   reqtmp
335   case "$profile" in
336     :*)
337       label=${profile#:} uservp=nil
338       ;;
339     *)
340       user=$USERV_USER label=$profile uservp=t
341       ;;
342     *:*)
343       user=${profile%%:*} label=${profile#*:} uservp=t
344       ;;
345   esac
346   checkword "profile label" "$label"
347
348   ## Fetch the profile settings from the user.
349   reqtmp
350   case $uservp in
351     t)
352       checkword "profile user" "$user"
353       userv "$user" cryptop-profile "$label" >$tmp/profile
354       ;;
355     nil)
356       $bindir/extract-profile $ETC/profile.d/ "$label" >$tmp/profile
357       ;;
358   esac
359
360   ## Read the file.
361   readprops $tmp/profile
362 }
363
364 ###--------------------------------------------------------------------------
365 ### General crypto operations.
366
367 c_genkey () {
368   profile=$1 kdir=$2 knub=$3 hook=$4; shift 4
369   ## Generate a key, and associate it with the named PROFILE (which is
370   ## assumed already to have been read!); store the main data in KDIR, and
371   ## the nub separately in the file KNUB; run HOOK after generation, passing
372   ## it the working key directory and nub file.  Remaining arguments are
373   ## options to the key type.
374
375   ## Set options and check them.
376   setprops "option" kopt_ "$@"
377   checkprops "option" kopt_ "$k_genopts"
378
379   ## Create directory structure and start writing metadata.
380   rm -rf "$kdir.new"
381   mkdir -m755 -p "$kdir.new"
382   case "$knub" in */*) mkdir -m700 -p "${knub%/*}" ;; esac
383   cat >"$kdir.new/meta" <<EOF
384 $profile
385 EOF
386
387   ## Generate the key.
388   umask=$(umask); umask 077; >"$knub.new"; umask $umask
389   k_generate "$kdir.new" "$knub.new"
390   $hook "$kdir.new" "$knub.new"
391
392   ## Hash the nub.
393   nubid <"$knub.new" >"$kdir.new/nubid"
394
395   ## Juggle everything into place.  Doing this atomically is very difficult,
396   ## and requires more machinery than I can really justify here.  If
397   ## something goes wrong halfway, it should always be possible to fix it,
398   ## either by backing out (if $kdir.new still exists) or pressing on
399   ## forwards (if not).
400   rm -rf "$kdir.old"
401   if [ -e "$kdir" ]; then mv "$kdir" "$kdir.old"; fi
402   mv "$kdir.new" "$kdir"
403   mv "$knub.new" "$knub"
404   rm -rf "$kdir.old"
405 }
406
407 c_encrypt () { k_encrypt "$@"; }
408 c_decrypt () {
409   if k_decrypt "$@" >$tmp/plain; then cat $tmp/plain
410   else return $?
411   fi
412 }
413 c_sign () { k_sign "$@"; }
414 c_verify () { k_verify "$@"; }
415
416 ## Stub implementations.
417 notsupp () { op=$1; echo >&2 "$quis: operation \`$op' not supported"; }
418 k_info () { :; }
419 k_encrypt () { notsupp encrypt; }
420 k_decrypt () { notsupp decrypt; }
421 k_sign () { notsupp sign; }
422 k_verify () { notsupp verify; }
423
424 prepare () {
425   key=$1 op=$2
426   ## Prepare for a crypto operation OP, using the KEY.  This validates the
427   ## key label, reads the profile, and checks the access-control list.
428
429   ## Find the key properties.
430   parse_keylabel "$key"
431   if [ ! -d $kdir ]; then echo >&2 "$quis: unknown key \`$key'"; exit 1; fi
432   readmeta $kdir
433   read_profile "$profile"
434
435   ## Check whether we're allowed to do this thing.  This is annoyingly
436   ## fiddly.
437   eval acl=\${kprop_acl_$op-!owner}
438   verdict=forbid
439   while :; do
440
441     ## Remove leading whitespace.
442     while :; do
443       case "$acl" in
444         [[:space:]]*) acl=${acl#?} ;;
445         *) break ;;
446       esac
447     done
448
449     ## If there's nothing left, leave.
450     case "$acl" in ?*) ;; *) break ;; esac
451
452     ## Split off the leading word.
453     case "$acl" in
454       *[[:space:]]*) word=${acl%%[[:space:]]*} acl=${acl#*[[:space:]]} ;;
455       *) word=$acl acl="" ;;
456     esac
457
458     ## See what sense it has if it matches.
459     case "$word" in
460       -*) sense=forbid rest=${word#-} ;;
461       *) sense=allow rest=$word ;;
462     esac
463
464     ## See whether the calling user matches.
465     case "$rest" in
466       !owner) pat=$kowner list=$USERV_USER ;;
467       !*) echo >&2 "$quis: unknown ACL token \`$word'" ;;
468       %*) pat=${rest#%} list="$USERV_GROUP $USERV_GID" ;;
469       *) pat=$rest list="$USERV_USER $USERV_UID" ;;
470     esac
471     matchp=nil
472     for i in $list; do case "$i" in $pat) matchp=t; break ;; esac; done
473     case $matchp in t) verdict=$sense; break ;; esac
474   done
475
476   case $verdict in
477     forbid) echo >&2 "$quis: $op access to key \`$key' forbidden"; exit ;;
478   esac
479 }
480
481 ###--------------------------------------------------------------------------
482 ### Crypto operations for infrastructure purposes.
483
484 c_sysprofile () {
485   profile=$1
486   ## Select the profile in FILE for future crypto operations.
487
488   unset $(set | sed -n '/^kprop_/s/=.*$//p')
489   reqtmp
490   getsysprofile "$profile" >$tmp/profile
491   readprops $tmp/profile
492 }
493
494 c_gensyskey () {
495   profile=$1 kdir=$2 knub=$3; shift 3
496   ## Generate a system key using PROFILE; store the data in KDIR and the nub
497   ## in KNUB.  Remaining arguments are options.
498
499   c_sysprofile "$profile"
500   c_genkey "$profile" "$kdir" "$knub" : "$@"
501 }
502
503 c_sysprepare () {
504   kdir=$1
505   readmeta "$kdir"
506   c_sysprofile "$profile"
507 }
508
509 c_sysop () {
510   op=$1 kdir=$2; shift 1
511   c_sysprepare "$kdir"
512   c_$op "$@"
513 }
514
515 c_sysencrypt () { c_sysop encrypt "$1" /dev/null; }
516 c_sysdecrypt () { c_sysop decrypt "$1" "$2"; }
517 c_syssign () { c_sysop sign "$1" "$2"; }
518 c_sysverify () { c_sysop verify "$1" /dev/null; }
519
520 ###--------------------------------------------------------------------------
521 ### Recovery operations.
522
523 stash () {
524   recov=$1 label=$2
525   ## Stash a copy of stdin encrypted under the recovery key RECOV, with a
526   ## given LABEL.
527   checkword "recovery key label" "$recov"
528   checklabel "secret" "$label"
529
530   rdir=$KEYS/recov/$recov/current
531   if [ ! -d $rdir/store ]; then
532     echo >&2 "$quis: unknown recovery key \`$recov'"
533     exit 1
534   fi
535   case $label in */*) mkdir -m755 -p $rdir/${label%/*} ;; esac
536   (c_sysencrypt $rdir/store >$rdir/$label.new)
537   mv $rdir/$label.new $rdir/$label.recov
538 }
539
540 recover () {
541   recov=$1 label=$2
542   ## Recover a stashed secret, protected by RECOV and stored as LABEL, and
543   ## write it to stdout.
544   checkword "recovery key label" "$recov"
545   checklabel "secret" "$label"
546
547   rdir=$KEYS/recov/$recov/current
548   if [ ! -f $rdir/$label.recov ]; then
549     echo >&2 "$quis: no blob for \`$label' under recovery key \`$recov'"
550     exit 1
551   fi
552   reqsafe
553   nub=$SAFE/keys.reveal/$recov.current/nub
554   if [ ! -f $nub ]; then
555     echo >&2 "$quis: current recovery key \`$recov' not revealed"
556     exit 1;
557   fi
558   mktmp
559   c_sysdecrypt $rdir/store $nub <$rdir/$label.recov
560 }
561
562 ###--------------------------------------------------------------------------
563 ### Help text.
564
565 defhelp () {
566   read umsg
567   usage="usage: $quis${umsg+ }$umsg"
568   help=$(cat)
569   case "$KEYS_HELP" in t) help; exit ;; esac
570 }
571
572 help () { showhelp; }
573 showhelp () {
574   cat <<EOF
575 $usage
576
577 $help
578 EOF
579 }
580
581 usage_err () { echo >&2 "$usage"; exit 1; }
582
583 ###--------------------------------------------------------------------------
584 ### Subcommand handling.
585
586 version () {
587   echo "$PACKAGE version $VERSION"
588 }
589
590 cmd_help () {
591   rc=0
592   version
593   case $# in
594     0)
595       cat <<EOF
596
597 $usage
598
599 Options:
600   -h            Show this help text.
601   -v            Show the program version number.
602
603 Commands installed:
604 EOF
605       cd "$KEYSLIB"
606       for i in $prefix.*; do
607         if [ ! -x "$i" ]; then continue; fi
608         sed -n "/<<HELP/{n;s/^/ ${i#$prefix.} /;p;q;}" "$i"
609       done
610       ;;
611     *)
612       for i in "$@"; do
613         echo
614         if [ ! -x "$KEYSLIB/$prefix.$i" ]; then
615           echo >&2 "$quis: unrecognized command \`$i'"
616           rc=1
617           continue
618         elif ! KEYS_HELP=t "$KEYSLIB/$prefix.$i"; then
619           rc=1
620         fi
621       done
622       ;;
623   esac
624   return $rc
625 }
626
627 dispatch () {
628   case $# in 0) echo >&2 "$usage"; exit 1 ;; esac
629   cmd=$1; shift
630   case "$cmd" in help) cmd_help "$@"; exit ;; esac
631   if [ ! -x "$KEYSLIB/$prefix.$cmd" ]; then
632     echo >&2 "$quis: unrecognized command \`$cmd'"
633     exit 1
634   fi
635
636   unset KEYS_HELP
637   exec "$KEYSLIB/$prefix.$cmd" "$@"
638 }
639
640 ###----- That's all, folks --------------------------------------------------