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