special gpg functions for host/authentication.
[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 PGRM_PATH=$(dirname $0)
14
15 SHARE=${SHARE:-"/usr/share/monkeysphere"}
16 export SHARE
17 . "${SHARE}/common"
18
19 VARLIB="/var/lib/monkeysphere"
20 export VARLIB
21
22 # date in UTF format if needed
23 DATE=$(date -u '+%FT%T')
24
25 # unset some environment variables that could screw things up
26 GREP_OPTIONS=
27
28 # default return code
29 ERR=0
30
31 ########################################################################
32 # FUNCTIONS
33 ########################################################################
34
35 usage() {
36 cat <<EOF
37 usage: $PGRM <subcommand> [args]
38 MonkeySphere server admin tool.
39
40 subcommands:
41   update-users (u) [USER]...            update users authorized_keys files
42   gen-key (g) [HOSTNAME]                generate gpg key for the server
43   show-fingerprint (f)                  show server's host key fingerprint
44   publish-key (p)                       publish server's host key to keyserver
45   trust-key (t) KEYID [LEVEL]           set owner trust for keyid
46   help (h,?)                            this help
47
48 EOF
49 }
50
51 gpg_host() {
52     GNUPGHOME="$GNUPGHOME_HOST"
53     export GNUPGHOME
54
55     gpg "$@"
56 }
57
58 gpg_authentication() {
59     GNUPGHOME="$GNUPGHOME_AUTHENTICATION"
60     export GNUPGHOME
61
62     su --preserve-environment "$MONKEYSPHERE_USER" -c -- "gpg $@"
63 }
64
65 # generate server gpg key
66 gen_key() {
67     local hostName
68     local userID
69     local keyParameters
70     local fingerprint
71
72     hostName=${1:-$(hostname --fqdn)}
73
74     SERVICE=${SERVICE:-"ssh"}
75     userID="${SERVICE}://${hostName}"
76
77     if gpg_host --list-key ="$userID" > /dev/null 2>&1 ; then
78         failure "Key for '$userID' already exists"
79     fi
80
81     # set key defaults
82     KEY_TYPE=${KEY_TYPE:-"RSA"}
83     KEY_LENGTH=${KEY_LENGTH:-"2048"}
84     KEY_USAGE=${KEY_USAGE:-"auth"}
85     KEY_EXPIRE=${KEY_EXPIRE:-"0"}
86     cat <<EOF
87 Please specify how long the key should be valid.
88          0 = key does not expire
89       <n>  = key expires in n days
90       <n>w = key expires in n weeks
91       <n>m = key expires in n months
92       <n>y = key expires in n years
93 EOF
94     read -p "Key is valid for? ($KEY_EXPIRE) " KEY_EXPIRE; KEY_EXPIRE=${KEY_EXPIRE:-"0"}
95
96     # set key parameters
97     keyParameters=$(cat <<EOF
98 Key-Type: $KEY_TYPE
99 Key-Length: $KEY_LENGTH
100 Key-Usage: $KEY_USAGE
101 Name-Real: $userID
102 Expire-Date: $KEY_EXPIRE
103 EOF
104 )
105
106     # add the revoker field if requested
107     # FIXME: the "1:" below assumes that $REVOKER's key is an RSA key.  why?
108     # FIXME: why is this marked "sensitive"?  how will this signature ever
109     # be transmitted to the expected revoker?
110     if [ "$REVOKER" ] ; then
111         keyParameters="${keyParameters}"$(cat <<EOF
112
113 Revoker: 1:$REVOKER sensitive
114 EOF
115 )
116     fi
117
118     echo "The following key parameters will be used:"
119     echo "$keyParameters"
120
121     read -p "Generate key? [Y|n]: " OK; OK=${OK:=Y}
122     if [ ${OK/y/Y} != 'Y' ] ; then
123         failure "aborting."
124     fi
125
126     # add commit command
127     keyParameters="${keyParameters}"$(cat <<EOF
128
129 %commit
130 %echo done
131 EOF
132 )
133
134     log "generating server key..."
135     echo "$keyParameters" | gpg_host --batch --gen-key
136
137     # output the server fingerprint
138     fingerprint_server_key "=${userID}"
139
140     # find the key fingerprint of the server primary key
141     fingerprint=$(gpg_host --list-key --with-colons --with-fingerprint "=${userID}" | \
142         grep '^fpr:' | head -1 | cut -d: -f10)
143
144     # export the host key to the authentication keyring
145     gpg_host --export "$fingerprint" | gpg_authentication --import
146
147     # set host key owner trust to ultimate in authentication keyring
148     echo "${fingerprint}:6:" | \
149         gpg_authentication "--import-ownertrust"
150
151     # write the key to the file
152     # NOTE: assumes that the primary key is the proper key to use
153     GNUPGHOME="$GNUPGHOME_HOST"
154     (umask 077 && gpgsecret2ssh "$fingerprint" > "${VARLIB}/ssh_host_rsa_key")
155     log "Private SSH host key output to file: ${VARLIB}/ssh_host_rsa_key"
156 }
157
158 # gpg output key fingerprint
159 fingerprint_server_key() {
160     local ID
161
162     if [ "$1" ] ; then
163         ID="$1"
164     else
165         ID="=ssh://$(hostname --fqdn)"
166     fi
167
168     gpg --fingerprint --list-secret-keys "$ID"
169 }
170
171 # publish server key to keyserver
172 publish_server_key() {
173     read -p "really publish key to $KEYSERVER? [y|N]: " OK; OK=${OK:=N}
174     if [ ${OK/y/Y} != 'Y' ] ; then
175         failure "aborting."
176     fi
177
178     # publish host key
179     # FIXME: need to figure out better way to identify host key
180     # dummy command so as not to publish fakes keys during testing
181     # eventually:
182     #gpg --keyserver "$KEYSERVER" --send-keys $(hostname -f)
183     failure "NOT PUBLISHED (to avoid permanent publication errors during monkeysphere development).
184 To publish manually, do: gpg --keyserver $KEYSERVER --send-keys $(hostname -f)"
185 }
186
187 # retrieve key from web of trust, and set owner trust to "full"
188 # if key is found.
189 trust_key() {
190     local keyID
191     local trustLevel
192
193     keyID="$1"
194     trustLevel="$2"
195
196     if [ -z "$keyID" ] ; then
197         failure "You must specify key to trust."
198     fi
199
200     export keyID
201
202     # get the key from the key server
203     if ! su_monkeysphere_user "gpg --keyserver $KEYSERVER --recv-key $keyID" ; then
204         failure "Could not retrieve key '$keyID'."
205     fi
206
207     # move the key from the authentication keyring to the host keyring
208     gpg_authentication --export "$keyID" | gpg_host --import
209
210     # get key fingerprint
211     GNUPGHOME="$GNUPGHOME_HOST"
212     fingerprint=$(get_key_fingerprint "$keyID")
213
214     echo "key found:"
215     gpg_host --fingerprint "$fingerprint"
216
217     while [ -z "$trustLevel" ] ; do
218         cat <<EOF
219 Please decide how far you trust this user to correctly verify other users' keys
220 (by looking at passports, checking fingerprints from different sources, etc.)
221
222   1 = I don't know or won't say
223   2 = I do NOT trust
224   3 = I trust marginally
225   4 = I trust fully
226   5 = I trust ultimately
227
228 EOF
229         read -p "Your decision? " trustLevel
230         if echo "$trustLevel" | grep -v "[1-5]" ; then
231             echo "Unknown trust level '$trustLevel'."
232             unset trustLevel
233         elif [ "$trustLevel" = 'q' ] ; then
234             failure "Aborting."
235         fi
236     done
237
238     # attach a "non-exportable" signature to the key
239     # this is required for the key to have any validity at all
240     # the 'y's on stdin indicates "yes, i really want to sign"
241     echo -e 'y\ny' | \
242         gpg_host --quiet --lsign-key --command-fd 0 "$fingerprint"
243
244     # copy the host keyring into the authentication keyring
245     mv "$GNUPGHOME_AUTHENTICATION"/pubring.gpg{,.old}
246     cp "$GNUPGHOME_HOST"/pubring.gpg "$GNUPGHOME_AUTHENTICATION"/pubring.gpg
247     chown "$MONKEYSPHERE_USER" "$GNUPGHOME_AUTHENTICATION"/pubring.gpg
248     gpg_authentication --import "$GNUPGHOME_AUTHENTICATION"/pubring.gpg.old
249
250     # index trustLevel by one to difference between level in ui and level
251     # internally
252     trustLevel=$((trustLevel+1))
253
254     # import new owner trust level for key
255     echo "${fingerprint}:${trustLevel}:" | \
256         gpg_authentication --import-ownertrust
257
258     if [ $? = 0 ] ; then
259         log "Owner trust updated."
260     else
261         failure "There was a problem changing owner trust."
262     fi
263 }
264
265 ########################################################################
266 # MAIN
267 ########################################################################
268
269 COMMAND="$1"
270 [ "$COMMAND" ] || failure "Type '$PGRM help' for usage."
271 shift
272
273 # set ms home directory
274 MS_HOME=${MS_HOME:-"$ETC"}
275
276 # load configuration file
277 MS_CONF=${MS_CONF:-"$MS_HOME"/monkeysphere-server.conf}
278 [ -e "$MS_CONF" ] && . "$MS_CONF"
279
280 # set empty config variable with defaults
281 MONKEYSPHERE_USER=${MONKEYSPHERE_USER:-"monkeysphere"}
282 KEYSERVER=${KEYSERVER:-"subkeys.pgp.net"}
283 CHECK_KEYSERVER=${CHECK_KEYSERVER:="true"}
284 AUTHORIZED_USER_IDS=${AUTHORIZED_USER_IDS:-"%h/.config/monkeysphere/authorized_user_ids"}
285 RAW_AUTHORIZED_KEYS=${RAW_AUTHORIZED_KEYS:-"%h/.ssh/authorized_keys"}
286
287 # other variables
288 REQUIRED_USER_KEY_CAPABILITY=${REQUIRED_USER_KEY_CAPABILITY:-"a"}
289 GNUPGHOME_HOST=${GNUPGHOME_HOST:-"${VARLIB}/gnupg-host"}
290 GNUPGHOME_AUTHENTICATION=${GNUPGHOME_AUTHENTICATION:-"${VARLIB}/gnupg-authentication"}
291
292 # export variables
293 export MODE
294 export MONKEYSPHERE_USER
295 export KEYSERVER
296 export CHECK_KEYSERVER
297 export REQUIRED_USER_KEY_CAPABILITY
298 export GNUPGHOME_HOST
299 export GNUPGHOME_AUTHENTICATION
300 export GNUPGHOME
301
302 case $COMMAND in
303     'update-users'|'update-user'|'u')
304         if [ "$1" ] ; then
305             # get users from command line
306             unames="$@"
307         else
308             # or just look at all users if none specified
309             unames=$(getent passwd | cut -d: -f1)
310         fi
311
312         # set mode
313         MODE="authorized_keys"
314
315         # set gnupg home
316         GNUPGHOME="$GNUPGHOME_AUTHENTICATION"
317
318         # check to see if the gpg trust database has been initialized
319         if [ ! -s "${GNUPGHOME}/trustdb.gpg" ] ; then
320             failure "GNUPG trust database uninitialized.  Please see MONKEYSPHERE-SERVER(8)."
321         fi
322
323         # make sure the authorized_keys directory exists
324         mkdir -p "${VARLIB}/authorized_keys"
325
326         # loop over users
327         for uname in $unames ; do
328             # check all specified users exist
329             if ! getent passwd "$uname" >/dev/null ; then
330                 error "----- unknown user '$uname' -----"
331                 continue
332             fi
333
334             # set authorized_user_ids and raw authorized_keys variables,
335             # translating ssh-style path variables
336             authorizedUserIDs=$(translate_ssh_variables "$uname" "$AUTHORIZED_USER_IDS")
337             rawAuthorizedKeys=$(translate_ssh_variables "$uname" "$RAW_AUTHORIZED_KEYS")
338
339             # if neither is found, skip user
340             if [ ! -s "$authorizedUserIDs" ] ; then
341                 if [ "$rawAuthorizedKeys" = '-' -o ! -s "$rawAuthorizedKeys" ] ; then
342                     continue
343                 fi
344             fi
345
346             log "----- user: $uname -----"
347
348             # make temporary directory
349             TMPDIR=$(mktemp -d)
350
351             # trap to delete temporary directory on exit
352             trap "rm -rf $TMPDIR" EXIT
353
354             # create temporary authorized_user_ids file
355             TMP_AUTHORIZED_USER_IDS="${TMPDIR}/authorized_user_ids"
356             touch "$TMP_AUTHORIZED_USER_IDS"
357
358             # create temporary authorized_keys file
359             AUTHORIZED_KEYS="${TMPDIR}/authorized_keys"
360             touch "$AUTHORIZED_KEYS"
361
362             # set restrictive permissions on the temporary files
363             # FIXME: is there a better way to do this?
364             chmod 0700 "$TMPDIR"
365             chmod 0600 "$AUTHORIZED_KEYS"
366             chmod 0600 "$TMP_AUTHORIZED_USER_IDS"
367             chown -R "$MONKEYSPHERE_USER" "$TMPDIR"
368
369             # if the authorized_user_ids file exists...
370             if [ -s "$authorizedUserIDs" ] ; then
371                 # copy user authorized_user_ids file to temporary
372                 # location
373                 cat "$authorizedUserIDs" > "$TMP_AUTHORIZED_USER_IDS"
374
375                 # export needed variables
376                 export AUTHORIZED_KEYS
377                 export TMP_AUTHORIZED_USER_IDS
378
379                 # process authorized_user_ids file, as monkeysphere
380                 # user
381                 su --preserve-environment "$MONKEYSPHERE_USER" -c -- \
382                     ". ${SHARE}/common; process_authorized_user_ids $TMP_AUTHORIZED_USER_IDS"
383             fi
384
385             # add user-controlled authorized_keys file path if specified
386             if [ "$rawAuthorizedKeys" != '-' -a -s "$rawAuthorizedKeys" ] ; then
387                 log -n "adding raw authorized_keys file... "
388                 cat "$rawAuthorizedKeys" >> "$AUTHORIZED_KEYS"
389                 loge "done."
390             fi
391
392             # openssh appears to check the contents of the
393             # authorized_keys file as the user in question, so the
394             # file must be readable by that user at least.
395             # FIXME: is there a better way to do this?
396             chown root "$AUTHORIZED_KEYS"
397             chgrp $(getent passwd "$uname" | cut -f4 -d:) "$AUTHORIZED_KEYS"
398             chmod g+r "$AUTHORIZED_KEYS"
399
400             # if the resulting authorized_keys file is not empty, move
401             # it into place
402             mv -f "$AUTHORIZED_KEYS" "${VARLIB}/authorized_keys/${uname}"
403
404             log "authorized_keys file updated."
405             
406             # destroy temporary directory
407             rm -rf "$TMPDIR"
408         done
409         ;;
410
411     'gen-key'|'g')
412         # set gnupg home
413         GNUPGHOME="$GNUPGHOME_HOST"
414         gen_key "$@"
415         ;;
416
417     'show-fingerprint'|'f')
418         # set gnupg home
419         GNUPGHOME="$GNUPGHOME_HOST"
420         fingerprint_server_key "$@"
421         ;;
422
423     'publish-key'|'p')
424         # set gnupg home
425         GNUPGHOME="$GNUPGHOME_HOST"
426         publish_server_key
427         ;;
428
429     'trust-key'|'t')
430         trust_key "$@"
431         ;;
432
433     'help'|'h'|'?')
434         usage
435         ;;
436
437     *)
438         failure "Unknown command: '$COMMAND'
439 Type '$PGRM help' for usage."
440         ;;
441 esac
442
443 exit "$ERR"