summaryrefslogtreecommitdiff
path: root/cmdline/apt-key.in
blob: 74ca4d1351d9c9d12b0284307682586a713c2a2b (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
#!/bin/sh

set -e
unset GREP_OPTIONS

APT_DIR="/"
eval $(apt-config shell APT_DIR Dir)

MASTER_KEYRING='&keyring-master-filename;'
eval $(apt-config shell MASTER_KEYRING APT::Key::MasterKeyring)
ARCHIVE_KEYRING='&keyring-filename;'
eval $(apt-config shell ARCHIVE_KEYRING APT::Key::ArchiveKeyring)
REMOVED_KEYS='&keyring-removed-filename;'
eval $(apt-config shell REMOVED_KEYS APT::Key::RemovedKeys)
ARCHIVE_KEYRING_URI='&keyring-uri;'
eval $(apt-config shell ARCHIVE_KEYRING_URI APT::Key::ArchiveKeyringURI)
TMP_KEYRING=${APT_DIR}/var/lib/apt/keyrings/maybe-import-keyring.gpg

aptkey_echo() { echo "$@"; }

requires_root() {
	if [ "$(id -u)" -ne 0 ]; then
		echo >&2 "ERROR: This command can only be used by root."
		exit 1
	fi
}

get_fingerprints_of_keyring() {
    $GPG_CMD --keyring "$1" --with-colons --fingerprint | while read publine; do
	# search for a public key
	if [ "${publine%%:*}" != 'pub' ]; then continue; fi
	# search for the associated fingerprint (should be the very next line)
	while read fprline; do
	   if [ "${fprline%%:*}" = 'sub' ]; then break; # should never happen
	   elif [ "${fprline%%:*}" != 'fpr' ]; then continue; fi
	   echo "$fprline" | cut -d':' -f 10
	done
    done
}

add_keys_with_verify_against_master_keyring() {
    ADD_KEYRING=$1
    MASTER=$2

    if [ ! -f "$ADD_KEYRING" ]; then
	echo >&2 "ERROR: '$ADD_KEYRING' not found"
	return
    fi
    if [ ! -f "$MASTER" ]; then
	echo >&2 "ERROR: '$MASTER' not found"
	return
    fi

    # when adding new keys, make sure that the archive-master-keyring
    # is honored. so:
    #   all keys that are exported must have a valid signature
    #   from a key in the $distro-master-keyring
    add_keys="$(get_fingerprints_of_keyring "$ADD_KEYRING")"
    all_add_keys=`$GPG_CMD --keyring $ADD_KEYRING --with-colons --list-keys | grep ^[ps]ub | cut -d: -f5`
    master_keys=`$GPG_CMD --keyring $MASTER --with-colons --list-keys | grep ^pub | cut -d: -f5`

    # ensure there are no colisions LP: #857472
    for all_add_key in $all_add_keys; do
	for master_key in $master_keys; do
            if [ "$all_add_key" = "$master_key" ]; then
                echo >&2 "Keyid collision for '$all_add_key' detected, operation aborted"
                return 1
            fi
        done
    done
    
    for add_key in $add_keys; do
        # export the add keyring one-by-one
        rm -f $TMP_KEYRING
        $GPG_CMD --keyring $ADD_KEYRING --output $TMP_KEYRING --export $add_key 
        # check if signed with the master key and only add in this case
        ADDED=0
	for master_key in $master_keys; do
	    if $GPG_CMD --keyring $MASTER --keyring $TMP_KEYRING --check-sigs --with-colons $add_key | grep '^sig:!:' | cut -d: -f5 | grep -q $master_key; then
		$GPG --import $TMP_KEYRING
		ADDED=1
	    fi
	done
	if [ $ADDED = 0 ]; then
	    echo >&2 "Key '$add_key' not added. It is not signed with a master key"
	fi
    done
    rm -f $TMP_KEYRING
}

# update the current archive signing keyring from a network URI
# the archive-keyring keys needs to be signed with the master key
# (otherwise it does not make sense from a security POV)
net_update() {
    # Disabled for now as code is insecure (LP: #1013639 (and 857472, 1013128))
    APT_KEY_NET_UPDATE_ENABLED=""
    eval $(apt-config shell APT_KEY_NET_UPDATE_ENABLED APT::Key::Net-Update-Enabled)
    if [ -z "$APT_KEY_NET_UPDATE_ENABLED" ]; then
        exit 1
    fi

    if [ -z "$ARCHIVE_KEYRING_URI" ]; then
	echo >&2 "ERROR: Your distribution is not supported in net-update as no uri for the archive-keyring is set"
	exit 1
    fi
    # in theory we would need to depend on wget for this, but this feature
    # isn't useable in debian anyway as we have no keyring uri nor a master key
    if ! which wget >/dev/null 2>&1; then
	echo >&2 "ERROR: an installed wget is required for a network-based update"
	exit 1
    fi
    if [ ! -d ${APT_DIR}/var/lib/apt/keyrings ]; then
	mkdir -p ${APT_DIR}/var/lib/apt/keyrings
    fi
    keyring=${APT_DIR}/var/lib/apt/keyrings/$(basename $ARCHIVE_KEYRING_URI)
    old_mtime=0
    if [ -e $keyring ]; then
	old_mtime=$(stat -c %Y $keyring)
    fi
    (cd  ${APT_DIR}/var/lib/apt/keyrings; wget --timeout=90 -q -N $ARCHIVE_KEYRING_URI)
    if [ ! -e $keyring ]; then
	return
    fi
    new_mtime=$(stat -c %Y $keyring)
    if [ $new_mtime -ne $old_mtime ]; then
	aptkey_echo "Checking for new archive signing keys now"
	add_keys_with_verify_against_master_keyring $keyring $MASTER_KEYRING
    fi
}

update() {
    if [ ! -f $ARCHIVE_KEYRING ]; then
	echo >&2 "ERROR: Can't find the archive-keyring"
	echo >&2 "Is the &keyring-package; package installed?"
	exit 1
    fi

    # add new keys from the package;

    # we do not use add_keys_with_verify_against_master_keyring here,
    # because "update" is run on regular package updates.  A
    # attacker might as well replace the master-archive-keyring file
    # in the package and add his own keys. so this check wouldn't
    # add any security. we *need* this check on net-update though
    $GPG_CMD --quiet --batch --keyring $ARCHIVE_KEYRING --export | $GPG --import

    if [ -r "$REMOVED_KEYS" ]; then
	# remove no-longer supported/used keys
	get_fingerprints_of_keyring "$REMOVED_KEYS" | while read key; do
	    foreach_keyring_do 'remove_key_from_keyring' "$key"
	done
    else
	echo >&2 "Warning: removed keys keyring  $REMOVED_KEYS missing or not readable"
    fi
}

remove_key_from_keyring() {
    local KEYRINGFILE="$1"
    shift
    # non-existent keyrings have by definition no keys
    if [ ! -e "$KEYRINGFILE" ]; then
       return
    fi

    local GPG="$GPG_CMD --keyring $KEYRINGFILE"
    while [ -n "$1" ]; do
       local KEY="$1"
       shift
	# check if the key is in this keyring: the key id is in the 5 column at the end
	if ! get_fingerprints_of_keyring "$KEYRINGFILE" | grep -q "^[0-9A-F]*${KEY}$"; then
	    continue
	fi
	if [ ! -w "$KEYRINGFILE" ]; then
	    echo >&2 "Key ${KEY} is in keyring ${KEYRINGFILE}, but can't be removed as it is read only."
	    continue
	fi
	# check if it is the only key in the keyring and if so remove the keyring altogether
	if [ '1' = "$(get_fingerprints_of_keyring "$KEYRINGFILE" | wc -l)" ]; then
	    mv -f "$KEYRINGFILE" "${KEYRINGFILE}~" # behave like gpg
	    return
	fi
	# we can't just modify pointed to files as these might be in /usr or something
	local REALTARGET
	if [ -L "$KEYRINGFILE" ]; then
	    REALTARGET="$(readlink -f "$KEYRINGFILE")"
	    mv -f "$KEYRINGFILE" "${KEYRINGFILE}.dpkg-tmp"
	    cp -a "$REALTARGET" "$KEYRINGFILE"
	fi
	# delete the key from the keyring
	$GPG --batch --delete-key --yes "$KEY"
	if [ -n "$REALTARGET" ]; then
	    # the real backup is the old link, not the copy we made
	    mv -f "${KEYRINGFILE}.dpkg-tmp" "${KEYRINGFILE}~"
	fi
    done
}

foreach_keyring_do() {
   local ACTION="$1"
   shift
   # if a --keyring was given, just remove from there
   if [ -n "$FORCED_KEYRING" ]; then
	$ACTION "$FORCED_KEYRING" "$@"
   else
	# otherwise all known keyrings are up for inspection
	if [ -s "$TRUSTEDFILE" ]; then
	    $ACTION "$TRUSTEDFILE" "$@"
	fi
	local TRUSTEDPARTS="/etc/apt/trusted.gpg.d"
	eval $(apt-config shell TRUSTEDPARTS Dir::Etc::TrustedParts/d)
	if [ -d "$TRUSTEDPARTS" ]; then
	    # strip / suffix as gpg will double-slash in that case (#665411)
	    local STRIPPED_TRUSTEDPARTS="${TRUSTEDPARTS%/}"
	    if [ "${STRIPPED_TRUSTEDPARTS}/" = "$TRUSTEDPARTS" ]; then
		TRUSTEDPARTS="$STRIPPED_TRUSTEDPARTS"
	    fi
	    for trusted in $(run-parts --list "$TRUSTEDPARTS" --regex '^.*\.gpg$'); do
		if [ -s "$trusted" ]; then
		    $ACTION "$trusted" "$@"
		fi
	    done
	fi
   fi
}

list_keys_from_keyring() {
    local KEYRINGFILE="$1"
    shift
    # don't show the error message if this keyring doesn't include the key
    $GPG_CMD --keyring "$KEYRINGFILE" --batch --list-keys "$@" 2>/dev/null || true
}

fingerprint_keys_from_keyring() {
    local KEYRINGFILE="$1"
    shift
    # don't show the error message if this keyring doesn't include the fingerprint
    $GPG_CMD --keyring "$KEYRINGFILE" --batch --fingerprint "$@" 2>/dev/null || true
}

import_keys_from_keyring() {
    local IMPORT="$1"
    local KEYRINGFILE="$2"
    $GPG_CMD --keyring "$KEYRINGFILE" --batch --import "$IMPORT" >/dev/null 2>&1
}

setup_merged_keyring() {
    if [ -z "$FORCED_KEYRING" ]; then
	local TRUSTEDFILE_BAK="$TRUSTEDFILE"
	TRUSTEDFILE='/dev/null'
	foreach_keyring_do 'import_keys_from_keyring' "${GPGHOMEDIR}/pubring.gpg"
	TRUSTEDFILE="$TRUSTEDFILE_BAK"
	# mark it as non-writeable so users get errors if gnupg tries to modify it
	if [ -s "${GPGHOMEDIR}/pubring.gpg" ]; then
	    chmod -w "${GPGHOMEDIR}/pubring.gpg"
	    GPG="$GPG --keyring ${GPGHOMEDIR}/pubring.gpg"
	fi
    fi
    if [ -r "$TRUSTEDFILE" ]; then
	GPG="$GPG --keyring $TRUSTEDFILE --primary-keyring $TRUSTEDFILE"
    fi
}


usage() {
    echo "Usage: apt-key [--keyring file] [command] [arguments]"
    echo
    echo "Manage apt's list of trusted keys"
    echo
    echo "  apt-key add <file>          - add the key contained in <file> ('-' for stdin)"
    echo "  apt-key del <keyid>         - remove the key <keyid>"
    echo "  apt-key export <keyid>      - output the key <keyid>"
    echo "  apt-key exportall           - output all trusted keys"
    echo "  apt-key update              - update keys using the keyring package"
    echo "  apt-key net-update          - update keys using the network"
    echo "  apt-key list                - list keys"
    echo "  apt-key finger              - list fingerprints"
    echo "  apt-key adv                 - pass advanced options to gpg (download key)"
    echo
    echo "If no specific keyring file is given the command applies to all keyring files."
}

while [ -n "$1" ]; do
   case "$1" in
      --keyring)
	 shift
	 TRUSTEDFILE="$1"
	 FORCED_KEYRING="$1"
	 shift
	 ;;
      --fakeroot)
	 requires_root() { true; }
	 shift
	 ;;
      --quiet)
	 aptkey_echo() { true; }
	 shift
	 ;;
      --*)
	 echo >&2 "Unknown option: $1"
	 usage
	 exit 1;;
      *)
	 break;;
   esac
done

if [ -z "$TRUSTEDFILE" ]; then
   TRUSTEDFILE="/etc/apt/trusted.gpg"
   eval $(apt-config shell TRUSTEDFILE Apt::GPGV::TrustedKeyring)
   eval $(apt-config shell TRUSTEDFILE Dir::Etc::Trusted/f)
fi

command="$1"
if [ -z "$command" ]; then
    usage
    exit 1
fi
shift

if [ "$command" != "help" ]; then
    eval $(apt-config shell GPG_EXE Apt::Key::gpgcommand)

    if [ -n "$GPG_EXE" ] && which "$GPG_EXE" >/dev/null 2>&1; then
	true
    elif which gpg >/dev/null 2>&1; then
	GPG_EXE="gpg"
    elif which gpg2 >/dev/null 2>&1; then
	GPG_EXE="gpg2"
    else
	echo >&2 "Error: gnupg or gnupg2 do not seem to be installed,"
	echo >&2 "Error: but apt-key requires gnupg or gnupg2 for operation."
	echo >&2
	exit 255
    fi

    GPG_CMD="$GPG_EXE --ignore-time-conflict --no-options --no-default-keyring"

    # gpg needs (in different versions more or less) files to function correctly,
    # so we give it its own homedir and generate some valid content for it
    GPGHOMEDIR="$(mktemp -d)"
    CURRENTTRAP="${CURRENTTRAP} rm -rf '${GPGHOMEDIR}';"
    trap "${CURRENTTRAP}" 0 HUP INT QUIT ILL ABRT FPE SEGV PIPE TERM
    chmod 700 "$GPGHOMEDIR"
    # We don't use a secret keyring, of course, but gpg panics and
    # implodes if there isn't one available - and writeable for imports
    SECRETKEYRING="${GPGHOMEDIR}/secring.gpg"
    touch $SECRETKEYRING
    GPG_CMD="$GPG_CMD --homedir $GPGHOMEDIR"
    # create the trustdb with an (empty) dummy keyring
    # older gpgs required it, newer gpgs even warn that it isn't needed,
    # but require it nonetheless for some commands, so we just play safe
    # here for the foreseeable future and create a dummy one
    $GPG_CMD --quiet --check-trustdb --keyring $SECRETKEYRING >/dev/null 2>&1
    # tell gpg that it shouldn't try to maintain a trustdb file
    GPG_CMD="$GPG_CMD --no-auto-check-trustdb --trust-model always"
    GPG="$GPG_CMD"

    # gpg defaults to mode 0600 for new keyrings. Create one with 0644 instead.
    if ! [ -e "$TRUSTEDFILE" ]; then
	if [ -w "$(dirname "$TRUSTEDFILE")" ]; then
	   touch -- "$TRUSTEDFILE"
	   chmod 0644 -- "$TRUSTEDFILE"
	fi
    fi
fi

case "$command" in
    add)
	requires_root
	setup_merged_keyring
	$GPG --quiet --batch --import "$@"
	aptkey_echo "OK"
        ;;
    del|rm|remove)
	requires_root
	foreach_keyring_do 'remove_key_from_keyring' "$@"
	aptkey_echo "OK"
        ;;
    update)
	requires_root
	setup_merged_keyring
	update
	;;
    net-update)
	requires_root
	setup_merged_keyring
	net_update
	;;
    list)
	foreach_keyring_do 'list_keys_from_keyring' "$@"
	;;
    finger*)
	foreach_keyring_do 'fingerprint_keys_from_keyring' "$@"
	;;
    export|exportall)
	foreach_keyring_do 'import_keys_from_keyring' "${GPGHOMEDIR}/pubring.gpg"
	$GPG_CMD --keyring "${GPGHOMEDIR}/pubring.gpg" --armor --export "$@"
	;;
    adv*)
	setup_merged_keyring
	aptkey_echo "Executing: $GPG $*"
	$GPG "$@"
	;;
    help)
        usage
        ;;
    *)
        usage
        exit 1
        ;;
esac