chiark / gitweb /
keyfunc.sh.in, cryptop.{genkey,recover}: Care over key ownership.
[distorted-keys] / keyfunc.sh.in
CommitLineData
53263601
MW
1### -*-sh-*-
2###
3### Common key management functions.
4###
5### (c) 2011 Mark Wooding
6###
7
8###----- Licensing notice ---------------------------------------------------
9###
599c8f75
MW
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
53263601
MW
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###
599c8f75 17### distorted-keys is distributed in the hope that it will be useful,
53263601
MW
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
599c8f75 23### along with distorted-keys; if not, write to the Free Software Foundation,
53263601
MW
24### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26quis=${0##*/}
27
28###--------------------------------------------------------------------------
29### Configuration variables.
30
e787e19c 31## Automatically configured pathnames.
53263601 32PACKAGE="@PACKAGE@" VERSION="@VERSION@"
53263601
MW
33bindir="@bindir@"
34
e787e19c 35## Read user configuration.
c47f2aba 36if [ -f $ETC/keys.conf ]; then . $ETC/keys.conf; fi
599c8f75 37
e787e19c 38## Maybe turn on debugging.
599c8f75
MW
39case "${KEYS_DEBUG+t}" in t) set -x ;; esac
40
ec208149
MW
41## Fake up caller credentials if not called via userv.
42case "${USERV_USER+t}" in
43 t) ;;
44 *) USERV_USER=${LOGNAME-${USER-$(id -un)}} USERV_UID=$(id -u) ;;
45esac
46case "${USERV_GROUP+t}" in
47 t) ;;
48 *) USERV_GROUP=$(id -Gn) USERV_GID=$(id -gn) ;;
49esac
50
53263601
MW
51###--------------------------------------------------------------------------
52### Cleanup handling.
53
54cleanups=""
c47f2aba
MW
55cleanup () { cleanups=${cleanups+$cleanups }$1; }
56runcleanups () { for i in $cleanups; do $i; done; }
57trap 'rc=$?; runcleanups; exit $rc' EXIT
58trap 'trap "" EXIT; runcleanups; exit 127' INT TERM
53263601
MW
59
60###--------------------------------------------------------------------------
61### Utility functions.
62
c47f2aba
MW
63reqsafe () {
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
53263601
MW
94## Temporary directory.
95unset tmp
c47f2aba
MW
96rmtmp () { case ${tmp+t} in t) cd /; rm -rf $tmp ;; esac; }
97cleanup rmtmp
53263601 98mktmp () {
c47f2aba 99 ## Make a temporary directory and store its name in `tmp'.
53263601 100
c47f2aba
MW
101 case "${tmp+t}" in t) return ;; esac
102 reqsafe
103 tmp="$SAFE/keys.tmp.$$"
53263601
MW
104 rm -rf "$tmp"
105 mkdir -m700 "$tmp"
53263601
MW
106}
107
c47f2aba
MW
108reqtmp () {
109 ## Fail unless a temporary directory is set.
53263601 110
c47f2aba
MW
111 case ${tmp+t} in
112 t) ;;
113 *) echo >&2 "$quis (INTERNAL): no tmp directory set"; exit 127 ;;
53263601
MW
114 esac
115}
116
c47f2aba
MW
117parse_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 ;;
53263601 125 esac
c47f2aba
MW
126 checkword "key owner name" "$kowner"
127 checklabel "key" "$klabel"
128 kdir=$KEYS/store/$kowner/$klabel
129 knub=$KEYS/nub/$kowner/$klabel
53263601
MW
130}
131
c47f2aba
MW
132###--------------------------------------------------------------------------
133### Input validation functions.
134
135nl="
136"
137check () {
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
599c8f75 145 case "$thing" in
c47f2aba
MW
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 ;;
599c8f75
MW
151 esac
152}
153
c47f2aba
MW
154## Regular expressions for validating input.
155R_IDENTCHARS="A-Za-z0-9_"
156R_WORDCHARS="-$R_IDENTCHARS!%@+="
157R_IDENT="[$R_IDENTCHARS][$R_IDENTCHARS]*"
158R_WORD="[$R_WORDCHARS][$R_WORDCHARS]*"
159R_WORDSEQ="[$R_WORDCHARS[:space:]][$R_WORDCHARS[:space:]]*"
160R_NUMERIC='\(\([1-9][0-9]*\)\{0,1\}0\{0,1\}\)'
161R_LABEL="\($R_WORD\(/$R_WORD\)*\)"
162R_LINE=".*"
163
164## Various validation functions.
165checknumber () { check "$1" "$R_NUMERIC" "$2"; }
166checkident () { check "$1" "$R_IDENT" "$2"; }
167checkword () { check "$1" "$R_WORD" "$2"; }
168checklabel () { check "$1 label" "$R_LABEL" "$2"; }
169
53263601 170###--------------------------------------------------------------------------
c47f2aba
MW
171### Key storage and properties.
172
173getsysprofile () {
174 profile=$1
175 ## Write the named system PROFILE to standard output.
176
b65e1f93 177 $bindir/extract-profile "$profile" $ETC/profile.d/
c47f2aba
MW
178}
179
180setprops () {
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}
53263601 198
c47f2aba
MW
199checkprops () {
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
53263601 203 ##
c47f2aba
MW
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
225EOF
226 done
227}
53263601 228
c47f2aba
MW
229defprops () {
230 name=$1
231 ## Define a properties table NAME.
232
233 table=$(cat)
234 eval $name=\$table
235}
236
237defprops g_props <<EOF
238type nil $R_IDENT
239recovery t $R_WORDSEQ
240random t $R_WORD
2a877b7f
MW
241nub_hash t $R_WORD
242nubid_hash t $R_WORD
243nub_random_bytes t $R_NUMERIC
c47f2aba
MW
244EOF
245
246readprops () {
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
270readmeta () {
271 kdir=$1
272 ## Read key metadata from KDIR.
273
274 { read profile; } <"$kdir"/meta
275}
276
277makenub () {
278 ## Generate a key nub in the default way, and write it to standard output.
2a877b7f
MW
279 ## The properties `random', `nub_random_bytes' and `nub_hash' are referred
280 ## to.
c47f2aba
MW
281
282 dd 2>/dev/null \
2a877b7f
MW
283 if=/dev/${kprop_random-random} bs=1 count=${kprop_nub_random_bytes-64} |
284 openssl dgst -${kprop_nub_hash-sha256} -binary |
c47f2aba
MW
285 openssl base64
286}
287
288nubid () {
289 ## Compute a hash of the key nub in stdin, and write it to stdout in hex.
2a877b7f 290 ## The property `nubid_hash' is used.
c47f2aba
MW
291
292 { echo "distorted-keys nubid"; cat -; } |
2a877b7f 293 openssl dgst -${kprop_nubid_hash-sha256}
c47f2aba
MW
294}
295
296subst () {
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
341read_profile () {
e9cf7079 342 owner=$1 profile=$2
c47f2aba 343 ## Read property settings from a profile. The PROFILE name has the form
e9cf7079
MW
344 ## [USER:]LABEL; USER defaults to OWNER. Properties are set using
345 ## `setprops' with prefix `kprop_'.
c47f2aba
MW
346
347 reqtmp
348 case "$profile" in
349 :*)
350 label=${profile#:} uservp=nil
351 ;;
53263601 352 *)
e9cf7079 353 user=$kowner label=$profile uservp=t
c47f2aba
MW
354 ;;
355 *:*)
356 user=${profile%%:*} label=${profile#*:} uservp=t
357 ;;
358 esac
359 checkword "profile label" "$label"
360
361 ## Fetch the profile settings from the user.
362 reqtmp
363 case $uservp in
364 t)
365 checkword "profile user" "$user"
366 userv "$user" cryptop-profile "$label" >$tmp/profile
367 ;;
368 nil)
b65e1f93 369 $bindir/extract-profile "$label" $ETC/profile.d/ >$tmp/profile
53263601
MW
370 ;;
371 esac
372
c47f2aba
MW
373 ## Read the file.
374 readprops $tmp/profile
53263601
MW
375}
376
c47f2aba
MW
377###--------------------------------------------------------------------------
378### General crypto operations.
379
380c_genkey () {
381 profile=$1 kdir=$2 knub=$3 hook=$4; shift 4
382 ## Generate a key, and associate it with the named PROFILE (which is
383 ## assumed already to have been read!); store the main data in KDIR, and
384 ## the nub separately in the file KNUB; run HOOK after generation, passing
385 ## it the working key directory and nub file. Remaining arguments are
386 ## options to the key type.
387
388 ## Set options and check them.
389 setprops "option" kopt_ "$@"
390 checkprops "option" kopt_ "$k_genopts"
391
392 ## Create directory structure and start writing metadata.
393 rm -rf "$kdir.new"
394 mkdir -m755 -p "$kdir.new"
395 case "$knub" in */*) mkdir -m700 -p "${knub%/*}" ;; esac
396 cat >"$kdir.new/meta" <<EOF
397$profile
398EOF
53263601 399
c47f2aba
MW
400 ## Generate the key.
401 umask=$(umask); umask 077; >"$knub.new"; umask $umask
402 k_generate "$kdir.new" "$knub.new"
403 $hook "$kdir.new" "$knub.new"
404
405 ## Hash the nub.
406 nubid <"$knub.new" >"$kdir.new/nubid"
407
408 ## Juggle everything into place. Doing this atomically is very difficult,
409 ## and requires more machinery than I can really justify here. If
410 ## something goes wrong halfway, it should always be possible to fix it,
411 ## either by backing out (if $kdir.new still exists) or pressing on
412 ## forwards (if not).
413 rm -rf "$kdir.old"
414 if [ -e "$kdir" ]; then mv "$kdir" "$kdir.old"; fi
415 mv "$kdir.new" "$kdir"
416 mv "$knub.new" "$knub"
417 rm -rf "$kdir.old"
53263601
MW
418}
419
c47f2aba
MW
420c_encrypt () { k_encrypt "$@"; }
421c_decrypt () {
422 if k_decrypt "$@" >$tmp/plain; then cat $tmp/plain
423 else return $?
424 fi
425}
426c_sign () { k_sign "$@"; }
427c_verify () { k_verify "$@"; }
428
429## Stub implementations.
430notsupp () { op=$1; echo >&2 "$quis: operation \`$op' not supported"; }
431k_info () { :; }
432k_encrypt () { notsupp encrypt; }
433k_decrypt () { notsupp decrypt; }
434k_sign () { notsupp sign; }
435k_verify () { notsupp verify; }
436
437prepare () {
438 key=$1 op=$2
439 ## Prepare for a crypto operation OP, using the KEY. This validates the
5cff41ea
MW
440 ## key label, reads the profile, and checks the access-control list. If OP
441 ## is `-' then allow the operation unconditionally.
c47f2aba
MW
442
443 ## Find the key properties.
444 parse_keylabel "$key"
445 if [ ! -d $kdir ]; then echo >&2 "$quis: unknown key \`$key'"; exit 1; fi
446 readmeta $kdir
e9cf7079 447 read_profile $kowner "$profile"
c47f2aba
MW
448
449 ## Check whether we're allowed to do this thing. This is annoyingly
450 ## fiddly.
5cff41ea 451 case $op in -) return ;; esac
c47f2aba
MW
452 eval acl=\${kprop_acl_$op-!owner}
453 verdict=forbid
454 while :; do
455
456 ## Remove leading whitespace.
457 while :; do
458 case "$acl" in
459 [[:space:]]*) acl=${acl#?} ;;
460 *) break ;;
461 esac
462 done
463
464 ## If there's nothing left, leave.
465 case "$acl" in ?*) ;; *) break ;; esac
466
467 ## Split off the leading word.
468 case "$acl" in
469 *[[:space:]]*) word=${acl%%[[:space:]]*} acl=${acl#*[[:space:]]} ;;
470 *) word=$acl acl="" ;;
471 esac
472
473 ## See what sense it has if it matches.
474 case "$word" in
475 -*) sense=forbid rest=${word#-} ;;
476 *) sense=allow rest=$word ;;
477 esac
478
479 ## See whether the calling user matches.
480 case "$rest" in
481 !owner) pat=$kowner list=$USERV_USER ;;
482 !*) echo >&2 "$quis: unknown ACL token \`$word'" ;;
483 %*) pat=${rest#%} list="$USERV_GROUP $USERV_GID" ;;
484 *) pat=$rest list="$USERV_USER $USERV_UID" ;;
485 esac
486 matchp=nil
487 for i in $list; do case "$i" in $pat) matchp=t; break ;; esac; done
488 case $matchp in t) verdict=$sense; break ;; esac
489 done
490
491 case $verdict in
68023101 492 forbid) echo >&2 "$quis: $op access to key \`$key' forbidden"; exit 1 ;;
c47f2aba 493 esac
53263601
MW
494}
495
c47f2aba
MW
496###--------------------------------------------------------------------------
497### Crypto operations for infrastructure purposes.
498
499c_sysprofile () {
500 profile=$1
501 ## Select the profile in FILE for future crypto operations.
53263601 502
c47f2aba
MW
503 unset $(set | sed -n '/^kprop_/s/=.*$//p')
504 reqtmp
505 getsysprofile "$profile" >$tmp/profile
506 readprops $tmp/profile
53263601
MW
507}
508
c47f2aba
MW
509c_gensyskey () {
510 profile=$1 kdir=$2 knub=$3; shift 3
511 ## Generate a system key using PROFILE; store the data in KDIR and the nub
512 ## in KNUB. Remaining arguments are options.
53263601 513
c47f2aba
MW
514 c_sysprofile "$profile"
515 c_genkey "$profile" "$kdir" "$knub" : "$@"
53263601
MW
516}
517
c47f2aba
MW
518c_sysprepare () {
519 kdir=$1
520 readmeta "$kdir"
521 c_sysprofile "$profile"
522}
599c8f75 523
c47f2aba
MW
524c_sysop () {
525 op=$1 kdir=$2; shift 1
526 c_sysprepare "$kdir"
527 c_$op "$@"
599c8f75
MW
528}
529
c47f2aba
MW
530c_sysencrypt () { c_sysop encrypt "$1" /dev/null; }
531c_sysdecrypt () { c_sysop decrypt "$1" "$2"; }
532c_syssign () { c_sysop sign "$1" "$2"; }
533c_sysverify () { c_sysop verify "$1" /dev/null; }
534
535###--------------------------------------------------------------------------
536### Recovery operations.
537
538stash () {
539 recov=$1 label=$2
540 ## Stash a copy of stdin encrypted under the recovery key RECOV, with a
541 ## given LABEL.
542 checkword "recovery key label" "$recov"
543 checklabel "secret" "$label"
544
545 rdir=$KEYS/recov/$recov/current
546 if [ ! -d $rdir/store ]; then
547 echo >&2 "$quis: unknown recovery key \`$recov'"
548 exit 1
549 fi
550 case $label in */*) mkdir -m755 -p $rdir/${label%/*} ;; esac
551 (c_sysencrypt $rdir/store >$rdir/$label.new)
552 mv $rdir/$label.new $rdir/$label.recov
553}
599c8f75 554
c47f2aba
MW
555recover () {
556 recov=$1 label=$2
557 ## Recover a stashed secret, protected by RECOV and stored as LABEL, and
558 ## write it to stdout.
559 checkword "recovery key label" "$recov"
560 checklabel "secret" "$label"
561
562 rdir=$KEYS/recov/$recov/current
563 if [ ! -f $rdir/$label.recov ]; then
564 echo >&2 "$quis: no blob for \`$label' under recovery key \`$recov'"
565 exit 1
566 fi
567 reqsafe
568 nub=$SAFE/keys.reveal/$recov.current/nub
569 if [ ! -f $nub ]; then
570 echo >&2 "$quis: current recovery key \`$recov' not revealed"
571 exit 1;
572 fi
573 mktmp
574 c_sysdecrypt $rdir/store $nub <$rdir/$label.recov
599c8f75
MW
575}
576
53263601
MW
577###--------------------------------------------------------------------------
578### Help text.
579
c47f2aba
MW
580defhelp () {
581 read umsg
582 usage="usage: $quis${umsg+ }$umsg"
583 help=$(cat)
584 case "$KEYS_HELP" in t) help; exit ;; esac
53263601
MW
585}
586
53263601
MW
587help () { showhelp; }
588showhelp () {
589 cat <<EOF
590$usage
591
592$help
593EOF
594}
595
c47f2aba
MW
596usage_err () { echo >&2 "$usage"; exit 1; }
597
598###--------------------------------------------------------------------------
599### Subcommand handling.
600
601version () {
602 echo "$PACKAGE version $VERSION"
603}
604
605cmd_help () {
606 rc=0
607 version
608 case $# in
609 0)
610 cat <<EOF
611
612$usage
613
614Options:
615 -h Show this help text.
616 -v Show the program version number.
617
618Commands installed:
619EOF
620 cd "$KEYSLIB"
621 for i in $prefix.*; do
622 if [ ! -x "$i" ]; then continue; fi
623 sed -n "/<<HELP/{n;s/^/ ${i#$prefix.} /;p;q;}" "$i"
624 done
625 ;;
626 *)
627 for i in "$@"; do
628 echo
629 if [ ! -x "$KEYSLIB/$prefix.$i" ]; then
630 echo >&2 "$quis: unrecognized command \`$i'"
631 rc=1
632 continue
633 elif ! KEYS_HELP=t "$KEYSLIB/$prefix.$i"; then
634 rc=1
635 fi
636 done
637 ;;
638 esac
639 return $rc
640}
641
642dispatch () {
643 case $# in 0) echo >&2 "$usage"; exit 1 ;; esac
644 cmd=$1; shift
645 case "$cmd" in help) cmd_help "$@"; exit ;; esac
646 if [ ! -x "$KEYSLIB/$prefix.$cmd" ]; then
647 echo >&2 "$quis: unrecognized command \`$cmd'"
648 exit 1
649 fi
650
651 unset KEYS_HELP
652 exec "$KEYSLIB/$prefix.$cmd" "$@"
653}
654
53263601 655###----- That's all, folks --------------------------------------------------