3 ### Common key management functions.
5 ### (c) 2011 Mark Wooding
8 ###----- Licensing notice ---------------------------------------------------
10 ### This file is part of the distorted.org.uk key management suite.
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.
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.
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.
28 ###--------------------------------------------------------------------------
29 ### Configuration variables.
31 PACKAGE="@PACKAGE@" VERSION="@VERSION@"
34 case ":$PATH:" in *:"$bindir":*) ;; *) PATH=$bindir:$PATH ;; esac
36 if [ -f $ETC/keys.conf ]; then . $ETC/keys.conf; fi
38 case "${KEYS_DEBUG+t}" in t) set -x ;; esac
40 ###--------------------------------------------------------------------------
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
49 ###--------------------------------------------------------------------------
50 ### Utility functions.
53 ## Fail unless a safe directory is set.
55 err="$quis: (CONFIGURATION ERROR)"
58 *) echo >&2 "$err: no SAFE directory"; exit 1 ;;
60 if [ ! -d "$SAFE" ]; then
61 echo >&2 "$err: SAFE path \`$SAFE' isn't a directory"
65 [!/]* | *[][[:space:]*?]*)
66 echo >&2 "$err: SAFE path \`$SAFE' contains bad characters"
72 read perm _ user stuff
76 echo >&2 "$err: SAFE path \`$SAFE' has bad owner or permissions"
83 ## Temporary directory.
85 rmtmp () { case ${tmp+t} in t) cd /; rm -rf $tmp ;; esac; }
88 ## Make a temporary directory and store its name in `tmp'.
90 case "${tmp+t}" in t) return ;; esac
92 tmp="$SAFE/keys.tmp.$$"
98 ## Fail unless a temporary directory is set.
102 *) echo >&2 "$quis (INTERNAL): no tmp directory set"; exit 127 ;;
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.
112 *:*) kowner=${key%%:*} klabel=${key#*:} ;;
113 *) kowner=$USERV_USER klabel=$key ;;
115 checkword "key owner name" "$kowner"
116 checklabel "key" "$klabel"
117 kdir=$KEYS/store/$kowner/$klabel
118 knub=$KEYS/nub/$kowner/$klabel
121 ###--------------------------------------------------------------------------
122 ### Input validation functions.
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
135 *"$nl"*) validp=nil ;;
136 *) if ! expr >/dev/null "$thing" : "$ckpat\$"; then validp=nil; fi ;;
139 nil) echo >&2 "$quis: bad $ckwhat \`$thing'"; exit 1 ;;
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\)*\)"
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"; }
159 ###--------------------------------------------------------------------------
160 ### Key storage and properties.
164 ## Write the named system PROFILE to standard output.
166 $bindir/extract-profile $ETC/profile.d/ "$profile"
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.
177 *\=*) name=${assg%%=*} value=${assg#*=} ;;
180 case "$goodp,$name" in t,*[!0-9A-Za-z_]*=*) goodp=nil ;; esac
182 nil) echo >&2 "$quis: bad $what assignment \`$assg'"; exit 1 ;;
184 eval "$prefix$name=\$value"
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
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
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
206 echo >&2 "$quis: missing $whatprop \`$name' required"
210 eval value=\$$prefix$name
211 check "value for $whatprop \`$name'" "$pat" "$value"
220 ## Define a properties table NAME.
226 defprops g_props <<EOF
228 recovery t $R_WORDSEQ
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_'.
241 ## Parse the settings from the file.
244 case "$line" in "" | \#*) continue ;; esac
245 setprops "property" kprop_ "$line"
248 checkprops "property" kprop_ "$g_props"
250 ## Fetch the key-type handling library.
251 if [ ! -f $KEYSLIB/ktype.$kprop_type ]; then
252 echo >&2 "$quis: unknown key type \`$kprop_type'"
255 . $KEYSLIB/ktype.$kprop_type
256 checkprops "property" kprop_ "$k_props"
261 ## Read key metadata from KDIR.
263 { read profile; } <"$kdir"/meta
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.
271 if=/dev/${kprop_random-random} bs=1 count=${kprop_nubsz-512} |
272 openssl dgst -${kprop_nubhash-sha384} -binary |
277 ## Compute a hash of the key nub in stdin, and write it to stdout in hex.
278 ## The property `nubidhash' is used.
280 { echo "distorted-keys nubid"; cat -; } |
281 openssl dgst -${kprop_nubidhash-sha256}
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
295 ## If there are no more markers to substitute, then finish.
296 case "$rest" in *"%{"*"}"*) ;; *) out=$out$rest; break ;; esac
298 ## Split the template into three parts.
299 left=${rest%%\%\{*} right=${rest#*\%\{}
300 var=${right%%\}*} rest=${right#*\}}
302 *-*) default=${var#*-} var=${var%%-*} defaultp=t ;;
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 ;;
313 echo >&2 "$quis: option \`$var' unset, used in template \`$templ'"
318 ## Do the substitution.
322 ## Check the final result.
323 check "$what" "$pat" "$out"
331 ## Read property settings from a profile. The PROFILE name has the form
332 ## [USER:]LABEL. Properties are set using `setprops' with prefix `kprop_'.
337 label=${profile#:} uservp=nil
340 user=$USERV_USER label=$profile uservp=t
343 user=${profile%%:*} label=${profile#*:} uservp=t
346 checkword "profile label" "$label"
348 ## Fetch the profile settings from the user.
352 checkword "profile user" "$user"
353 userv "$user" cryptop-profile "$label" >$tmp/profile
356 $bindir/extract-profile $ETC/profile.d/ "$label" >$tmp/profile
361 readprops $tmp/profile
364 ###--------------------------------------------------------------------------
365 ### General crypto operations.
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.
375 ## Set options and check them.
376 setprops "option" kopt_ "$@"
377 checkprops "option" kopt_ "$k_genopts"
379 ## Create directory structure and start writing metadata.
381 mkdir -m755 -p "$kdir.new"
382 case "$knub" in */*) mkdir -m700 -p "${knub%/*}" ;; esac
383 cat >"$kdir.new/meta" <<EOF
388 umask=$(umask); umask 077; >"$knub.new"; umask $umask
389 k_generate "$kdir.new" "$knub.new"
390 $hook "$kdir.new" "$knub.new"
393 nubid <"$knub.new" >"$kdir.new/nubid"
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).
401 if [ -e "$kdir" ]; then mv "$kdir" "$kdir.old"; fi
402 mv "$kdir.new" "$kdir"
403 mv "$knub.new" "$knub"
407 c_encrypt () { k_encrypt "$@"; }
409 if k_decrypt "$@" >$tmp/plain; then cat $tmp/plain
413 c_sign () { k_sign "$@"; }
414 c_verify () { k_verify "$@"; }
416 ## Stub implementations.
417 notsupp () { op=$1; echo >&2 "$quis: operation \`$op' not supported"; }
419 k_encrypt () { notsupp encrypt; }
420 k_decrypt () { notsupp decrypt; }
421 k_sign () { notsupp sign; }
422 k_verify () { notsupp verify; }
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.
429 ## Find the key properties.
430 parse_keylabel "$key"
431 if [ ! -d $kdir ]; then echo >&2 "$quis: unknown key \`$key'"; exit 1; fi
433 read_profile "$profile"
435 ## Check whether we're allowed to do this thing. This is annoyingly
437 eval acl=\${kprop_acl_$op-!owner}
441 ## Remove leading whitespace.
444 [[:space:]]*) acl=${acl#?} ;;
449 ## If there's nothing left, leave.
450 case "$acl" in ?*) ;; *) break ;; esac
452 ## Split off the leading word.
454 *[[:space:]]*) word=${acl%%[[:space:]]*} acl=${acl#*[[:space:]]} ;;
455 *) word=$acl acl="" ;;
458 ## See what sense it has if it matches.
460 -*) sense=forbid rest=${word#-} ;;
461 *) sense=allow rest=$word ;;
464 ## See whether the calling user matches.
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" ;;
472 for i in $list; do case "$i" in $pat) matchp=t; break ;; esac; done
473 case $matchp in t) verdict=$sense; break ;; esac
477 forbid) echo >&2 "$quis: $op access to key \`$key' forbidden"; exit ;;
481 ###--------------------------------------------------------------------------
482 ### Crypto operations for infrastructure purposes.
486 ## Select the profile in FILE for future crypto operations.
488 unset $(set | sed -n '/^kprop_/s/=.*$//p')
490 getsysprofile "$profile" >$tmp/profile
491 readprops $tmp/profile
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.
499 c_sysprofile "$profile"
500 c_genkey "$profile" "$kdir" "$knub" : "$@"
506 c_sysprofile "$profile"
510 op=$1 kdir=$2; shift 1
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; }
520 ###--------------------------------------------------------------------------
521 ### Recovery operations.
525 ## Stash a copy of stdin encrypted under the recovery key RECOV, with a
527 checkword "recovery key label" "$recov"
528 checklabel "secret" "$label"
530 rdir=$KEYS/recov/$recov/current
531 if [ ! -d $rdir/store ]; then
532 echo >&2 "$quis: unknown recovery key \`$recov'"
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
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"
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'"
553 nub=$SAFE/keys.reveal/$recov.current/nub
554 if [ ! -f $nub ]; then
555 echo >&2 "$quis: current recovery key \`$recov' not revealed"
559 c_sysdecrypt $rdir/store $nub <$rdir/$label.recov
562 ###--------------------------------------------------------------------------
567 usage="usage: $quis${umsg+ }$umsg"
569 case "$KEYS_HELP" in t) help; exit ;; esac
572 help () { showhelp; }
581 usage_err () { echo >&2 "$usage"; exit 1; }
583 ###--------------------------------------------------------------------------
584 ### Subcommand handling.
587 echo "$PACKAGE version $VERSION"
600 -h Show this help text.
601 -v Show the program version number.
606 for i in $prefix.*; do
607 if [ ! -x "$i" ]; then continue; fi
608 sed -n "/<<HELP/{n;s/^/ ${i#$prefix.} /;p;q;}" "$i"
614 if [ ! -x "$KEYSLIB/$prefix.$i" ]; then
615 echo >&2 "$quis: unrecognized command \`$i'"
618 elif ! KEYS_HELP=t "$KEYSLIB/$prefix.$i"; then
628 case $# in 0) echo >&2 "$usage"; exit 1 ;; esac
630 case "$cmd" in help) cmd_help "$@"; exit ;; esac
631 if [ ! -x "$KEYSLIB/$prefix.$cmd" ]; then
632 echo >&2 "$quis: unrecognized command \`$cmd'"
637 exec "$KEYSLIB/$prefix.$cmd" "$@"
640 ###----- That's all, folks --------------------------------------------------