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