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