tweak loading of fingerprints in multi_key wrapper function, so unnecessary error...
[monkeysphere.git] / src / monkeysphere-host
1 #!/usr/bin/env bash
2
3 # monkeysphere-host: Monkeysphere host admin tool
4 #
5 # The monkeysphere scripts are written by:
6 # Jameson Rollins <jrollins@finestructure.net>
7 # Jamie McClelland <jm@mayfirst.org>
8 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
9 # Micah Anderson <micah@riseup.net>
10 #
11 # They are Copyright 2008-2010, and are all released under the GPL,
12 # version 3 or later.
13
14 ########################################################################
15 set -e
16
17 # set the pipefail option so pipelines fail on first command failure
18 set -o pipefail
19
20 PGRM=$(basename $0)
21
22 SYSSHAREDIR=${MONKEYSPHERE_SYSSHAREDIR:-"/usr/share/monkeysphere"}
23 export SYSSHAREDIR
24 . "${SYSSHAREDIR}/defaultenv"
25 . "${SYSSHAREDIR}/common"
26
27 SYSDATADIR=${MONKEYSPHERE_SYSDATADIR:-"/var/lib/monkeysphere"}
28 export SYSDATADIR
29
30 # sharedir for host functions
31 MHSHAREDIR="${SYSSHAREDIR}/mh"
32
33 # datadir for host functions
34 MHDATADIR="${SYSDATADIR}/host"
35
36 # host pub key files
37 HOST_KEY_FILE="${SYSDATADIR}/host_keys.pub.pgp"
38
39 # UTC date in ISO 8601 format if needed
40 DATE=$(date -u '+%FT%T')
41
42 # unset some environment variables that could screw things up
43 unset GREP_OPTIONS
44
45 ########################################################################
46 # FUNCTIONS
47 ########################################################################
48
49 usage() {
50     cat <<EOF >&2
51 usage: $PGRM <subcommand> [options] [args]
52 Monkeysphere host admin tool.
53
54 subcommands:
55  import-key (i) FILE SERVICENAME       import PEM-encoded key from file
56  show-keys (s) [KEYID ...]             output host key information
57  publish-keys (p) [KEYID ...]          publish key(s) to keyserver
58  set-expire (e) EXPIRE [KEYID]         set key expiration
59  add-servicename (n+) SERVICENAME [KEYID]
60                                        add a service name to key
61  revoke-servicename (n-) SERVICENAME [KEYID]
62                                        revoke a service name from key
63  add-revoker (r+) REVOKER_KEYID|FILE [KEYID]
64                                        add a revoker to key
65  revoke-key [KEYID]                    generate and/or publish revocation
66                                        certificate for key
67
68  version (v)                           show version number
69  help (h,?)                            this help
70
71 See ${PGRM}(8) for more info.
72 EOF
73 }
74
75 # function to interact with the gpg keyring
76 gpg_host() {
77     GNUPGHOME="$GNUPGHOME_HOST" gpg --no-greeting --quiet --no-tty "$@"
78 }
79
80 # list the info about the a key, in colon format, to stdout
81 gpg_host_list_keys() {
82     if [ "$1" ] ; then
83         gpg_host --list-keys --with-colons --fixed-list-mode \
84             --with-fingerprint --with-fingerprint \
85             "$1"
86     else
87         gpg_host --list-keys --with-colons --fixed-list-mode \
88             --with-fingerprint --with-fingerprint
89     fi
90 }
91
92 # edit key scripts, takes scripts on stdin, and keyID as first input
93 gpg_host_edit() {
94     gpg_host --command-fd 0 --edit-key "$@"
95 }
96
97 # export the monkeysphere OpenPGP pub key file
98 update_pgp_pub_file() {
99     log debug "updating openpgp public key file '$HOST_KEY_FILE'..."
100     gpg_host --export --armor --export-options export-minimal \
101         $(gpg_host --list-secret-keys --with-colons --fingerprint | grep ^fpr | cut -f10 -d:) \
102         > "$HOST_KEY_FILE"
103 }
104
105 # check that the service name is well formed. we assume that the
106 # service name refers to a host; DNS labels for host names are limited
107 # to a very small range of characters (see RFC 1912, section 2.1).
108
109 # FIXME: i'm failing to check here for label components that are
110 # all-number (e.g. ssh://666.666), which are technically not allowed
111 # (though some exist on the 'net, apparently)
112
113 check_service_name() {
114     local name="$1"
115     local errs=""
116     local scheme
117     local port
118     local assigned_ports
119
120     [ -n "$name" ] || \
121         failure "You must supply a service name to check"
122
123     printf '%s' "$name" | perl -n -e '($str = $_) =~ s/\s//g ; exit !(lc($str) eq $_);' || \
124         failure "Not a valid service name: '$name'
125
126 Service names should be canonicalized to all lower-case,
127 with no whitespace"
128
129     [[ "$name" =~ ^[a-z0-9./:-]+$ ]] || \
130         failure "Not a valid service name: '$name'
131
132 Service names should contain only lower-case ASCII letters
133 numbers, dots (.), hyphens (-), slashes (/), and a colon (:).
134 If you are using non-ASCII characters (e.g. IDN), you should
135 use the canonicalized ASCII (NAMEPREP -> Punycode) representation
136 (see RFC 3490)."
137
138     [[ "$name" =~ \. ]] || \
139         failure "Not a valid service name: '$name'
140
141 Service names should use fully-qualified domain names (FQDN), but the
142 domain name you chose appears to only have the local part.  For
143 example: don't use 'ssh://foo' ; use 'ssh://foo.example.com' instead."
144
145     [[ "$name" =~ ^[a-z]([a-z0-9-]*[a-z0-9])?://[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.|((\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+))(:[1-9][0-9]{0,4})?$ ]] || \
146         failure "Not a valid service name: '$name'
147
148 Service names look like <scheme>://full.example.com[:<portnumber>],
149 where <scheme> is something like ssh or https, and <portnumber> is
150 a decimal number (supplied only if the service is on a non-standard
151 port)."
152     
153     scheme=$(cut -f1 -d: <<<"$name")
154     port=$(cut -f3 -d: <<<"$name")
155     
156     # check that the scheme name is found in the system services
157     # database
158     available_=$(get_port_for_service "$scheme") || \
159         log error "Error looking up service scheme named '%s'" "$scheme"
160
161     # FIXME: if the service isn't found, or does not have a port, what
162     # should we do? at the moment, we're just warning.
163     
164     if [ -n "$port" ]; then
165     # check that the port number is a legitimate port number (> 0, < 65536)
166         [ "$port" -gt 0 ] && [ "$port" -lt 65536 ] || \
167             failure "The given port number should be greater than 0 and
168 less than 65536.  '$port' is not OK"
169
170     # if the port number is given, and the scheme is in the services
171     # database, check that the port number does *not* match the
172     # default port.
173         if (printf '%s' "$assigned_ports" | grep -q -F -x "$port" ) ; then
174             failure $(printf "The scheme %s uses port number %d by default.
175 You should leave off the port number if it is the default" "$scheme" "$port")
176         fi
177     fi
178
179 }
180
181 # fail if host key not present
182 check_no_keys() {
183     [ -s "$HOST_KEY_FILE" ] \
184         || failure "You don't appear to have a Monkeysphere host key on this server.
185 Please run 'monkeysphere-host import-key' import a key."
186 }
187
188 # key input to functions, outputs full fingerprint of specified key if
189 # found
190 check_key_input() {
191     local keyID="$1"
192     # array of fingerprints
193     local fprs=($(list_primary_fingerprints <"$HOST_KEY_FILE"))
194
195     case ${#fprs[@]} in
196         0)
197             failure "You don't appear to have any Monkeysphere host keys.
198 Please run 'monkeysphere-host import-key' to import a key."
199             ;;
200         1)
201             :
202             ;;
203         *)
204             if [ -z "$keyID" ] ; then
205                 failure "Your host keyring contains multiple keys.
206 Please specify one to act on (see 'monkeysphere-host show-keys')."
207             fi
208             ;;
209     esac
210     printf '%s\n' "${fprs[@]}" | grep "${keyID}$" \
211         || failure "Host key '$keyID' not found."
212 }
213
214 # return 0 if user ID was found.
215 # return 1 if user ID not found.
216 check_key_userid() {
217     local keyID="$1"
218     local userID="$2"
219     local tmpuidMatch
220
221     # match to only "unknown" user IDs (host has no need for ultimate trust)
222     tmpuidMatch="uid:-:$(echo $userID | gpg_escape)"
223
224     # See whether the requsted user ID is present
225     gpg_host_list_keys "$keyID" | cut -f1,2,10 -d: | \
226         grep -q -x -F "$tmpuidMatch" 2>/dev/null
227 }
228
229 prompt_userid_exists() {
230     local userID="$1"
231     local gpgOut
232     local fingerprint
233
234     if gpgOut=$(gpg_host_list_keys "=${userID}" 2>/dev/null) ; then
235         fingerprint=$(echo "$gpgOut" | grep '^fpr:' | cut -d: -f10)
236         if [ "$PROMPT" != "false" ] ; then
237             printf "Service name '%s' is already being used by key '%s'.\nAre you sure you want to use it again? (y/N) " "$fingerprint" "$userID" >&2
238             read OK; OK=${OK:=N}
239             if [ "${OK/y/Y}" != 'Y' ] ; then
240                 failure "Service name not added."
241             fi
242         else
243             log info "Key '%s' is already using the service name '%s'." "$fingerprint" "$userID" >&2
244         fi
245     fi
246 }
247
248 # run command looped over keys
249 multi_key() {
250     local cmd="$1"
251     shift
252     local keys=$@
253     local i=0
254     local key
255
256     check_no_keys
257
258     local fprs=($(list_primary_fingerprints <"$HOST_KEY_FILE"))
259
260     if [[ -z "$1" || "$1" == '--all' ]] ; then
261         keys="${fprs[@]}"
262     fi
263
264     for key in $keys ; do
265         if (( i++ > 0 )) ; then
266             echo "##############################"
267         fi
268         eval "$cmd" "$key"
269     done
270 }
271
272 # show info about the a key
273 show_key() {
274     local id="$1"
275     local GNUPGHOME
276     local fingerprint
277     local tmpssh
278     local revokers
279
280     # tmp gpghome dir
281     export GNUPGHOME=$(msmktempdir)
282
283     # trap to remove tmp dir if break
284     trap "rm -rf $GNUPGHOME" EXIT
285
286     # import the host key into the tmp dir
287     gpg --quiet --import <"$HOST_KEY_FILE"
288
289     # get the gpg fingerprint
290     if gpg --quiet --list-keys \
291         --with-colons --with-fingerprint "$id" \
292         | grep '^fpr:' | cut -d: -f10 > "$GNUPGHOME"/fingerprint ; then
293         fingerprint=$(cat "$GNUPGHOME"/fingerprint)
294     else
295         failure "ID '$id' not found."
296     fi
297
298     # create the ssh key
299     tmpssh="$GNUPGHOME"/ssh_host_key_rsa_pub
300     gpg --export "$fingerprint" 2>/dev/null \
301         | openpgp2ssh 2>/dev/null >"$tmpssh"
302
303     # list the host key info
304     # FIXME: make no-show-keyring work so we don't have to do the grep'ing
305     # FIXME: can we show uid validity somehow?
306     gpg --list-keys --list-options show-unusable-uids "$fingerprint" 2>/dev/null \
307         | grep -v "^${GNUPGHOME}/pubring.gpg$" \
308         | egrep -v '^-+$'
309
310     # list revokers, if there are any
311     revokers=$(gpg --list-keys --with-colons --fixed-list-mode "$fingerprint" \
312         | awk -F: '/^rvk:/{ print $10 }' )
313     if [ "$revokers" ] ; then
314         echo "The following keys are allowed to revoke this host key:"
315         for key in $revokers ; do
316             echo "revoker: $key"
317         done
318         echo
319     fi
320
321     # list the pgp fingerprint
322     echo "OpenPGP fingerprint: $fingerprint"
323
324     # list the ssh fingerprint
325     echo -n "ssh fingerprint: "
326     ssh-keygen -l -f "$tmpssh" | awk '{ print $1, $2, $4 }'
327
328     # remove the tmp file
329     trap - EXIT
330     rm -rf "$GNUPGHOME"
331 }
332
333 ########################################################################
334 # MAIN
335 ########################################################################
336
337 # load configuration file
338 [ -e ${MONKEYSPHERE_HOST_CONFIG:="${SYSCONFIGDIR}/monkeysphere-host.conf"} ] \
339     && . "$MONKEYSPHERE_HOST_CONFIG"
340
341 # set empty config variable with ones from the environment, or with
342 # defaults
343 LOG_LEVEL=${MONKEYSPHERE_LOG_LEVEL:=$LOG_LEVEL}
344 KEYSERVER=${MONKEYSPHERE_KEYSERVER:=$KEYSERVER}
345 CHECK_KEYSERVER=${MONKEYSPHERE_CHECK_KEYSERVER:=$CHECK_KEYSERVER}
346 MONKEYSPHERE_USER=${MONKEYSPHERE_MONKEYSPHERE_USER:=$MONKEYSPHERE_USER}
347 MONKEYSPHERE_GROUP=$(get_primary_group "$MONKEYSPHERE_USER")
348 PROMPT=${MONKEYSPHERE_PROMPT:=$PROMPT}
349
350 # other variables
351 GNUPGHOME_HOST=${MONKEYSPHERE_GNUPGHOME_HOST:="${MHDATADIR}"}
352 LOG_PREFIX=${MONKEYSPHERE_LOG_PREFIX:='ms: '}
353
354 # export variables needed in su invocation
355 export DATE
356 export LOG_LEVEL
357 export KEYSERVER
358 export CHECK_KEYSERVER
359 export MONKEYSPHERE_USER
360 export MONKEYSPHERE_GROUP
361 export PROMPT
362 export GNUPGHOME_HOST
363 export GNUPGHOME
364 export HOST_FINGERPRINT
365 export LOG_PREFIX
366
367 if [ "$#" -eq 0 ] ; then 
368     usage
369     failure "Please supply a subcommand."
370 fi
371
372 # get subcommand
373 COMMAND="$1"
374 shift
375
376 case $COMMAND in
377     'import-key'|'i')
378         source "${MHSHAREDIR}/import_key"
379         import_key "$@"
380         ;;
381
382     'show-keys'|'show-key'|'show'|'s')
383         multi_key show_key "$@"
384         ;;
385
386     'set-expire'|'extend-key'|'e')
387         source "${MHSHAREDIR}/set_expire"
388         set_expire "$@"
389         ;;
390
391     'add-servicename'|'add-hostname'|'add-name'|'n+')
392         source "${MHSHAREDIR}/add_name"
393         add_name "$@"
394         ;;
395
396     'revoke-servicename'|'revoke-hostname'|'revoke-name'|'n-')
397         source "${MHSHAREDIR}/revoke_name"
398         revoke_name "$@"
399         ;;
400
401     'add-revoker'|'r+')
402         source "${MHSHAREDIR}/add_revoker"
403         add_revoker "$@"
404         ;;
405
406     'revoke-key')
407         source "${MHSHAREDIR}/revoke_key"
408         revoke_key "$@"
409         ;;
410
411     'publish-keys'|'publish-key'|'publish'|'p')
412         source "${MHSHAREDIR}/publish_key"
413         multi_key publish_key "$@"
414         ;;
415
416     'diagnostics'|'d')
417         source "${MHSHAREDIR}/diagnostics"
418         diagnostics
419         ;;
420
421     'update-pgp-pub-file')
422         update_pgp_pub_file
423         ;;
424
425     'version'|'v')
426         version
427         ;;
428
429     '--help'|'help'|'-h'|'h'|'?')
430         usage
431         ;;
432
433     *)
434         failure "Unknown command: '$COMMAND'
435 Try '$PGRM help' for usage."
436         ;;
437 esac