scripts/library: introduce parseopts
[pacman-ng.git] / scripts / pacman-key.sh.in
blob288b76eb10b4f76f87e5052c31fef2aea5b8d23f
1 #!/bin/bash
3 # pacman-key - manages pacman's keyring
4 # Based on apt-key, from Debian
5 # @configure_input@
7 # Copyright (c) 2010-2012 Pacman Development Team <pacman-dev@archlinux.org>
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
23 # gettext initialization
24 export TEXTDOMAIN='pacman-scripts'
25 export TEXTDOMAINDIR='@localedir@'
27 declare -r myver="@PACKAGE_VERSION@"
29 # Options
30 ADD=0
31 DELETE=0
32 EDITKEY=0
33 EXPORT=0
34 FINGER=0
35 IMPORT=0
36 IMPORT_TRUSTDB=0
37 INIT=0
38 KEYSERVER=''
39 LISTKEYS=0
40 LISTSIGS=0
41 LSIGNKEY=0
42 POPULATE=0
43 RECEIVE=0
44 REFRESH=0
45 UPDATEDB=0
46 VERIFY=0
48 DEFAULT_KEYSERVER='hkp://pool.sks-keyservers.net'
50 m4_include(library/output_format.sh)
52 m4_include(library/parse_options.sh)
54 usage() {
55 printf "pacman-key (pacman) %s\n" ${myver}
56 echo
57 printf -- "$(gettext "Usage: %s [options]")\n" $(basename $0)
58 echo
59 printf -- "$(gettext "Manage pacman's list of trusted keys")\n"
60 echo
61 printf -- "$(gettext "Options:")\n"
62 printf -- "$(gettext " -a, --add [file(s)] Add the specified keys (empty for stdin)")\n"
63 printf -- "$(gettext " -d, --delete <keyid(s)> Remove the specified keyids")\n"
64 printf -- "$(gettext " -e, --export [keyid(s)] Export the specified or all keyids")\n"
65 printf -- "$(gettext " -f, --finger [keyid(s)] List fingerprint for specified or all keyids")\n"
66 printf -- "$(gettext " -h, --help Show this help message and exit")\n"
67 printf -- "$(gettext " -l, --list-keys [keyid(s)] List the specified or all keys")\n"
68 printf -- "$(gettext " -r, --recv-keys <keyid(s)> Fetch the specified keyids")\n"
69 printf -- "$(gettext " -u, --updatedb Update the trustdb of pacman")\n"
70 printf -- "$(gettext " -v, --verify <signature> Verify the file specified by the signature")\n"
71 printf -- "$(gettext " -V, --version Show program version")\n"
72 printf -- "$(gettext " --config <file> Use an alternate config file (instead of\n\
73 '%s')")\n" "@sysconfdir@/pacman.conf"
74 printf -- "$(gettext " --edit-key <keyid(s)> Present a menu for key management task on keyids")\n"
75 printf -- "$(gettext " --gpgdir <dir> Set an alternate directory for GnuPG (instead\n\
76 of '%s')")\n" "@sysconfdir@/pacman.d/gnupg"
77 printf -- "$(gettext " --import <dir(s)> Imports pubring.gpg from dir(s)")\n"
78 printf -- "$(gettext " --import-trustdb <dir(s)> Imports ownertrust values from trustdb.gpg in dir(s)")\n"
79 printf -- "$(gettext " --init Ensure the keyring is properly initialized")\n"
80 printf -- "$(gettext " --keyserver Specify a keyserver to use if necessary")\n"
81 printf -- "$(gettext " --list-sigs [keyid(s)] List keys and their signatures")\n"
82 printf -- "$(gettext " --lsign-key <keyid> Locally sign the specified keyid")\n"
83 printf -- "$(gettext " --populate [keyring(s)] Reload the default keys from the (given) keyrings\n\
84 in '%s'")\n" "@pkgdatadir@/keyrings"
85 printf -- "$(gettext " --refresh-keys [keyid(s)] Update specified or all keys from a keyserver")\n"
88 version() {
89 printf "pacman-key (pacman) %s\n" "${myver}"
90 printf -- "$(gettext "\
91 Copyright (c) 2010-2012 Pacman Development Team <pacman-dev@archlinux.org>.\n\
92 This is free software; see the source for copying conditions.\n\
93 There is NO WARRANTY, to the extent permitted by law.\n")"
96 # read the config file "$1" which has key=value pairs, and return the key which
97 # matches "$2". the equals sign between pairs may be surrounded by any amount
98 # of whitespace. Optionally, "$3" can be specified which is the default value
99 # when no key is found.
100 get_from() {
101 while IFS='=' read -r key value; do
102 [[ -z $key || ${key:0:1} = '#' ]] && continue
104 if [[ ${key%% *} = "$2" && -n ${value##* } ]]; then
105 echo "${value##* }"
106 return 0
108 done < "$1"
109 if [[ -n "$3" ]]; then
110 printf '%s\n' "$3"
111 return 0
113 return 1
116 generate_master_key() {
117 # Generate the master key, which will be in both pubring and secring
118 "${GPG_PACMAN[@]}" --gen-key --batch <<EOF
119 %echo Generating pacman keychain master key...
120 Key-Type: RSA
121 Key-Length: 2048
122 Key-Usage: sign
123 Name-Real: Pacman Keychain Master Key
124 Name-Email: pacman@localhost
125 Expire-Date: 0
126 %commit
127 %echo Done
131 secret_keys_available() {
132 "${GPG_PACMAN[@]}" -K --with-colons | wc -l
135 # Adds the given gpg.conf option if it is not present in the file.
136 # Note that if we find it commented out, we won't add the option.
137 # args: $1 conffile, $2 option-name, $3 (optional) option-value
138 add_gpg_conf_option() {
139 local conffile=$1; shift
140 # looking for the option 'bare', only leading spaces or # chars allowed,
141 # followed by at least one space and any other text or the end of line.
142 if ! grep -q "^[[:space:]#]*$1\([[:space:]].*\)*$" "$conffile" &>/dev/null; then
143 printf '%s\n' "$*" >> "$conffile"
147 check_keyids_exist() {
148 local ret=0
149 for key in "${KEYIDS[@]}"; do
150 # Verify if the key exists in pacman's keyring
151 if ! "${GPG_PACMAN[@]}" --list-keys "$key" &>/dev/null ; then
152 error "$(gettext "The key identified by %s could not be found locally.")" "$key"
153 ret=1
155 done
156 if (( ret )); then
157 exit 1
161 initialize() {
162 local conffile keyserv
163 # Check for simple existence rather than for a directory as someone
164 # may want to use a symlink here
165 [[ -e ${PACMAN_KEYRING_DIR} ]] || mkdir -p -m 755 "${PACMAN_KEYRING_DIR}"
167 # keyring files
168 [[ -f ${PACMAN_KEYRING_DIR}/pubring.gpg ]] || touch ${PACMAN_KEYRING_DIR}/pubring.gpg
169 [[ -f ${PACMAN_KEYRING_DIR}/secring.gpg ]] || touch ${PACMAN_KEYRING_DIR}/secring.gpg
170 [[ -f ${PACMAN_KEYRING_DIR}/trustdb.gpg ]] || "${GPG_PACMAN[@]}" --update-trustdb
171 chmod 644 ${PACMAN_KEYRING_DIR}/{pubring,trustdb}.gpg
172 chmod 600 ${PACMAN_KEYRING_DIR}/secring.gpg
174 # gpg.conf
175 conffile="${PACMAN_KEYRING_DIR}/gpg.conf"
176 [[ -f $conffile ]] || touch "$conffile"
177 chmod 644 "$conffile"
178 add_gpg_conf_option "$conffile" 'no-greeting'
179 add_gpg_conf_option "$conffile" 'no-permission-warning'
180 add_gpg_conf_option "$conffile" 'lock-never'
181 keyserv=${KEYSERVER:-$DEFAULT_KEYSERVER}
182 add_gpg_conf_option "$conffile" 'keyserver' "$keyserv"
183 add_gpg_conf_option "$conffile" 'keyserver-options' 'timeout=10'
185 # set up a private signing key (if none available)
186 if [[ $(secret_keys_available) -lt 1 ]]; then
187 generate_master_key
188 UPDATEDB=1
192 check_keyring() {
193 if [[ ! -r ${PACMAN_KEYRING_DIR}/pubring.gpg || \
194 ! -r ${PACMAN_KEYRING_DIR}/trustdb.gpg ]]; then
195 error "$(gettext "You do not have sufficient permissions to read the %s keyring.")" "pacman"
196 msg "$(gettext "Use '%s' to correct the keyring permissions.")" "pacman-key --init"
197 exit 1
200 if (( (EXPORT || FINGER || LIST || VERIFY) && EUID != 0 )); then
201 if ! grep -q "^[[:space:]]*lock-never[[:space:]]*$" ${PACMAN_KEYRING_DIR}/gpg.conf &>/dev/null; then
202 error "$(gettext "You do not have sufficient permissions to run this command.")"
203 msg "$(gettext "Use '%s' to correct the keyring permissions.")" "pacman-key --init"
204 exit 1
208 if (( LSIGNKEY )); then
209 if [[ $(secret_keys_available) -lt 1 ]]; then
210 error "$(gettext "There is no secret key available to sign with.")"
211 msg "$(gettext "Use '%s' to generate a default secret key.")" "pacman-key --init"
212 exit 1
217 populate_keyring() {
218 local KEYRING_IMPORT_DIR='@pkgdatadir@/keyrings'
220 local keyring
221 local ret=0
222 if [[ -z ${KEYRINGIDS[@]} ]]; then
223 # get list of all available keyrings
224 shopt -s nullglob
225 KEYRINGIDS=("$KEYRING_IMPORT_DIR"/*.gpg)
226 shopt -u nullglob
227 KEYRINGIDS=("${KEYRINGIDS[@]##*/}")
228 KEYRINGIDS=("${KEYRINGIDS[@]%.gpg}")
229 if [[ -z ${KEYRINGIDS[@]} ]]; then
230 error "$(gettext "No keyring files exist in %s.")" "$KEYRING_IMPORT_DIR"
231 ret=1
233 else
234 # verify listed keyrings exist
235 for keyring in "${KEYRINGIDS[@]}"; do
236 if [[ ! -f "$KEYRING_IMPORT_DIR/$keyring.gpg" ]]; then
237 error "$(gettext "The keyring file %s does not exist.")" "$KEYRING_IMPORT_DIR/$keyring.gpg"
238 ret=1
240 done
243 if (( ret )); then
244 exit 1
247 # Variable used for iterating on keyrings
248 local keys key_id
250 # Add keys from requested keyrings
251 for keyring in "${KEYRINGIDS[@]}"; do
252 msg "$(gettext "Appending keys from %s.gpg...")" "$keyring"
253 "${GPG_PACMAN[@]}" --import "${KEYRING_IMPORT_DIR}/${keyring}.gpg"
254 done
256 # Read the trusted key IDs to an array. Because this is an ownertrust
257 # file, we know we have the full 40 hex digit fingerprint values.
258 # Format of ownertrust dump file:
259 # 40CHARFINGERPRINTXXXXXXXXXXXXXXXXXXXXXXX:6:
260 # 40CHARFINGERPRINTXXXXXXXXXXXXXXXXXXXXXXX:5:
261 local -A trusted_ids
262 for keyring in "${KEYRINGIDS[@]}"; do
263 if [[ -f "${KEYRING_IMPORT_DIR}/${keyring}-trusted" ]]; then
264 while IFS=: read key_id _; do
265 # skip blank lines, comments; these are valid in this file
266 [[ -z $key_id || ${key_id:0:1} = \# ]] && continue
268 # Mark this key to be lsigned
269 trusted_ids[$key_id]=$keyring
270 done < "${KEYRING_IMPORT_DIR}/${keyring}-trusted"
272 done
274 if (( ${#trusted_ids[@]} > 0 )); then
275 msg "$(gettext "Locally signing trusted keys in keyring...")"
276 for key_id in "${!trusted_ids[@]}"; do
277 msg2 "$(gettext "Locally signing key %s...")" "${key_id}"
278 "${GPG_PACMAN[@]}" --quiet --lsign-key "${key_id}"
279 done
280 msg "$(gettext "Importing owner trust values...")"
281 for keyring in "${KEYRINGIDS[@]}"; do
282 if [[ -f "${KEYRING_IMPORT_DIR}/${keyring}-trusted" ]]; then
283 "${GPG_PACMAN[@]}" --import-ownertrust "${KEYRING_IMPORT_DIR}/${keyring}-trusted"
285 done
288 # Read the revoked key IDs to an array. The conversion from whatever is
289 # inside the file to key ids is important, because key ids are the only
290 # guarantee of identification for the keys.
291 local -A revoked_ids
292 for keyring in "${KEYRINGIDS[@]}"; do
293 if [[ -f "${KEYRING_IMPORT_DIR}/${keyring}-revoked" ]]; then
294 IFS=$'\n' read -r -d '' -a keys < "${KEYRING_IMPORT_DIR}/${keyring}-revoked"
295 while IFS=: read _ _ _ _ key_id _; do
296 if [[ -n $key_id ]]; then
297 # Mark this key to be disabled
298 revoked_ids[$key_id]="${keyring}"
300 done < <("${GPG_PACMAN[@]}" --quiet --with-colons --list-keys "${keys[@]}" 2>/dev/null)
302 done
304 if (( ${#revoked_ids[@]} > 0 )); then
305 msg "$(gettext "Disabling revoked keys in keyring...")"
306 for key_id in "${!revoked_ids[@]}"; do
307 msg2 "$(gettext "Disabling key %s...")" "${key_id}"
308 printf 'disable\nquit\n' | LANG=C "${GPG_PACMAN[@]}" --command-fd 0 --quiet --batch --edit-key "${key_id}" 2>/dev/null
309 done
313 add_keys() {
314 if ! "${GPG_PACMAN[@]}" --quiet --batch --import "${KEYFILES[@]}" ; then
315 error "$(gettext "A specified keyfile could not be added to the gpg keychain.")"
316 exit 1
320 delete_keys() {
321 check_keyids_exist
322 if ! "${GPG_PACMAN[@]}" --quiet --batch --delete-key --yes "${KEYIDS[@]}" ; then
323 error "$(gettext "A specified key could not be removed from the gpg keychain.")"
324 exit 1
328 edit_keys() {
329 check_keyids_exist
330 local ret=0
331 for key in "${KEYIDS[@]}"; do
332 if ! "${GPG_PACMAN[@]}" --edit-key "$key" ; then
333 error "$(gettext "The key identified by %s could not be edited.")" "$key"
334 ret=1
336 done
337 if (( ret )); then
338 exit 1
342 export_keys() {
343 check_keyids_exist
344 if ! "${GPG_PACMAN[@]}" --armor --export "${KEYIDS[@]}" ; then
345 error "$(gettext "A specified key could not be exported from the gpg keychain.")"
346 exit 1
350 finger_keys() {
351 check_keyids_exist
352 if ! "${GPG_PACMAN[@]}" --batch --fingerprint "${KEYIDS[@]}" ; then
353 error "$(gettext "The fingerprint of a specified key could not be determined.")"
354 exit 1
358 import_trustdb() {
359 local importdir
360 local ret=0
361 for importdir in "${IMPORT_DIRS[@]}"; do
362 if [[ -f "${importdir}/trustdb.gpg" ]]; then
363 gpg --homedir "${importdir}" --export-ownertrust | \
364 "${GPG_PACMAN[@]}" --import-ownertrust -
365 if (( PIPESTATUS )); then
366 error "$(gettext "%s could not be imported.")" "${importdir}/trustdb.gpg"
367 ret=1
369 else
370 error "$(gettext "File %s does not exist and could not be imported.")" "${importdir}/trustdb.gpg"
371 ret=1
373 done
374 if (( ret )); then
375 exit 1
379 import() {
380 local importdir
381 local ret=0
382 for importdir in "${IMPORT_DIRS[@]}"; do
383 if [[ -f "${importdir}/pubring.gpg" ]]; then
384 if ! "${GPG_PACMAN[@]}" --quiet --batch --import "${importdir}/pubring.gpg" ; then
385 error "$(gettext "%s could not be imported.")" "${importdir}/pubring.gpg"
386 ret=1
388 else
389 error "$(gettext "File %s does not exist and could not be imported.")" "${importdir}/pubring.gpg"
390 ret=1
392 done
393 if (( ret )); then
394 exit 1
398 list_keys() {
399 check_keyids_exist
400 if ! "${GPG_PACMAN[@]}" --batch --list-keys "${KEYIDS[@]}" ; then
401 error "$(gettext "A specified key could not be listed.")"
402 exit 1
406 list_sigs() {
407 check_keyids_exist
408 if ! "${GPG_PACMAN[@]}" --batch --list-sigs "${KEYIDS[@]}" ; then
409 error "$(gettext "A specified signature could not be listed.")"
410 exit 1
414 lsign_keys() {
415 check_keyids_exist
416 printf 'y\ny\n' | LANG=C "${GPG_PACMAN[@]}" --command-fd 0 --quiet --batch --lsign-key "${KEYIDS[@]}" 2>/dev/null
417 if (( PIPESTATUS[1] )); then
418 error "$(gettext "A specified key could not be locally signed.")"
419 exit 1
423 receive_keys() {
424 if ! "${GPG_PACMAN[@]}" --recv-keys "${KEYIDS[@]}" ; then
425 error "$(gettext "Remote key not fetched correctly from keyserver.")"
426 exit 1
430 refresh_keys() {
431 check_keyids_exist
432 if ! "${GPG_PACMAN[@]}" --refresh-keys "${KEYIDS[@]}" ; then
433 error "$(gettext "A specified local key could not be updated from a keyserver.")"
434 exit 1
438 verify_sig() {
439 if ! "${GPG_PACMAN[@]}" --status-fd 1 --verify $SIGNATURE | grep -qE 'TRUST_(FULLY|ULTIMATE)'; then
440 error "$(gettext "The signature identified by %s could not be verified.")" "$SIGNATURE"
441 exit 1
445 updatedb() {
446 msg "$(gettext "Updating trust database...")"
447 if ! "${GPG_PACMAN[@]}" --batch --check-trustdb ; then
448 error "$(gettext "Trust database could not be updated.")"
449 exit 1
453 # PROGRAM START
454 if ! type gettext &>/dev/null; then
455 gettext() {
456 echo "$@"
460 OPT_SHORT="a::d:e::f::hl::r:uv:V"
461 OPT_LONG="add::,config:,delete:,edit-key:,export::,finger::,gpgdir:"
462 OPT_LONG+=",help,import:,import-trustdb:,init,keyserver:,list-keys::,list-sigs::"
463 OPT_LONG+=",lsign-key:,populate::,recv-keys:,refresh-keys::,updatedb"
464 OPT_LONG+=",verify:,version"
465 if ! OPT_TEMP="$(parse_options $OPT_SHORT $OPT_LONG "$@")"; then
466 echo; usage; exit 1 # E_INVALID_OPTION;
468 eval set -- "$OPT_TEMP"
469 unset OPT_SHORT OPT_LONG OPT_TEMP
471 if [[ $1 == "--" ]]; then
472 usage;
473 exit 0;
476 while true; do
477 case "$1" in
478 -a|--add) ADD=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYFILES=($1); UPDATEDB=1 ;;
479 --config) shift; CONFIG=$1 ;;
480 -d|--delete) DELETE=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
481 --edit-key) EDITKEY=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
482 -e|--export) EXPORT=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
483 -f|--finger) FINGER=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
484 --gpgdir) shift; PACMAN_KEYRING_DIR=$1 ;;
485 --import) IMPORT=1; shift; IMPORT_DIRS=($1); UPDATEDB=1 ;;
486 --import-trustdb) IMPORT_TRUSTDB=1; shift; IMPORT_DIRS=($1); UPDATEDB=1 ;;
487 --init) INIT=1 ;;
488 --keyserver) shift; KEYSERVER=$1 ;;
489 -l|--list-keys) LISTKEYS=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
490 --list-sigs) LISTSIGS=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
491 --lsign-key) LSIGNKEY=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
492 --populate) POPULATE=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYRINGIDS=($1); UPDATEDB=1 ;;
493 -r|--recv-keys) RECEIVE=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
494 --refresh-keys) REFRESH=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
495 -u|--updatedb) UPDATEDB=1 ;;
496 -v|--verify) VERIFY=1; shift; SIGNATURE=$1 ;;
498 -h|--help) usage; exit 0 ;;
499 -V|--version) version; exit 0 ;;
501 --) OPT_IND=0; shift; break;;
502 *) usage; exit 1 ;;
503 esac
504 shift
505 done
508 if ! type -p gpg >/dev/null; then
509 error "$(gettext "Cannot find the %s binary required for all %s operations.")" "gpg" "pacman-key"
510 exit 1
513 if (( (ADD || DELETE || EDITKEY || IMPORT || IMPORT_TRUSTDB || INIT || LSIGNKEY || POPULATE || RECEIVE || REFRESH || UPDATEDB) && EUID != 0 )); then
514 error "$(gettext "%s needs to be run as root for this operation.")" "pacman-key"
515 exit 1
518 CONFIG=${CONFIG:-@sysconfdir@/pacman.conf}
519 if [[ ! -r "${CONFIG}" ]]; then
520 error "$(gettext "%s configuration file '%s' not found.")" "pacman" "$CONFIG"
521 exit 1
524 # if PACMAN_KEYRING_DIR isn't assigned, try to get it from the config
525 # file, falling back on a hard default
526 PACMAN_KEYRING_DIR=${PACMAN_KEYRING_DIR:-$(get_from "$CONFIG" "GPGDir" "@sysconfdir@/pacman.d/gnupg")}
528 GPG_PACMAN=(gpg --homedir "${PACMAN_KEYRING_DIR}" --no-permission-warning)
529 if [[ -n ${KEYSERVER} ]]; then
530 GPG_PACMAN+=(--keyserver "${KEYSERVER}")
533 # check only a single operation has been given
534 # don't include UPDATEDB in here as other opts can induce it
535 numopt=$(( ADD + DELETE + EDITKEY + EXPORT + FINGER + IMPORT + IMPORT_TRUSTDB +
536 INIT + LISTKEYS + LISTSIGS + LSIGNKEY + POPULATE + RECEIVE + REFRESH + VERIFY ))
538 case $numopt in
540 if (( ! UPDATEDB )); then
541 error "$(gettext "no operation specified (use -h for help)")"
542 exit 1
545 [!1])
546 error "$(gettext "Multiple operations specified.")"
547 msg "$(gettext "Please run %s with each operation separately.")" "pacman-key"
548 exit 1
550 esac
552 (( ! INIT )) && check_keyring
554 (( ADD )) && add_keys
555 (( DELETE )) && delete_keys
556 (( EDITKEY )) && edit_keys
557 (( EXPORT )) && export_keys
558 (( FINGER )) && finger_keys
559 (( IMPORT )) && import
560 (( IMPORT_TRUSTDB)) && import_trustdb
561 (( INIT )) && initialize
562 (( LISTKEYS )) && list_keys
563 (( LISTSIGS )) && list_sigs
564 (( LSIGNKEY )) && lsign_keys
565 (( POPULATE )) && populate_keyring
566 (( RECEIVE )) && receive_keys
567 (( REFRESH )) && refresh_keys
568 (( VERIFY )) && verify_sig
570 (( UPDATEDB )) && updatedb
572 exit 0
574 # vim: set ts=2 sw=2 noet: