fixing an error message in monkeysphere-host
[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 # FIXME: this will probably misbehave if raw IP addresses are provided,
114 # either IPv4 or IPv6 using the bracket notation.
115
116 # FIXME: this doesn't address the use of hashed User IDs.
117
118 check_service_name() {
119     local name="$1"
120     local errs=""
121     local scheme
122     local port
123     local assigned_ports
124
125     [ -n "$name" ] || \
126         failure "You must supply a service name to check"
127
128     printf '%s' "$name" | perl -n -e '($str = $_) =~ s/\s//g ; exit !(lc($str) eq $_);' || \
129         failure "Not a valid service name: '$name'
130
131 Service names should be canonicalized to all lower-case,
132 with no whitespace"
133
134     [[ "$name" =~ ^[a-z0-9./:-]+$ ]] || \
135         failure "Not a valid service name: '$name'
136
137 Service names should contain only lower-case ASCII letters
138 numbers, dots (.), hyphens (-), slashes (/), and a colon (:).
139 If you are using non-ASCII characters (e.g. IDN), you should
140 use the canonicalized ASCII (NAMEPREP -> Punycode) representation
141 (see RFC 3490)."
142
143     [[ "$name" =~ \. ]] || \
144         failure "Not a valid service name: '$name'
145
146 Service names should use fully-qualified domain names (FQDN), but the
147 domain name you chose appears to only have the local part.  For
148 example: don't use 'ssh://foo' ; use 'ssh://foo.example.com' instead."
149
150     [[ "$name" =~ ^[a-z0-9]([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})?$ ]] || \
151         failure "Not a valid service name: '$name'
152
153 Service names look like <scheme>://full.example.com[:<portnumber>],
154 where <scheme> is something like ssh or https, and <portnumber> is
155 a decimal number (supplied only if the service is on a non-standard
156 port)."
157     
158     scheme=$(cut -f1 -d: <<<"$name")
159     port=$(cut -f3 -d: <<<"$name")
160     
161     # check that the scheme name is found in the system services
162     # database
163     available_=$(get_port_for_service "$scheme") || \
164         log error "Error looking up service scheme named '%s'" "$scheme"
165
166     # FIXME: if the service isn't found, or does not have a port, what
167     # should we do? at the moment, we're just warning.
168     
169     if [ -n "$port" ]; then
170     # check that the port number is a legitimate port number (> 0, < 65536)
171         [ "$port" -gt 0 ] && [ "$port" -lt 65536 ] || \
172             failure "The given port number should be greater than 0 and
173 less than 65536.  '$port' is not OK"
174
175     # if the port number is given, and the scheme is in the services
176     # database, check that the port number does *not* match the
177     # default port.
178         if (printf '%s' "$assigned_ports" | grep -q -F -x "$port" ) ; then
179             failure $(printf "The scheme %s uses port number %d by default.
180 You should leave off the port number if it is the default" "$scheme" "$port")
181         fi
182     fi
183
184 }
185
186 # fail if host key not present
187 check_no_keys() {
188     [ -s "$HOST_KEY_FILE" ] \
189         || failure "You don't appear to have a Monkeysphere host key on this server.
190 Please run 'monkeysphere-host import-key' import a key."
191 }
192
193 # key input to functions, outputs full fingerprint of specified key if
194 # found
195 check_key_input() {
196     local keyID="$1"
197     # array of fingerprints
198     local fprs=($(list_primary_fingerprints <"$HOST_KEY_FILE"))
199
200     case ${#fprs[@]} in
201         0)
202             failure "You don't appear to have any Monkeysphere host keys.
203 Please run 'monkeysphere-host import-key' to import a key."
204             ;;
205         1)
206             :
207             ;;
208         *)
209             if [ -z "$keyID" ] ; then
210                 failure "Your host keyring contains multiple keys.
211 Please specify one to act on (see 'monkeysphere-host show-keys')."
212             fi
213             ;;
214     esac
215     printf '%s\n' "${fprs[@]}" | grep "${keyID}$" \
216         || failure "Host key '$keyID' not found."
217 }
218
219 # return 0 if user ID was found.
220 # return 1 if user ID not found.
221 check_key_userid() {
222     local keyID="$1"
223     local userID="$2"
224     local tmpuidMatch
225
226     # match to only "unknown" user IDs (host has no need for ultimate trust)
227     tmpuidMatch="uid:-:$(echo $userID | gpg_escape)"
228
229     # See whether the requsted user ID is present
230     gpg_host_list_keys "$keyID" | cut -f1,2,10 -d: | \
231         grep -q -x -F "$tmpuidMatch" 2>/dev/null
232 }
233
234 prompt_userid_exists() {
235     local userID="$1"
236     local gpgOut
237     local fingerprint
238
239     if gpgOut=$(gpg_host_list_keys "=${userID}" 2>/dev/null) ; then
240         fingerprint=$(echo "$gpgOut" | grep '^fpr:' | cut -d: -f10)
241         if [ "$PROMPT" != "false" ] ; then
242             printf "Service name '%s' is already being used by key '%s'.\nAre you sure you want to use it again? (y/N) " "$userID" "$fingerprint" >&2
243             read OK; OK=${OK:=N}
244             if [ "${OK/y/Y}" != 'Y' ] ; then
245                 failure "Service name not added."
246             fi
247         else
248             log info "Key '%s' is already using the service name '%s'." "$fingerprint" "$userID" >&2
249         fi
250     fi
251 }
252
253 # run command looped over keys
254 multi_key() {
255     local cmd="$1"
256     shift
257     local keys=$@
258     local i=0
259     local key
260
261     check_no_keys
262
263     local fprs=($(list_primary_fingerprints <"$HOST_KEY_FILE"))
264
265     if [[ -z "$1" || "$1" == '--all' ]] ; then
266         keys="${fprs[@]}"
267     fi
268
269     for key in $keys ; do
270         if (( i++ > 0 )) ; then
271             printf "\n"
272         fi
273         "$cmd" "$key"
274     done
275 }
276
277 # show info about the a key
278 show_key() {
279     local id="$1"
280     local GNUPGHOME
281     local fingerprint
282     local tmpssh
283     local revokers
284
285     # tmp gpghome dir
286     export GNUPGHOME=$(msmktempdir)
287
288     # trap to remove tmp dir if break
289     trap "rm -rf $GNUPGHOME" EXIT
290
291     # import the host key into the tmp dir
292     gpg --quiet --import <"$HOST_KEY_FILE"
293
294     # get the gpg fingerprint
295     if gpg --quiet --list-keys \
296         --with-colons --with-fingerprint "$id" \
297         | grep '^fpr:' | cut -d: -f10 > "$GNUPGHOME"/fingerprint ; then
298         fingerprint=$(cat "$GNUPGHOME"/fingerprint)
299     else
300         failure "ID '$id' not found."
301     fi
302
303     # create the ssh key
304     tmpssh="$GNUPGHOME"/ssh_host_key_rsa_pub
305     gpg --export --no-armor "$fingerprint" 2>/dev/null \
306         | openpgp2ssh 2>/dev/null >"$tmpssh"
307
308     # list the host key info
309     # FIXME: make no-show-keyring work so we don't have to do the grep'ing
310     # FIXME: can we show uid validity somehow?
311     gpg --list-keys --list-options show-unusable-uids "$fingerprint" 2>/dev/null \
312         | grep -v "^${GNUPGHOME}/pubring.gpg$" \
313         | egrep -v '^-+$' \
314         | grep -v '^$'
315
316     # list revokers, if there are any
317     revokers=$(gpg --list-keys --with-colons --fixed-list-mode "$fingerprint" \
318         | awk -F: '/^rvk:/{ print $10 }' )
319     if [ "$revokers" ] ; then
320         echo "The following keys are allowed to revoke this host key:"
321         for key in $revokers ; do
322             echo "revoker: $key"
323         done
324     fi
325
326     # list the pgp fingerprint
327     echo "OpenPGP fingerprint: $fingerprint"
328
329     # list the ssh fingerprint
330     echo -n "ssh fingerprint: "
331     ssh-keygen -l -f "$tmpssh" | awk '{ print $1, $2, $4 }'
332
333     # remove the tmp file
334     trap - EXIT
335     rm -rf "$GNUPGHOME"
336 }
337
338 ########################################################################
339 # MAIN
340 ########################################################################
341
342 # load configuration file
343 [ -e ${MONKEYSPHERE_HOST_CONFIG:="${SYSCONFIGDIR}/monkeysphere-host.conf"} ] \
344     && . "$MONKEYSPHERE_HOST_CONFIG"
345
346 # set empty config variable with ones from the environment, or with
347 # defaults
348 LOG_LEVEL=${MONKEYSPHERE_LOG_LEVEL:=$LOG_LEVEL}
349 KEYSERVER=${MONKEYSPHERE_KEYSERVER:=$KEYSERVER}
350 CHECK_KEYSERVER=${MONKEYSPHERE_CHECK_KEYSERVER:=$CHECK_KEYSERVER}
351 MONKEYSPHERE_USER=${MONKEYSPHERE_MONKEYSPHERE_USER:=$MONKEYSPHERE_USER}
352 MONKEYSPHERE_GROUP=$(get_primary_group "$MONKEYSPHERE_USER")
353 PROMPT=${MONKEYSPHERE_PROMPT:=$PROMPT}
354
355 # other variables
356 GNUPGHOME_HOST=${MONKEYSPHERE_GNUPGHOME_HOST:="${MHDATADIR}"}
357 LOG_PREFIX=${MONKEYSPHERE_LOG_PREFIX:='ms: '}
358
359 # export variables needed in su invocation
360 export DATE
361 export LOG_LEVEL
362 export KEYSERVER
363 export CHECK_KEYSERVER
364 export MONKEYSPHERE_USER
365 export MONKEYSPHERE_GROUP
366 export PROMPT
367 export GNUPGHOME_HOST
368 export GNUPGHOME
369 export HOST_FINGERPRINT
370 export LOG_PREFIX
371
372 if [ "$#" -eq 0 ] ; then 
373     usage
374     failure "Please supply a subcommand."
375 fi
376
377 # get subcommand
378 COMMAND="$1"
379 shift
380
381 case $COMMAND in
382     'import-key'|'import'|'i')
383         source "${MHSHAREDIR}/import_key"
384         import_key "$@"
385         ;;
386
387     'show-keys'|'show-key'|'show'|'s')
388         multi_key show_key "$@"
389         ;;
390
391     'set-expire'|'extend-key'|'extend'|'e')
392         source "${MHSHAREDIR}/set_expire"
393         set_expire "$@"
394         ;;
395
396     'add-servicename'|'add-hostname'|'add-name'|'n+')
397         source "${MHSHAREDIR}/add_name"
398         add_name "$@"
399         ;;
400
401     'revoke-servicename'|'revoke-hostname'|'revoke-name'|'n-')
402         source "${MHSHAREDIR}/revoke_name"
403         revoke_name "$@"
404         ;;
405
406     'add-revoker'|'r+')
407         source "${MHSHAREDIR}/add_revoker"
408         add_revoker "$@"
409         ;;
410
411     'revoke-key')
412         source "${MHSHAREDIR}/revoke_key"
413         revoke_key "$@"
414         ;;
415
416     'publish-keys'|'publish-key'|'publish'|'p')
417         source "${MHSHAREDIR}/publish_key"
418         multi_key publish_key "$@"
419         ;;
420
421     'diagnostics'|'d')
422         source "${MHSHAREDIR}/diagnostics"
423         diagnostics
424         ;;
425
426     'update-pgp-pub-file')
427         update_pgp_pub_file
428         ;;
429
430     'version'|'--version'|'v')
431         version
432         ;;
433
434     '--help'|'help'|'-h'|'h'|'?')
435         usage
436         ;;
437
438     *)
439         failure "Unknown command: '$COMMAND'
440 Try '$PGRM help' for usage."
441         ;;
442 esac