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 ## Automatically configured pathnames.
32 PACKAGE="@PACKAGE@" VERSION="@VERSION@"
35 ## Read user configuration.
36 if [ -f $ETC/keys.conf ]; then . $ETC/keys.conf; fi
38 ## Maybe turn on debugging.
39 case "${KEYS_DEBUG+t}" in t) set -x ;; esac
41 ## Fake up caller credentials if not called via userv.
42 case "${USERV_USER+t}" in
44 *) USERV_USER=${LOGNAME-${USER-$(id -un)}} USERV_UID=$(id -u) ;;
46 case "${USERV_GROUP+t}" in
48 *) USERV_GROUP=$(id -Gn) USERV_GID=$(id -gn) ;;
51 ###--------------------------------------------------------------------------
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
60 ###--------------------------------------------------------------------------
61 ### Utility functions.
64 ## Fail unless a safe directory is set.
66 err="$quis: (CONFIGURATION ERROR)"
69 *) echo >&2 "$err: no SAFE directory"; exit 1 ;;
71 if [ ! -d "$SAFE" ]; then
72 echo >&2 "$err: SAFE path \`$SAFE' isn't a directory"
76 [!/]* | *[][[:space:]*?]*)
77 echo >&2 "$err: SAFE path \`$SAFE' contains bad characters"
83 read perm _ user stuff
87 echo >&2 "$err: SAFE path \`$SAFE' has bad owner or permissions"
94 ## Temporary directory.
96 rmtmp () { case ${tmp+t} in t) cd /; rm -rf $tmp ;; esac; }
99 ## Make a temporary directory and store its name in `tmp'.
101 case "${tmp+t}" in t) return ;; esac
103 tmp="$SAFE/keys.tmp.$$"
109 ## Fail unless a temporary directory is set.
113 *) echo >&2 "$quis (INTERNAL): no tmp directory set"; exit 127 ;;
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.
123 *:*) kowner=${key%%:*} klabel=${key#*:} ;;
124 *) kowner=$USERV_USER klabel=$key ;;
126 checkword "key owner name" "$kowner"
127 checklabel "key" "$klabel"
128 kdir=$KEYS/store/$kowner/$klabel
129 knub=$KEYS/nub/$kowner/$klabel
133 user=$1 service=$2; shift 2
134 ## If the current (effective) user is not USER then reinvoke via `userv',
135 ## as the specified service, with the remaining arguments.
139 *) exec userv "$user" "$service" "$@" ;;
143 ###--------------------------------------------------------------------------
144 ### Input validation functions.
149 ckwhat=$1 ckpat=$2 thing=$3
150 ## Verify that THING matches the (anchored, basic) regular expression
151 ## CKPAT. Since matching newlines is hard to do portably, also check that
152 ## THING doesn't contain any. If the checks fail, report an error and
157 *"$nl"*) validp=nil ;;
158 *) if ! expr >/dev/null "Q$thing" : "Q$ckpat\$"; then validp=nil; fi ;;
161 nil) echo >&2 "$quis: bad $ckwhat \`$thing'"; exit 1 ;;
165 ## Regular expressions for validating input.
166 R_IDENTCHARS="A-Za-z0-9_"
168 R_WORDCHARS="-$R_IDENTCHARS$R_GOODPUNCT"
169 R_IDENT="[$R_IDENTCHARS][$R_IDENTCHARS]*"
170 R_WORD="[$R_WORDCHARS][$R_WORDCHARS]*"
171 R_ACLCHARS="][$R_IDENTCHARS$R_GOODPUNCT*?:.#"
172 R_WORDSEQ="[$R_WORDCHARS[:space:]][$R_WORDCHARS[:space:]]*"
173 R_ACL="[$R_ACLCHARS[:space:]-][$R_ACLCHARS[:space:]-]*"
174 R_NUMERIC='\(\([1-9][0-9]*\)\{0,1\}0\{0,1\}\)'
175 R_LABEL="\($R_WORD\(/$R_WORD\)*\)"
178 ## Various validation functions.
179 checknumber () { check "$1" "$R_NUMERIC" "$2"; }
180 checkident () { check "$1" "$R_IDENT" "$2"; }
181 checkword () { check "$1" "$R_WORD" "$2"; }
182 checklabel () { check "$1 label" "$R_LABEL" "$2"; }
184 ###--------------------------------------------------------------------------
185 ### Key storage and properties.
189 ## Write the named system PROFILE to standard output.
191 $bindir/extract-profile "$profile" $ETC/profile.d/
195 what=$1 prefix=$2; shift 2
196 ## Set variables based on the NAME=VALUE assignments in the arguments. The
197 ## value for property NAME is stored in the shell variable PREFIX_NAME.
202 *\=*) name=${assg%%=*} value=${assg#*=} ;;
205 case "$goodp,$name" in t,*[!0-9A-Za-z_]*=*) goodp=nil ;; esac
207 nil) echo >&2 "$quis: bad $what assignment \`$assg'"; exit 1 ;;
209 eval "$prefix$name=\$value"
214 whatprop=$1 prefix=$2; shift 2
215 ## Check that property variables are set in accordance with the remaining
216 ## TABLE arguments. Each row of TABLE has the form
220 ## A table row is satisfied if there is a variable PREFIXNAME whose value
221 ## matces the (basic) regular expression PAT, or if the variable is unset
224 for table in "$@"; do
225 case "$table" in ?*) ;; *) continue ;; esac
226 while read -r name omit pat; do
227 eval foundp=\${$prefix$name+t}
228 case "$foundp,$omit" in
231 echo >&2 "$quis: missing $whatprop \`$name' required"
235 eval value=\$$prefix$name
236 check "value for $whatprop \`$name'" "$pat" "$value"
245 ## Define a properties table NAME.
251 defprops g_props <<EOF
253 recovery t $R_WORDSEQ
257 nub_random_bytes t $R_NUMERIC
267 ## Read a profile from a file. This doesn't check the form of the
268 ## filename, so it's not suitable for unchecked input. Properties are set
269 ## using `setprops' with prefix `kprop_'.
271 ## Parse the settings from the file.
274 case "$line" in "" | \#*) continue ;; esac
275 setprops "property" kprop_ "$line"
278 checkprops "property" kprop_ "$g_props"
280 ## Fetch the key-type handling library.
281 if [ ! -f $KEYSLIB/ktype.$kprop_type ]; then
282 echo >&2 "$quis: unknown key type \`$kprop_type'"
285 . $KEYSLIB/ktype.$kprop_type
286 checkprops "property" kprop_ "$k_props"
291 ## Read key metadata from KDIR.
293 { read profile; } <"$kdir"/meta
297 ## Generate a key nub in the default way, and write it to standard output.
298 ## The properties `random', `nub_random_bytes' and `nub_hash' are referred
302 if=/dev/${kprop_random-random} bs=1 count=${kprop_nub_random_bytes-64} |
303 openssl dgst -${kprop_nub_hash-sha256} -binary |
308 ## Compute a hash of the key nub in stdin, and write it to stdout in hex.
309 ## The property `nubid_hash' is used.
311 { echo "distorted-keys nubid"; cat -; } |
312 openssl dgst -${kprop_nubid_hash-sha256}
316 what=$1 templ=$2 prefix=$3 pat=$4
317 ## Substitute option values into the template TEMPL. Each occurrence of
318 ## %{VAR} is replaced by the value of the variable PREFIXVAR. Finally, an
319 ## error is reported unless the final value matches the regular expression
326 ## If there are no more markers to substitute, then finish.
327 case "$rest" in *"%{"*"}"*) ;; *) out=$out$rest; break ;; esac
329 ## Split the template into three parts.
330 left=${rest%%\%\{*} right=${rest#*\%\{}
331 var=${right%%\}*} rest=${right#*\}}
333 *-*) default=${var#*-} var=${var%%-*} defaultp=t ;;
337 ## Find the variable value.
338 checkident "template variable name" "$var"
339 eval foundp=\${$prefix$var+t}
340 case $foundp,$defaultp in
341 t,*) eval value=\$$prefix$var ;;
342 ,t) value=$default ;;
344 echo >&2 "$quis: option \`$var' unset, used in template \`$templ'"
349 ## Do the substitution.
353 ## Check the final result.
354 check "$what" "$pat" "$out"
362 ## Read property settings from a profile. The PROFILE name has the form
363 ## [USER:]LABEL; USER defaults to OWNER. Properties are set using
364 ## `setprops' with prefix `kprop_'.
369 label=${profile#:} uservp=nil
372 user=$kowner label=$profile uservp=t
375 user=${profile%%:*} label=${profile#*:} uservp=t
378 checkword "profile label" "$label"
380 ## Fetch the profile settings from the user.
384 checkword "profile user" "$user"
385 userv "$user" cryptop-profile "$label" >$tmp/profile
388 $bindir/extract-profile "$label" $ETC/profile.d/ >$tmp/profile
393 readprops $tmp/profile
396 ###--------------------------------------------------------------------------
397 ### General crypto operations.
400 profile=$1 kdir=$2 knub=$3 hook=$4; shift 4
401 ## Generate a key, and associate it with the named PROFILE (which is
402 ## assumed already to have been read!); store the main data in KDIR, and
403 ## the nub separately in the file KNUB; run HOOK after generation, passing
404 ## it the working key directory and nub file. Remaining arguments are
405 ## options to the key type.
407 ## Set options and check them.
408 setprops "option" kopt_ "$@"
409 checkprops "option" kopt_ "$k_genopts"
411 ## Create directory structure and start writing metadata.
413 mkdir -m755 -p "$kdir.new"
414 case "$knub" in */*) mkdir -m700 -p "${knub%/*}" ;; esac
415 cat >"$kdir.new/meta" <<EOF
420 umask=$(umask); umask 077; >"$knub.new"; umask $umask
421 k_generate "$kdir.new" "$knub.new"
422 $hook "$kdir.new" "$knub.new"
425 nubid <"$knub.new" >"$kdir.new/nubid"
427 ## Juggle everything into place. Doing this atomically is very difficult,
428 ## and requires more machinery than I can really justify here. If
429 ## something goes wrong halfway, it should always be possible to fix it,
430 ## either by backing out (if $kdir.new still exists) or pressing on
431 ## forwards (if not).
433 if [ -e "$kdir" ]; then mv "$kdir" "$kdir.old"; fi
434 mv "$kdir.new" "$kdir"
435 mv "$knub.new" "$knub"
439 c_encrypt () { k_encrypt "$@"; }
441 if k_decrypt "$@" >$tmp/plain; then cat $tmp/plain
445 c_sign () { k_sign "$@"; }
446 c_verify () { k_verify "$@"; }
448 ## Stub implementations.
449 notsupp () { op=$1; echo >&2 "$quis: operation \`$op' not supported"; }
451 k_encrypt () { notsupp encrypt; }
452 k_decrypt () { notsupp decrypt; }
453 k_sign () { notsupp sign; }
454 k_verify () { notsupp verify; }
458 ## Prepare for a crypto operation OP, using the KEY. This validates the
459 ## key label, reads the profile, and checks the access-control list. If OP
460 ## is `-' then allow the operation unconditionally.
462 ## Find the key properties.
463 parse_keylabel "$key"
464 if [ ! -d $kdir ]; then echo >&2 "$quis: unknown key \`$key'"; exit 1; fi
466 read_profile $kowner "$profile"
468 ## Check whether we're allowed to do this thing. This is annoyingly
470 case $op in -) return ;; esac
471 eval acl=\${kprop_acl_$op-!owner}
475 ## Remove leading whitespace.
478 [[:space:]]*) acl=${acl#?} ;;
483 ## If there's nothing left, leave.
484 case "$acl" in ?*) ;; *) break ;; esac
486 ## Split off the leading word.
488 *[[:space:]]*) word=${acl%%[[:space:]]*} acl=${acl#*[[:space:]]} ;;
489 *) word=$acl acl="" ;;
492 ## See what sense it has if it matches.
494 -*) sense=forbid rest=${word#-} ;;
495 *) sense=allow rest=$word ;;
498 ## See whether the calling user matches.
500 !owner) pat=$kowner list=$USERV_USER ;;
501 !*) echo >&2 "$quis: unknown ACL token \`$word'" ;;
502 %*) pat=${rest#%} list="$USERV_GROUP $USERV_GID" ;;
503 *) pat=$rest list="$USERV_USER $USERV_UID" ;;
506 for i in $list; do case "$i" in $pat) matchp=t; break ;; esac; done
507 case $matchp in t) verdict=$sense; break ;; esac
511 forbid) echo >&2 "$quis: $op access to key \`$key' forbidden"; exit 1 ;;
515 ###--------------------------------------------------------------------------
516 ### Crypto operations for infrastructure purposes.
520 ## Select the profile in FILE for future crypto operations.
522 unset $(set | sed -n '/^kprop_/s/=.*$//p')
524 getsysprofile "$profile" >$tmp/profile
525 readprops $tmp/profile
529 profile=$1 kdir=$2 knub=$3; shift 3
530 ## Generate a system key using PROFILE; store the data in KDIR and the nub
531 ## in KNUB. Remaining arguments are options.
533 c_sysprofile "$profile"
534 c_genkey "$profile" "$kdir" "$knub" : "$@"
540 c_sysprofile "$profile"
544 op=$1 kdir=$2; shift 1
549 c_sysencrypt () { c_sysop encrypt "$1" /dev/null; }
550 c_sysdecrypt () { c_sysop decrypt "$1" "$2"; }
551 c_syssign () { c_sysop sign "$1" "$2"; }
552 c_sysverify () { c_sysop verify "$1" /dev/null; }
554 ###--------------------------------------------------------------------------
555 ### Recovery operations.
559 ## Stash a copy of stdin encrypted under the recovery key RECOV, with a
561 checkword "recovery key label" "$recov"
562 checklabel "secret" "$label"
564 rdir=$KEYS/recov/$recov/current
565 if [ ! -d $rdir/store ]; then
566 echo >&2 "$quis: unknown recovery key \`$recov'"
569 case $label in */*) mkdir -m755 -p $rdir/${label%/*} ;; esac
570 (c_sysencrypt $rdir/store >$rdir/$label.new)
571 mv $rdir/$label.new $rdir/$label.recov
576 ## Recover a stashed secret, protected by RECOV and stored as LABEL, and
577 ## write it to stdout.
578 checkword "recovery key label" "$recov"
579 checklabel "secret" "$label"
581 rdir=$KEYS/recov/$recov/current
582 if [ ! -f $rdir/$label.recov ]; then
583 echo >&2 "$quis: no blob for \`$label' under recovery key \`$recov'"
587 nub=$SAFE/keys.reveal/$recov.current/nub
588 if [ ! -f $nub ]; then
589 echo >&2 "$quis: current recovery key \`$recov' not revealed"
593 c_sysdecrypt $rdir/store $nub <$rdir/$label.recov
596 ###--------------------------------------------------------------------------
601 usage="usage: $quis${umsg+ }$umsg"
603 case "$KEYS_HELP" in t) help; exit ;; esac
606 help () { showhelp; }
615 usage_err () { echo >&2 "$usage"; exit 1; }
617 ###--------------------------------------------------------------------------
618 ### Subcommand handling.
621 echo "$PACKAGE version $VERSION"
634 -h Show this help text.
635 -v Show the program version number.
640 for i in $prefix.*; do
641 if [ ! -x "$i" ]; then continue; fi
642 sed -n "/<<HELP/{n;s/^/ ${i#$prefix.} /;p;q;}" "$i"
648 if [ ! -x "$KEYSLIB/$prefix.$i" ]; then
649 echo >&2 "$quis: unrecognized command \`$i'"
652 elif ! KEYS_HELP=t "$KEYSLIB/$prefix.$i"; then
662 case $# in 0) echo >&2 "$usage"; exit 1 ;; esac
664 case "$cmd" in help) cmd_help "$@"; exit ;; esac
665 if [ ! -x "$KEYSLIB/$prefix.$cmd" ]; then
666 echo >&2 "$quis: unrecognized command \`$cmd'"
671 exec "$KEYSLIB/$prefix.$cmd" "$@"
674 ###----- That's all, folks --------------------------------------------------