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