summaryrefslogtreecommitdiff
path: root/scripts/pacman-key.sh.in
blob: 7eebf7c870608afae7dfc09f43c24441387b93d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#!/bin/bash
#
#   pacman-key - manages pacman's keyring
#                Based on apt-key, from Debian
#   @configure_input@
#
#   Copyright (c) 2010-2011 Pacman Development Team <pacman-dev@archlinux.org>
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# gettext initialization
export TEXTDOMAIN='pacman-scripts'
export TEXTDOMAINDIR='@localedir@'

myver="@PACKAGE_VERSION@"

# Options
ADD=0
DELETE=0
EDITKEY=0
EXPORT=0
FINGER=0
IMPORT=0
IMPORT_TRUSTDB=0
INIT=0
KEYSERVER=''
LISTKEYS=0
LISTSIGS=0
LSIGNKEY=0
POPULATE=0
RECEIVE=0
REFRESH=0
UPDATEDB=0
VERIFY=0

DEFAULT_KEYSERVER='hkp://keys.gnupg.net'

m4_include(library/output_format.sh)

m4_include(library/parse_options.sh)

usage() {
  printf "pacman-key (pacman) %s\n" ${myver}
  echo
  printf "$(gettext "Usage: %s [options]")\n" $(basename $0)
  echo
  printf "$(gettext "Manage pacman\'s list of trusted keys")\n"
  echo
  echo "$(gettext "Options:")"
  echo "$(gettext "  -a, --add [file(s)]       Add the specified keys (empty for stdin)")"
  echo "$(gettext "  -d, --delete <keyid(s)>   Remove the specified keyids")"
  echo "$(gettext "  -e, --export [keyid(s)]   Export the specified or all keyids")"
  echo "$(gettext "  -f, --finger [keyid(s)]   List fingerprint for specified or all keyids")"
  echo "$(gettext "  -h, --help                Show this help message and exit")"
  echo "$(gettext "  -l, --list-keys [keyid(s)] List the specified or all keys")"
  echo "$(gettext "  -r, --recv-keys <keyid(s)> Fetch the specified keyids")"
  echo "$(gettext "  -u, --updatedb            Update the trustdb of pacman")"
  echo "$(gettext "  -v, --verify <signature>  Verify the file specified by the signature")"
  echo "$(gettext "  -V, --version             Show program version")"
  printf "$(gettext "  --config <file>           Use an alternate config file (instead of\n\
                            '%s')")\n" "@sysconfdir@/pacman.conf"
  echo "$(gettext "  --edit-key <keyid(s)>     Present a menu for key management task on keyids")"
  printf "$(gettext "  --gpgdir <dir>            Set an alternate directory for GnuPG (instead\n\
                            of '%s')")\n" "@sysconfdir@/pacman.d/gnupg"
  echo "$(gettext "  --import <dir(s)>         Imports pubring.gpg and trustdb.gpg from dir(s)")"
  echo "$(gettext "  --import-trustdb <dir(s)> Imports ownertrust values from trustdb.gpg in dir(s)")"
  echo "$(gettext "  --init                    Ensure the keyring is properly initialized")"
  echo "$(gettext "  --keyserver               Specify a keyserver to use if necessary")"
  echo "$(gettext "  --list-sigs [keyid(s)]    List keys and their signatures")"
  echo "$(gettext "  --lsign-key <keyid>       Locally sign the specified keyid")"
  printf "$(gettext "  --populate [keyring(s)]   Reload the default keys from the (given) keyrings\n\
                            in '%s'")\n" "@pkgdatadir@/keyrings"
  echo "$(gettext "  --refresh-keys [keyid(s)] Update specified or all keys from a keyserver")"
}

version() {
  printf "pacman-key (pacman) %s\n" "${myver}"
  printf "$(gettext "\
Copyright (c) 2010-2011 Pacman Development Team <pacman-dev@archlinux.org>.\n\
This is free software; see the source for copying conditions.\n\
There is NO WARRANTY, to the extent permitted by law.\n")"
}

# read the config file "$1" which has key=value pairs, and return the key which
# matches "$2". the equals sign between pairs may be surrounded by any amount
# of whitespace. Optionally, "$3" can be specified which is the default value
# when no key is found.
get_from() {
  while IFS='=' read -r key value; do
    [[ -z $key || ${key:0:1} = '#' ]] && continue

    if [[ ${key%% *} = "$2" && -n ${value##* } ]]; then
      echo "${value##* }"
      return 0
    fi
  done < "$1"
  if [[ -n "$3" ]]; then
    printf '%s\n' "$3"
    return 0
  fi
  return 1
}

generate_master_key() {
  # Generate the master key, which will be in both pubring and secring
  "${GPG_PACMAN[@]}" --gen-key --batch <<EOF
%echo Generating pacman keychain master key...
Key-Type: RSA
Key-Length: 2048
Key-Usage: sign
Name-Real: Pacman Keychain Master Key
Name-Email: pacman@localhost
Expire-Date: 0
%commit
%echo Done
EOF
}

secret_keys_available() {
  "${GPG_PACMAN[@]}" -K --with-colons | wc -l
}

# Adds the given gpg.conf option if it is not present in the file.
# Note that if we find it commented out, we won't add the option.
# args: $1 conffile, $2 option-name, $3 (optional) option-value
add_gpg_conf_option() {
  local conffile=$1; shift
  # looking for the option 'bare', only leading spaces or # chars allowed,
  # followed by at least one space and any other text or the end of line.
  if ! grep -q "^[[:space:]#]*$1\([[:space:]].*\)*$" "$conffile" &>/dev/null; then
    printf '%s\n' "$*" >> "$conffile"
  fi
}

initialize() {
  local conffile keyserv
  # Check for simple existence rather than for a directory as someone
  # may want to use a symlink here
  [[ -e ${PACMAN_KEYRING_DIR} ]] || mkdir -p -m 755 "${PACMAN_KEYRING_DIR}"

  # keyring files
  [[ -f ${PACMAN_KEYRING_DIR}/pubring.gpg ]] || touch ${PACMAN_KEYRING_DIR}/pubring.gpg
  [[ -f ${PACMAN_KEYRING_DIR}/secring.gpg ]] || touch ${PACMAN_KEYRING_DIR}/secring.gpg
  [[ -f ${PACMAN_KEYRING_DIR}/trustdb.gpg ]] || "${GPG_PACMAN[@]}" --update-trustdb
  chmod 644 ${PACMAN_KEYRING_DIR}/{pubring,trustdb}.gpg
  chmod 600 ${PACMAN_KEYRING_DIR}/secring.gpg

  # gpg.conf
  conffile="${PACMAN_KEYRING_DIR}/gpg.conf"
  [[ -f $conffile ]] || touch "$conffile"
  chmod 644 "$conffile"
  add_gpg_conf_option "$conffile" 'no-greeting'
  add_gpg_conf_option "$conffile" 'no-permission-warning'
  add_gpg_conf_option "$conffile" 'lock-never'
  keyserv=${KEYSERVER:-$DEFAULT_KEYSERVER}
  add_gpg_conf_option "$conffile" 'keyserver' "$keyserv"

  # set up a private signing key (if none available)
  if [[ $(secret_keys_available) -lt 1 ]]; then
    generate_master_key
    UPDATEDB=1
  fi
}

check_keyring() {
  if [[ ! -r ${PACMAN_KEYRING_DIR}/pubring.gpg || \
      ! -r ${PACMAN_KEYRING_DIR}/trustdb.gpg ]]; then
    error "$(gettext "You do not have sufficient permissions to read the %s keyring.")" "pacman"
    msg "$(gettext "Use '%s' to correct the keyring permissions.")" "pacman-key --init"
    exit 1
  fi

  if (( (EXPORT || FINGER || LIST || VERIFY) && EUID != 0 )); then
    if ! grep -q "^[[:space:]]*lock-never[[:space:]]*$" ${PACMAN_KEYRING_DIR}/gpg.conf &>/dev/null; then
      error "$(gettext "You do not have sufficient permissions to run this command.")"
      msg "$(gettext "Use '%s' to correct the keyring permissions.")" "pacman-key --init"
      exit 1
    fi
  fi

  if (( LSIGNKEY )); then
    if [[ $(secret_keys_available) -lt 1 ]]; then
      error "$(gettext "There is no secret key available to sign with.")"
      msg "$(gettext "Use '%s' to generate a default secret key.")" "pacman-key --init"
      exit 1
    fi
  fi
}

validate_with_gpg() {
  msg2 "$(gettext "Verifying %s...")" "$1"
  if [[ ! -f "$1.sig" ]]; then
    error "$(gettext "File %s is unsigned, cannot continue.")" "$1"
    return 1
  elif ! "${GPG_PACMAN[@]}" --verify "$1.sig"; then
    error "$(gettext "The signature of file %s is not valid.")" "$1"
    return 1
  fi
  return 0
}

verify_keyring_input() {
  local ret=0;
  local KEYRING_IMPORT_DIR='@pkgdatadir@/keyrings'

  # Verify signatures of keyring files and association revocation files if they exist
  msg "$(gettext "Verifying keyring file signatures...")"
  local keyring keyfile
  for keyring in "${KEYRINGIDS[@]}"; do
    keyfile="${KEYRING_IMPORT_DIR}/${keyring}.gpg"
    validate_with_gpg "${keyfile}" || ret=1

    keyfile="${KEYRING_IMPORT_DIR}/${keyring}-trusted"
    if [[ -f "${keyfile}" ]]; then
      validate_with_gpg "${keyfile}" || ret=1
    fi

    keyfile="${KEYRING_IMPORT_DIR}/${keyring}-revoked"
    if [[ -f "${keyfile}" ]]; then
      validate_with_gpg "${keyfile}" || ret=1
    fi
  done

  return $ret
}

populate_keyring() {
  local KEYRING_IMPORT_DIR='@pkgdatadir@/keyrings'

  local keyring
  local ret=0
  if [[ -z ${KEYRINGIDS[@]} ]]; then
    # get list of all available keyrings
    shopt -s nullglob
    KEYRINGIDS=("$KEYRING_IMPORT_DIR"/*.gpg)
    shopt -u nullglob
    KEYRINGIDS=("${KEYRINGIDS[@]##*/}")
    KEYRINGIDS=("${KEYRINGIDS[@]%.gpg}")
    if [[ -z ${KEYRINGIDS[@]} ]]; then
      error "$(gettext "No keyring files exist in %s.")" "$KEYRING_IMPORT_DIR"
      ret=1
    fi
  else
    # verify listed keyrings exist
    for keyring in "${KEYRINGIDS[@]}"; do
      if [[ ! -f "$KEYRING_IMPORT_DIR/$keyring.gpg" ]]; then
        error "$(gettext "The keyring file %s does not exist.")" "$KEYRING_IMPORT_DIR/$keyring.gpg"
        ret=1
      fi
    done
  fi

  if (( ret )); then
    exit 1
  fi

  verify_keyring_input || exit 1

  # Variable used for iterating on keyrings
  local key
  local key_id

  # Add keys from requested keyrings
  for keyring in "${KEYRINGIDS[@]}"; do
    msg "$(gettext "Appending keys from %s.gpg...")" "$keyring"
    "${GPG_PACMAN[@]}" --import "${KEYRING_IMPORT_DIR}/${keyring}.gpg"
  done

  # Read the trusted key IDs to an array. The conversion from whatever is inside the file
  # to key ids is important, because key ids are the only guarantee of identification
  # for the keys.
  local -A trusted_ids
  for keyring in "${KEYRINGIDS[@]}"; do
    if [[ -f "${KEYRING_IMPORT_DIR}/${keyring}-trusted" ]]; then
      while read key; do
        key_id="$("${GPG_PACMAN[@]}" --quiet --with-colons --list-key "${key}" 2>/dev/null | grep ^pub | cut -d: -f5)"
        if [[ -n ${key_id} ]]; then
          # Mark this key to be lsigned
          trusted_ids[$key_id]="${keyring}"
        fi
      done < "${KEYRING_IMPORT_DIR}/${keyring}-trusted"
    fi
  done

  if (( ${#trusted_ids[@]} > 0 )); then
    msg "$(gettext "Locally signing trusted keys in keyring...")"
    for key_id in "${!trusted_ids[@]}"; do
      msg2 "$(gettext "Locally signing key %s...")" "${key_id}"
      "${GPG_PACMAN[@]}" --quiet --lsign-key "${key_id}"
    done
  fi

  # Read the revoked key IDs to an array.
  local -A revoked_ids
  for keyring in "${KEYRINGIDS[@]}"; do
    if [[ -f "${KEYRING_IMPORT_DIR}/${keyring}-revoked" ]]; then
      while read key; do
        key_id="$("${GPG_PACMAN[@]}" --quiet --with-colons --list-key "${key}" 2>/dev/null | grep ^pub | cut -d: -f5)"
        if [[ -n ${key_id} ]]; then
          # Mark this key to be disabled
          revoked_ids[$key_id]="${keyring}"
        fi
      done < "${KEYRING_IMPORT_DIR}/${keyring}-revoked"
    fi
  done

  if (( ${#revoked_ids[@]} > 0 )); then
    msg "$(gettext "Disabling revoked keys in keyring...")"
    for key_id in "${!revoked_ids[@]}"; do
      msg2 "$(gettext "Disabling key %s...")" "${key_id}"
      printf 'disable\nquit\n' | LANG=C "${GPG_PACMAN[@]}" --command-fd 0 --quiet --batch --edit-key "${key_id}" 2>/dev/null
    done
  fi
}

edit_keys() {
  local errors=0;
  for key in "${KEYIDS[@]}"; do
    # Verify if the key exists in pacman's keyring
    if ! "${GPG_PACMAN[@]}" --list-keys "$key" &>/dev/null; then
      error "$(gettext "The key identified by %s does not exist.")" "$key"
      errors=1;
    fi
  done
  (( errors )) && exit 1;

  for key in "${KEYIDS[@]}"; do
    "${GPG_PACMAN[@]}" --edit-key "$key"
  done
}

import_trustdb() {
  local importdir
  local trustdb=$(mktemp)
  "${GPG_PACMAN[@]}" --export-ownertrust > ${trustdb}

  for importdir in "${IMPORT_DIRS[@]}"; do
    if [[ -f "${importdir}/trustdb.gpg" ]]; then
      gpg --homedir "${importdir}" --export-ownertrust >> ${trustdb}
    fi
  done

  "${GPG_PACMAN[@]}" --import-ownertrust ${trustdb}
  rm -f ${trustdb}
}

import() {
  local importdir

  # Imports public keys, then import trustdbs
  for importdir in "${IMPORT_DIRS[@]}"; do
    if [[ -f "${importdir}/pubring.gpg" ]]; then
      "${GPG_PACMAN[@]}" --quiet --batch --import "${importdir}/pubring.gpg"
    fi
  done

  import_trustdb
}

# PROGRAM START
if ! type gettext &>/dev/null; then
  gettext() {
    echo "$@"
  }
fi

OPT_SHORT="a::d:e:f::hl::r:uv:V"
OPT_LONG="add::,config:,delete:,edit-key:,export::,finger::,gpgdir:"
OPT_LONG+=",help,import:,import-trustdb:,init,keyserver:,list-keys::,list-sigs::"
OPT_LONG+=",lsign-key:,populate::,recv-keys:,refresh-keys::,updatedb"
OPT_LONG+=",verify:,version"
if ! OPT_TEMP="$(parse_options $OPT_SHORT $OPT_LONG "$@")"; then
  echo; usage; exit 1 # E_INVALID_OPTION;
fi
eval set -- "$OPT_TEMP"
unset OPT_SHORT OPT_LONG OPT_TEMP

if [[ $1 == "--" ]]; then
  usage;
  exit 0;
fi

while true; do
  case "$1" in
    -a|--add)         ADD=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYFILES=($1); UPDATEDB=1 ;;
    --config)         shift; CONFIG=$1 ;;
    -d|--delete)      DELETE=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
    --edit-key)       EDITKEY=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
    -e|--export)      EXPORT=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
    -f|--finger)      FINGER=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
    --gpgdir)         shift; PACMAN_KEYRING_DIR=$1 ;;
    --import)         IMPORT=1; shift; IMPORT_DIRS=($1); UPDATEDB=1 ;;
    --import-trustdb) IMPORT_TRUSTDB=1; shift; IMPORT_DIRS=($1); UPDATEDB=1 ;;
    --init)           INIT=1 ;;
    --keyserver)      shift; KEYSERVER=$1 ;;
    -l|--list-keys)   LISTKEYS=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
    --list-sigs)      LISTSIGS=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
    --lsign-key)      LSIGNKEY=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
    --populate)       POPULATE=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYRINGIDS=($1); UPDATEDB=1 ;;
    -r|--recv-keys)   RECEIVE=1; shift; KEYIDS=($1); UPDATEDB=1 ;;
    --refresh-keys)   REFRESH=1; [[ -n $2 && ${2:0:1} != "-" ]] && shift && KEYIDS=($1) ;;
    -u|--updatedb)    UPDATEDB=1 ;;
    -v|--verify)      VERIFY=1; shift; SIGNATURE=$1 ;;

    -h|--help)        usage; exit 0 ;;
    -V|--version)     version; exit 0 ;;

    --)               OPT_IND=0; shift; break;;
    *)                usage; exit 1 ;;
  esac
  shift
done


if ! type -p gpg >/dev/null; then
    error "$(gettext "Cannot find the %s binary required for all %s operations.")" "gpg" "pacman-key"
  exit 1
fi

if (( (ADD || DELETE || EDITKEY || IMPORT || IMPORT_TRUSTDB || INIT || LSIGNKEY || POPULATE || RECEIVE || REFRESH || UPDATEDB) && EUID != 0 )); then
  error "$(gettext "%s needs to be run as root for this operation.")" "pacman-key"
  exit 1
fi

CONFIG=${CONFIG:-@sysconfdir@/pacman.conf}
if [[ ! -r "${CONFIG}" ]]; then
  error "$(gettext "%s configuration file '%s' not found.")" "pacman" "$CONFIG"
  exit 1
fi

# if PACMAN_KEYRING_DIR isn't assigned, try to get it from the config
# file, falling back on a hard default
PACMAN_KEYRING_DIR=${PACMAN_KEYRING_DIR:-$(get_from "$CONFIG" "GPGDir" "@sysconfdir@/pacman.d/gnupg")}

GPG_PACMAN=(gpg --homedir ${PACMAN_KEYRING_DIR} --no-permission-warning)
if [[ -n ${KEYSERVER} ]]; then
  GPG_PACMAN+=(--keyserver ${KEYSERVER})
fi

# check only a single operation has been given
# don't include UPDATEDB in here as other opts can induce it
numopt=$(( ADD + DELETE + EDITKEY + EXPORT + FINGER + IMPORT + IMPORT_TRUSTDB +
    INIT + LISTKEYS + LISTSIGS + LSIGNKEY + POPULATE + RECEIVE + REFRESH + VERIFY ))

case $numopt in
  0)
    if (( ! UPDATEDB )); then
      error "$(gettext "no operation specified (use -h for help)")"
      exit 1
    fi
    ;;
  [!1])
    error "$(gettext "Multiple operations specified.")"
    msg "$(gettext "Please run %s with each operation separately.")" "pacman-key"
    exit 1
    ;;
esac

(( ! INIT )) && check_keyring

(( ADD )) && "${GPG_PACMAN[@]}" --quiet --batch --import "${KEYFILES[@]}"
(( DELETE )) && "${GPG_PACMAN[@]}" --quiet --batch --delete-key --yes "${KEYIDS[@]}"
(( EDITKEY )) && edit_keys
(( EXPORT )) && "${GPG_PACMAN[@]}" --armor --export "${KEYIDS[@]}"
(( FINGER )) && "${GPG_PACMAN[@]}" --batch --fingerprint "${KEYIDS[@]}"
(( IMPORT )) && import
(( IMPORT_TRUSTDB)) && import_trustdb
(( INIT )) && initialize
(( LISTKEYS )) && "${GPG_PACMAN[@]}" --batch --list-keys "${KEYIDS[@]}"
(( LISTSIGS )) && "${GPG_PACMAN[@]}" --batch --list-sigs "${KEYIDS[@]}"
if (( LSIGNKEY )); then
  printf 'y\ny\n' | LANG=C "${GPG_PACMAN[@]}" --command-fd 0 --quiet --batch --lsign-key "${KEYIDS[@]}" 2>/dev/null
fi
(( POPULATE )) && populate_keyring
(( RECEIVE )) && "${GPG_PACMAN[@]}" --recv-keys "${KEYIDS[@]}"
(( REFRESH )) && "${GPG_PACMAN[@]}" --refresh-keys "${KEYIDS[@]}"
(( VERIFY )) && "${GPG_PACMAN[@]}" --verify $SIGNATURE

if (( UPDATEDB )); then
  msg "$(gettext "Updating trust database...")"
  "${GPG_PACMAN[@]}" --batch --check-trustdb
fi

# vim: set ts=2 sw=2 noet: