Tweak key publication command.
[monkeysphere.git] / src / monkeysphere-server
1 #!/bin/bash
2
3 # monkeysphere-server: MonkeySphere server admin tool
4 #
5 # The monkeysphere scripts are written by:
6 # Jameson Rollins <jrollins@fifthhorseman.net>
7 #
8 # They are Copyright 2008, and are all released under the GPL, version 3
9 # or later.
10
11 ########################################################################
12 PGRM=$(basename $0)
13
14 SHARE=${MONKEYSPHERE_SHARE:="/usr/share/monkeysphere"}
15 export SHARE
16 . "${SHARE}/common" || exit 1
17
18 VARLIB="/var/lib/monkeysphere"
19 export VARLIB
20
21 # date in UTF format if needed
22 DATE=$(date -u '+%FT%T')
23
24 # unset some environment variables that could screw things up
25 unset GREP_OPTIONS
26
27 # default return code
28 RETURN=0
29
30 ########################################################################
31 # FUNCTIONS
32 ########################################################################
33
34 usage() {
35 cat <<EOF
36 usage: $PGRM <subcommand> [options] [args]
37 MonkeySphere server admin tool.
38
39 subcommands:
40   update-users (u) [USER]...            update user authorized_keys files
41
42   gen-key (g) [HOSTNAME]                generate gpg key for the server
43     -l|--length BITS                      key length in bits (2048)
44     -e|--expire EXPIRE                    date to expire
45     -r|--revoker FINGERPRINT              add a revoker
46   show-fingerprint (f)                  show server's host key fingerprint
47   publish-key (p)                       publish server's host key to keyserver
48
49   add-identity-certifier (a) KEYID      import and tsign a certification key
50     -n|--domain DOMAIN                    domain of certifier ()
51     -t|--trust TRUST                      trust level of certifier (2)
52     -d|--depth DEPTH                      trust depth for certifier (1)
53   remove-identity-certifier (r) KEYID   remove a certification key
54   list-identity-certifiers (l)          list certification keys
55
56   gpg-authentication-cmd                execute a gpg command to the
57                                         authentication keyring as the
58                                         monkeysphere user
59
60   help (h,?)                            this help
61
62 EOF
63 }
64
65 su_monkeysphere_user() {
66     su --preserve-environment "$MONKEYSPHERE_USER" -- -c "$@"
67 }
68
69 # function to interact with the host gnupg keyring
70 gpg_host() {
71     local returnCode
72
73     GNUPGHOME="$GNUPGHOME_HOST"
74     export GNUPGHOME
75
76     # NOTE: we supress this warning because we need the monkeysphere
77     # user to be able to read the host pubring.  we realize this might
78     # be problematic, but it's the simplest solution, without too much
79     # loss of security.
80     gpg --no-permission-warning "$@"
81     returnCode="$?"
82
83     # always reset the permissions on the host pubring so that the
84     # monkeysphere user can read the trust signatures
85     chgrp "$MONKEYSPHERE_USER" "${GNUPGHOME_HOST}/pubring.gpg"
86     chmod g+r "${GNUPGHOME_HOST}/pubring.gpg"
87     
88     return "$returnCode"
89 }
90
91 # function to interact with the authentication gnupg keyring
92 # FIXME: this function requires basically accepts only a single
93 # argument because of problems with quote expansion.  this needs to be
94 # fixed/improved.
95 gpg_authentication() {
96     GNUPGHOME="$GNUPGHOME_AUTHENTICATION"
97     export GNUPGHOME
98
99     su_monkeysphere_user "gpg $@"
100 }
101
102 # update authorized_keys for users
103 update_users() {
104     if [ "$1" ] ; then
105         # get users from command line
106         unames="$@"
107     else
108         # or just look at all users if none specified
109         unames=$(getent passwd | cut -d: -f1)
110     fi
111
112     # set mode
113     MODE="authorized_keys"
114
115     # set gnupg home
116     GNUPGHOME="$GNUPGHOME_AUTHENTICATION"
117
118     # check to see if the gpg trust database has been initialized
119     if [ ! -s "${GNUPGHOME}/trustdb.gpg" ] ; then
120         failure "GNUPG trust database uninitialized.  Please see MONKEYSPHERE-SERVER(8)."
121     fi
122
123     # make sure the authorized_keys directory exists
124     mkdir -p "${VARLIB}/authorized_keys"
125
126     # loop over users
127     for uname in $unames ; do
128         # check all specified users exist
129         if ! getent passwd "$uname" >/dev/null ; then
130             log "----- unknown user '$uname' -----"
131             continue
132         fi
133
134         # set authorized_user_ids and raw authorized_keys variables,
135         # translating ssh-style path variables
136         authorizedUserIDs=$(translate_ssh_variables "$uname" "$AUTHORIZED_USER_IDS")
137         rawAuthorizedKeys=$(translate_ssh_variables "$uname" "$RAW_AUTHORIZED_KEYS")
138
139         # if neither is found, skip user
140         if [ ! -s "$authorizedUserIDs" ] ; then
141             if [ "$rawAuthorizedKeys" = '-' -o ! -s "$rawAuthorizedKeys" ] ; then
142                 continue
143             fi
144         fi
145
146         log "----- user: $uname -----"
147
148         if ! check_key_file_permissions "$uname" "$AUTHORIZED_USER_IDS" ; then
149             log "Improper permissions on authorized_user_ids file."
150             continue
151         fi
152
153         if ! check_key_file_permissions "$uname" "$RAW_AUTHORIZED_KEYS" ; then
154             log "Improper permissions on authorized_keys file."
155             continue
156         fi
157
158         # make temporary directory
159         TMPDIR=$(mktemp -d)
160
161         # trap to delete temporary directory on exit
162         trap "rm -rf $TMPDIR" EXIT
163
164         # create temporary authorized_user_ids file
165         TMP_AUTHORIZED_USER_IDS="${TMPDIR}/authorized_user_ids"
166         touch "$TMP_AUTHORIZED_USER_IDS"
167
168         # create temporary authorized_keys file
169         AUTHORIZED_KEYS="${TMPDIR}/authorized_keys"
170         touch "$AUTHORIZED_KEYS"
171
172         # set restrictive permissions on the temporary files
173         # FIXME: is there a better way to do this?
174         chmod 0700 "$TMPDIR"
175         chmod 0600 "$AUTHORIZED_KEYS"
176         chmod 0600 "$TMP_AUTHORIZED_USER_IDS"
177         chown -R "$MONKEYSPHERE_USER" "$TMPDIR"
178
179         # if the authorized_user_ids file exists...
180         if [ -s "$authorizedUserIDs" ] ; then
181             # copy user authorized_user_ids file to temporary
182             # location
183             cat "$authorizedUserIDs" > "$TMP_AUTHORIZED_USER_IDS"
184
185             # export needed variables
186             export AUTHORIZED_KEYS
187             export TMP_AUTHORIZED_USER_IDS
188
189             # process authorized_user_ids file, as monkeysphere
190             # user
191             su_monkeysphere_user \
192                 ". ${SHARE}/common; process_authorized_user_ids $TMP_AUTHORIZED_USER_IDS"
193             RETURN="$?"
194         fi
195
196         # add user-controlled authorized_keys file path if specified
197         if [ "$rawAuthorizedKeys" != '-' -a -s "$rawAuthorizedKeys" ] ; then
198             log -n "adding raw authorized_keys file... "
199             cat "$rawAuthorizedKeys" >> "$AUTHORIZED_KEYS"
200             loge "done."
201         fi
202
203         # openssh appears to check the contents of the
204         # authorized_keys file as the user in question, so the
205         # file must be readable by that user at least.
206         # FIXME: is there a better way to do this?
207         chown root "$AUTHORIZED_KEYS"
208         chgrp $(getent passwd "$uname" | cut -f4 -d:) "$AUTHORIZED_KEYS"
209         chmod g+r "$AUTHORIZED_KEYS"
210
211         # if the resulting authorized_keys file is not empty, move
212         # it into place
213         mv -f "$AUTHORIZED_KEYS" "${VARLIB}/authorized_keys/${uname}"
214
215         # destroy temporary directory
216         rm -rf "$TMPDIR"
217     done
218 }
219
220 # generate server gpg key
221 gen_key() {
222     local keyType
223     local keyLength
224     local keyUsage
225     local keyExpire
226     local revoker
227     local hostName
228     local userID
229     local keyParameters
230     local fingerprint
231
232     # set default key parameter values
233     keyType="RSA"
234     keyLength="2048"
235     keyUsage="auth"
236     keyExpire=
237     revoker=
238
239     # get options
240     TEMP=$(getopt -o l:e:r: -l length:,expire:,revoker: -n "$PGRM" -- "$@")
241
242     if [ $? != 0 ] ; then
243         exit 1
244     fi
245
246     # Note the quotes around `$TEMP': they are essential!
247     eval set -- "$TEMP"
248
249     while true ; do
250         case "$1" in
251             -l|--length)
252                 keyLength="$2"
253                 shift 2
254                 ;;
255             -e|--expire)
256                 keyExpire="$2"
257                 shift 2
258                 ;;
259             -r|--revoker)
260                 revoker="$2"
261                 shift 2
262                 ;;
263             --)
264                 shift
265                 ;;
266             *)
267                 break
268                 ;;
269         esac
270     done
271
272     hostName=${1:-$(hostname --fqdn)}
273     userID="ssh://${hostName}"
274
275     # check for presense of key with user ID
276     if gpg_host --list-key ="$userID" > /dev/null 2>&1 ; then
277         failure "Key for '$userID' already exists"
278     fi
279
280     # prompt about key expiration if not specified
281     if [ -z "$keyExpire" ] ; then
282         cat <<EOF
283 Please specify how long the key should be valid.
284          0 = key does not expire
285       <n>  = key expires in n days
286       <n>w = key expires in n weeks
287       <n>m = key expires in n months
288       <n>y = key expires in n years
289 EOF
290         while [ -z "$keyExpire" ] ; do
291             read -p "Key is valid for? (0) " keyExpire
292             if ! test_gpg_expire ${keyExpire:=0} ; then
293                 echo "invalid value"
294                 unset keyExpire
295             fi
296         done
297     elif ! test_gpg_expire "$keyExpire" ; then
298         failure "invalid key expiration value '$keyExpire'."
299     fi
300
301     # set key parameters
302     keyParameters=$(cat <<EOF
303 Key-Type: $keyType
304 Key-Length: $keyLength
305 Key-Usage: $keyUsage
306 Name-Real: $userID
307 Expire-Date: $keyExpire
308 EOF
309 )
310
311     # add the revoker field if specified
312     # FIXME: the "1:" below assumes that $REVOKER's key is an RSA key.
313     # FIXME: key is marked "sensitive"?  is this appropriate?
314     if [ "$revoker" ] ; then
315         keyParameters="${keyParameters}"$(cat <<EOF
316 Revoker: 1:$revoker sensitive
317 EOF
318 )
319     fi
320
321     echo "The following key parameters will be used for the host private key:"
322     echo "$keyParameters"
323
324     read -p "Generate key? (Y/n) " OK; OK=${OK:=Y}
325     if [ ${OK/y/Y} != 'Y' ] ; then
326         failure "aborting."
327     fi
328
329     # add commit command
330     keyParameters="${keyParameters}"$(cat <<EOF
331
332 %commit
333 %echo done
334 EOF
335 )
336
337     log "generating server key..."
338     echo "$keyParameters" | gpg_host --batch --gen-key
339
340     # output the server fingerprint
341     fingerprint_server_key "=${userID}"
342
343     # find the key fingerprint of the server primary key
344     fingerprint=$(gpg_host --list-key --with-colons --with-fingerprint "=${userID}" | \
345         grep '^fpr:' | head -1 | cut -d: -f10)
346
347     # translate the private key to ssh format, and export to a file
348     # for sshs usage.
349     # NOTE: assumes that the primary key is the proper key to use
350     (umask 077 && \
351         gpg_host --export-secret-key "$fingerprint" | \
352         openpgp2ssh "$fingerprint" > "${VARLIB}/ssh_host_rsa_key")
353     log "Private SSH host key output to file: ${VARLIB}/ssh_host_rsa_key"
354 }
355
356 # gpg output key fingerprint
357 fingerprint_server_key() {
358     gpg_host --fingerprint --list-secret-keys
359 }
360
361 # publish server key to keyserver
362 publish_server_key() {
363     read -p "Really publish key to $KEYSERVER? (y/N) " OK; OK=${OK:=N}
364     if [ ${OK/y/Y} != 'Y' ] ; then
365         failure "aborting."
366     fi
367
368     # publish host key
369     # FIXME: need to figure out better way to identify host key
370     # dummy command so as not to publish fakes keys during testing
371     # eventually:
372     #gpg_authentication "--keyserver $KEYSERVER --send-keys $(hostname -f)"
373     echo "NOT PUBLISHED (to avoid permanent publication errors during monkeysphere development)."
374     echo "The following command should publish the key:"
375     echo "monkeysphere-server gpg-authentication-cmd '--keyserver $KEYSERVER --send-keys $(hostname -f)'"
376     exit 255
377 }
378
379 # retrieve key from web of trust, import it into the host keyring, and
380 # ltsign the key in the host keyring so that it may certify other keys
381 add_certifier() {
382     local domain
383     local trust
384     local depth
385     local keyID
386     local fingerprint
387     local ltsignCommand
388
389     # set default values for trust depth and domain
390     domain=
391     trust=2
392     depth=1
393
394     # get options
395     TEMP=$(getopt -o n:t:d: -l domain:,trust:,depth: -n "$PGRM" -- "$@")
396
397     if [ $? != 0 ] ; then
398         exit 1
399     fi
400
401     # Note the quotes around `$TEMP': they are essential!
402     eval set -- "$TEMP"
403
404     while true ; do
405         case "$1" in
406             -n|--domain)
407                 domain="$2"
408                 shift 2
409                 ;;
410             -t|--trust)
411                 trust="$2"
412                 shift 2
413                 ;;
414             -d|--depth)
415                 depth="$2"
416                 shift 2
417                 ;;
418             --)
419                 shift
420                 ;;
421             *)
422                 break
423                 ;;
424         esac
425     done
426
427     keyID="$1"
428     export keyID
429
430     # export host ownertrust to authentication keyring
431     gpg_host --export-ownertrust | gpg_authentication "--import-ownertrust"
432
433     # get the key from the key server
434     gpg_authentication "--keyserver $KEYSERVER --recv-key '$keyID'"
435
436     # get the full fingerprint of a key ID
437     fingerprint=$(gpg_authentication "--list-key --with-colons --with-fingerprint $keyID" | \
438         grep '^fpr:' | grep "$keyID" | cut -d: -f10)
439
440     echo "key found:"
441     gpg_authentication "--fingerprint $fingerprint"
442
443     read -p "Are you sure you want to add this key as a certifier of users on this system? (y/N) " OK; OK=${OK:-N}
444     if [ "${OK/y/Y}" != 'Y' ] ; then
445         failure "aborting."
446     fi
447
448     # export the key to the host keyring
449     gpg_authentication "--export $keyID" | gpg_host --import
450
451     # ltsign command
452     # NOTE: *all* user IDs will be ltsigned
453     ltsignCommand=$(cat <<EOF
454 ltsign
455 y
456 $trust
457 $depth
458 $domain
459 y
460 save
461 EOF
462 )
463
464     # ltsign the key
465     echo "$ltsignCommand" | gpg_host --quiet --command-fd 0 --edit-key "$fingerprint"
466
467     # update the trustdb for the authentication keyring
468     gpg_authentication "--check-trustdb"
469 }
470
471 # delete a certifiers key from the host keyring
472 remove_certifier() {
473     local keyID
474     local fingerprint
475
476     keyID="$1"
477
478     # delete the requested key (with prompting)
479     gpg_host --delete-key "$keyID"
480
481     # update the trustdb for the authentication keyring
482     gpg_authentication "--check-trustdb"
483 }
484
485 # list the host certifiers
486 list_certifiers() {
487     gpg_host --list-keys
488 }
489
490 # issue command to gpg-authentication keyring
491 gpg_authentication_cmd() {
492     gpg_authentication "$@"
493 }
494
495 ########################################################################
496 # MAIN
497 ########################################################################
498
499 # unset variables that should be defined only in config file
500 unset KEYSERVER
501 unset AUTHORIZED_USER_IDS
502 unset RAW_AUTHORIZED_KEYS
503 unset MONKEYSPHERE_USER
504
505 # load configuration file
506 [ -e ${MONKEYSPHERE_SERVER_CONFIG:="${ETC}/monkeysphere-server.conf"} ] && . "$MONKEYSPHERE_SERVER_CONFIG"
507
508 # set empty config variable with ones from the environment, or with
509 # defaults
510 KEYSERVER=${MONKEYSPHERE_KEYSERVER:=${KEYSERVER:="subkeys.pgp.net"}}
511 AUTHORIZED_USER_IDS=${MONKEYSPHERE_AUTHORIZED_USER_IDS:=${AUTHORIZED_USER_IDS:="%h/.config/monkeysphere/authorized_user_ids"}}
512 RAW_AUTHORIZED_KEYS=${MONKEYSPHERE_RAW_AUTHORIZED_KEYS:=${RAW_AUTHORIZED_KEYS:="%h/.ssh/authorized_keys"}}
513 MONKEYSPHERE_USER=${MONKEYSPHERE_MONKEYSPHERE_USER:=${MONKEYSPHERE_USER:="monkeysphere"}}
514
515 # other variables
516 CHECK_KEYSERVER=${MONKEYSPHERE_CHECK_KEYSERVER:="true"}
517 REQUIRED_USER_KEY_CAPABILITY=${MONKEYSPHERE_REQUIRED_USER_KEY_CAPABILITY:="a"}
518 GNUPGHOME_HOST=${MONKEYSPHERE_GNUPGHOME_HOST:="${VARLIB}/gnupg-host"}
519 GNUPGHOME_AUTHENTICATION=${MONKEYSPHERE_GNUPGHOME_AUTHENTICATION:="${VARLIB}/gnupg-authentication"}
520
521 # export variables needed in su invocation
522 export DATE
523 export MODE
524 export MONKEYSPHERE_USER
525 export KEYSERVER
526 export CHECK_KEYSERVER
527 export REQUIRED_USER_KEY_CAPABILITY
528 export GNUPGHOME_HOST
529 export GNUPGHOME_AUTHENTICATION
530 export GNUPGHOME
531
532 # get subcommand
533 COMMAND="$1"
534 [ "$COMMAND" ] || failure "Type '$PGRM help' for usage."
535 shift
536
537 case $COMMAND in
538     'update-users'|'update-user'|'u')
539         update_users "$@"
540         ;;
541
542     'gen-key'|'g')
543         gen_key "$@"
544         ;;
545
546     'show-fingerprint'|'f')
547         fingerprint_server_key
548         ;;
549
550     'publish-key'|'p')
551         publish_server_key
552         ;;
553
554     'add-identity-certifier'|'add-certifier'|'a')
555         if [ -z "$1" ] ; then
556             failure "You must specify a key ID."
557         fi
558         add_certifier "$1"
559         ;;
560
561     'remove-identity-certifier'|'remove-certifier'|'r')
562         if [ -z "$1" ] ; then
563             failure "You must specify a key ID."
564         fi
565         remove_certifier "$1"
566         ;;
567
568     'list-identity-certifiers'|'list-certifiers'|'list-certifier'|'l')
569         list_certifiers "$@"
570         ;;
571
572     'gpg-authentication-cmd')
573         gpg_authentication_cmd "$@"
574         ;;
575
576     'help'|'h'|'?')
577         usage
578         ;;
579
580     *)
581         failure "Unknown command: '$COMMAND'
582 Type '$PGRM help' for usage."
583         ;;
584 esac
585
586 exit "$RETURN"