Debian Codegraph @

contrib/ssh-copy-id

raw
1 #!/bin/sh
2
3 # Copyright (c) 1999-2025 Philip Hands <[email protected]>
4 # 2025 Denis Ovsienko <[email protected]>
5 # 2024 Frank Fischer <[email protected]>
6 # 2021 Carlos Rodríguez Gili <[email protected]>
7 # 2020 Matthias Blümel <[email protected]>
8 # 2017 Sebastien Boyron <[email protected]>
9 # 2013 Martin Kletzander <[email protected]>
10 # 2010 Adeodato =?iso-8859-1?Q?Sim=F3?= <[email protected]>
11 # 2010 Eric Moret
12 # 2009 Xr <[email protected]>
13 # 2007 Justin Pryzby <[email protected]>
14 # 2004 Reini Urban <[email protected]>
15 # 2003 Colin Watson <[email protected]>
16 # All rights reserved.
17 #
18 # Redistribution and use in source and binary forms, with or without
19 # modification, are permitted provided that the following conditions
20 # are met:
21 # 1. Redistributions of source code must retain the above copyright
22 # notice, this list of conditions and the following disclaimer.
23 # 2. Redistributions in binary form must reproduce the above copyright
24 # notice, this list of conditions and the following disclaimer in the
25 # documentation and/or other materials provided with the distribution.
26 #
27 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
38 # Shell script to install your public key(s) on a remote machine
39 # See the ssh-copy-id(1) man page for details
40
41 # shellcheck shell=dash
42
43 # check that we have something mildly sane as our shell, or try to find something better
44 if false ^ printf "%s: WARNING: ancient shell, hunting for a more modern one... " "$0"
45 then
46 SANE_SH=${SANE_SH:-/usr/bin/ksh}
47 if printf 'true ^ false\n' | "$SANE_SH"
48 then
49 printf "'%s' seems viable.\\n" "$SANE_SH"
50 exec "$SANE_SH" "$0" "$@"
51 else
52 cat <<-EOF
53 oh dear.
54
55 If you have a more recent shell available, that supports \$(...) etc.
56 please try setting the environment variable SANE_SH to the path of that
57 shell, and then retry running this script. If that works, please report
58 a bug describing your setup, and the shell you used to make it work.
59
60 EOF
61 printf '%s: ERROR: Less dimwitted shell required.\n' "$0" >&2
62 exit 1
63 fi
64 fi
65
66 # shellcheck disable=SC2010
67 DEFAULT_PUB_ID_FILE=$(ls -dt "${HOME}"/.ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)
68 SSH="ssh -a -x"
69 TARGET_PATH=".ssh/authorized_keys"
70 umask 0177
71
72 usage () {
73 printf 'Usage: %s [-h|-?|-f|-n|-s|-x] [-i [identity_file]] [-t target_path] [-F ssh_config] [[-o ssh_option] ...] [-p port] [user@]hostname\n' "$0" >&2
74 printf '\t-f: force mode -- copy keys without trying to check if they are already installed\n' >&2
75 printf '\t-n: dry run -- no keys are actually copied\n' >&2
76 printf '\t-s: use sftp -- use sftp instead of executing remote-commands. Can be useful if the remote only allows sftp\n' >&2
77 printf '\t-x: debug -- enables -x in this shell, for debugging\n' >&2
78 printf '\t-h|-?: print this help\n' >&2
79 exit 1
80 }
81
82 # escape any single quotes in an argument
83 quote() {
84 printf '%s\n' "$1" | sed -e "s/'/'\\\\''/g"
85 }
86
87 use_id_file() {
88 L_ID_FILE="$1"
89
90 if [ -z "$L_ID_FILE" ] ; then
91 printf '%s: ERROR: no ID file found\n' "$0" >&2
92 exit 1
93 fi
94
95 if expr "$L_ID_FILE" : '.*\.pub$' >/dev/null ; then
96 PUB_ID_FILE="$L_ID_FILE"
97 else
98 PUB_ID_FILE="$L_ID_FILE.pub"
99 fi
100
101 [ "$FORCED" ] || PRIV_ID_FILE=$(dirname "$PUB_ID_FILE")/$(basename "$PUB_ID_FILE" .pub)
102
103 # check that the files are readable
104 for f in "$PUB_ID_FILE" ${PRIV_ID_FILE:+"$PRIV_ID_FILE"} ; do
105 ErrMSG=$( { : < "$f" ; } 2>&1 ) || {
106 L_PRIVMSG=""
107 [ "$f" = "$PRIV_ID_FILE" ] && L_PRIVMSG=" (to install the contents of '$PUB_ID_FILE' anyway, look at the -f option)"
108 printf "\\n%s: ERROR: failed to open ID file '%s': %s\\n" "$0" "$f" "$(printf '%s\n%s\n' "$ErrMSG" "$L_PRIVMSG" | sed -e 's/.*: *//')" >&2
109 exit 1
110 }
111 done
112 GET_ID="cat \"$PUB_ID_FILE\""
113 }
114
115 if [ -n "$SSH_AUTH_SOCK" ] && ssh-add -L >/dev/null 2>&1 ; then
116 GET_ID="ssh-add -L"
117 fi
118
119 OPTS="io:p:F:t:fnsxh?"
120
121 while getopts "$OPTS" OPT
122 do
123 case "$OPT" in
124 i)
125 [ "${SEEN_OPT_I}" ] && {
126 printf '\n%s: ERROR: -i option must not be specified more than once\n\n' "$0" >&2
127 usage
128 }
129 SEEN_OPT_I="yes"
130
131 # Check for -i's optional parameter
132 eval "nextarg=\${$OPTIND}"
133 # shellcheck disable=SC2154
134 if [ $OPTIND = $# ]; then
135 if [ -r "$nextarg" ] && grep -iq ssh "$nextarg"; then
136 printf '\n%s: ERROR: Missing hostname. Use "-i -- %s" if you really mean to use this as the hostname\n\n' "$0" "$nextarg" >&2
137 usage
138 fi
139 elif ! expr -- "$nextarg" : "-[$(echo "$OPTS" | tr -d :)-]" >/dev/null ; then
140 # when not at the last arg, and not followed by an option, -i has an argument
141 OPTARG="$nextarg"
142 OPTIND=$((OPTIND + 1))
143 fi
144 use_id_file "${OPTARG:-$DEFAULT_PUB_ID_FILE}"
145 ;;
146 o|F)
147 OPTS_oF="${OPTS_oF:+$OPTS_oF }-$OPT '$(quote "${OPTARG}")'"
148 ;;
149 f)
150 FORCED=1
151 ;;
152 n)
153 DRY_RUN=1
154 ;;
155 p)
156 SSH_PORT=${OPTARG}
157 ;;
158 s)
159 SFTP=sftp
160 ;;
161 t)
162 TARGET_PATH="${OPTARG}"
163 ;;
164 x)
165 SET_X="set -x;"
166 set -x
167 ;;
168 h|\?)
169 usage
170 ;;
171 esac
172 done
173 #shift all args to keep only USER_HOST
174 shift $((OPTIND-1))
175
176 if [ $# = 0 ] ; then
177 usage
178 fi
179 if [ $# != 1 ] ; then
180 printf '%s: ERROR: Too many arguments. Expecting a target hostname, got: %s\n\n' "$0" "$SAVEARGS" >&2
181 usage
182 fi
183
184 USER_HOST="$*"
185 # tack the hostname onto SSH_OPTS
186 OPTS_USER_HOST="${OPTS_oF:+$OPTS_oF }'$(quote "$USER_HOST")'"
187 SSH_OPTS="${SSH_PORT:+-p $SSH_PORT }$OPTS_USER_HOST"
188 # and populate "$@" for later use (only way to get proper quoting of options)
189 eval set -- "$SSH_OPTS"
190
191 # shellcheck disable=SC2086
192 if [ -z "$(eval $GET_ID)" ] && [ -r "${PUB_ID_FILE:=$DEFAULT_PUB_ID_FILE}" ] ; then
193 use_id_file "$PUB_ID_FILE"
194 fi
195
196 printf '%s: INFO: Source of key(s) to be installed: %s\n' "$0" "${GET_ID#cat }" >&2
197
198 # shellcheck disable=SC2086
199 if [ -z "$(eval $GET_ID)" ] ; then
200 printf '%s: ERROR: No identities found\n' "$0" >&2
201 exit 1
202 fi
203
204 # assert_scratch_ok()
205 # ensures that $SCRATCH_DIR is setup.
206 assert_scratch_ok() {
207 [ "$SCRATCH_DIR" ] && [ -d "$SCRATCH_DIR" ] && [ -w "$SCRATCH_DIR" ] && return 0
208
209 printf 'ERROR: Assertion failure: in %s(): scratch_dir was not correctly set up (SCRATCH_DIR = "%s")\n' "$1" "$SCRATCH_DIR" >&2
210 return 1
211 }
212
213 # filter_ids()
214 # tries to log in using the keys piped to it, and filters out any that work
215 filter_ids() {
216 L_SUCCESS="$1"
217 assert_scratch_ok filter_ids || return
218 L_TMP_ID_FILE="$SCRATCH_DIR"/popids_tmp_id
219 L_OUTPUT_FILE="$SCRATCH_DIR"/popids_output
220
221 # repopulate "$@" inside this function
222 eval set -- "$SSH_OPTS"
223
224 while read -r ID || [ "$ID" ] ; do
225 printf '%s\n' "$ID" > "$L_TMP_ID_FILE"
226
227 # the next line assumes $PRIV_ID_FILE only set if using a single id file - this
228 # assumption will break if we implement the possibility of multiple -i options.
229 # The point being that if file based, ssh needs the private key, which it cannot
230 # find if only given the contents of the .pub file in an unrelated tmpfile
231 $SSH -i "${PRIV_ID_FILE:-$L_TMP_ID_FILE}" \
232 -o ControlPath=none \
233 -o LogLevel=INFO \
234 -o PreferredAuthentications=publickey \
235 -o IdentitiesOnly=yes "$@" exit >"$L_OUTPUT_FILE" 2>&1 </dev/null
236 if [ "$?" = "$L_SUCCESS" ] || {
237 [ "$SFTP" ] && grep 'allows sftp connections only' "$L_OUTPUT_FILE" >/dev/null
238 # this error counts as a success if we're setting up an sftp connection
239 }
240 then
241 : > "$L_TMP_ID_FILE"
242 else
243 grep 'Permission denied' "$L_OUTPUT_FILE" >/dev/null || {
244 sed -e 's/^/ERROR: /' <"$L_OUTPUT_FILE" >"$L_TMP_ID_FILE"
245 cat >/dev/null #consume the other keys, causing loop to end
246 }
247 fi
248
249 cat "$L_TMP_ID_FILE"
250 done
251 }
252
253 # populate_new_ids() uses several global variables ($USER_HOST, $SSH_OPTS ...)
254 # and has the side effect of setting $NEW_IDS
255 populate_new_ids() {
256 if [ "$FORCED" ] ; then
257 # shellcheck disable=SC2086
258 NEW_IDS=$(eval $GET_ID)
259 return
260 fi
261
262 printf '%s: INFO: attempting to log in with the new key(s), to filter out any that are already installed\n' "$0" >&2
263 # shellcheck disable=SC2086
264 NEW_IDS=$(eval $GET_ID | filter_ids $1)
265
266 if expr "$NEW_IDS" : "^ERROR: " >/dev/null ; then
267 printf '\n%s: %s\n\n' "$0" "$NEW_IDS" >&2
268 exit 1
269 fi
270 if [ -z "$NEW_IDS" ] ; then
271 printf '\n%s: WARNING: All keys were skipped because they already exist on the remote system.\n' "$0" >&2
272 printf '\t\t(if you think this is a mistake, you may want to use -f option)\n\n' >&2
273 exit 0
274 fi
275 printf '%s: INFO: %d key(s) remain to be installed -- if you are prompted now it is to install the new keys\n' "$0" "$(printf '%s\n' "$NEW_IDS" | wc -l)" >&2
276 }
277
278 # installkey_sh [target_path]
279 # produce a one-liner to add the keys to remote $TARGET_PATH
280 installkeys_sh() {
281 # In setting INSTALLKEYS_SH:
282 # the tr puts it all on one line (to placate tcsh)
283 # (hence the excessive use of semi-colons (;) )
284 # then in the command:
285 # cd to be at $HOME, just in case;
286 # the -z `tail ...` checks for a trailing newline. The echo adds one if was missing
287 # the cat adds the keys we're getting via STDIN
288 # and if available restorecon is used to restore the SELinux context
289 # OpenWrt has a special case for root/UID:0. Haiku is also special.
290 INSTALLKEYS_SH=$(tr -s '\t\n' ' ' <<-EOF
291 $SET_X
292 cd;
293 umask 077;
294 AUTH_KEY_FILE="${TARGET_PATH}";
295 [ -f /etc/openwrt_release ] &&
296 { [ "\$LOGNAME" = "root" ] || [ "\$(id -u)" = "0" ]; } &&
297 AUTH_KEY_FILE=/etc/dropbear/authorized_keys;
298 [ "\`uname -s\`" = "Haiku" ] &&
299 AUTH_KEY_FILE=config/settings/ssh/authorized_keys;
300 AUTH_KEY_DIR=\`dirname "\${AUTH_KEY_FILE}"\`;
301 mkdir -p "\${AUTH_KEY_DIR}" &&
302 { [ -z "\`tail -1c "\${AUTH_KEY_FILE}" 2>/dev/null\`" ] ||
303 echo >> "\${AUTH_KEY_FILE}" || exit 1; } &&
304 cat >> "\${AUTH_KEY_FILE}" || exit 1;
305 if type restorecon >/dev/null 2>&1; then
306 restorecon -F "\${AUTH_KEY_DIR}" "\${AUTH_KEY_FILE}";
307 fi
308 EOF
309 )
310
311 # to defend against quirky remote shells: use 'exec sh -c' to get POSIX;
312 printf "exec sh -c '%s'" "${INSTALLKEYS_SH}"
313 }
314
315 #shellcheck disable=SC2120 # the 'eval set' confuses this
316 installkeys_via_sftp() {
317 AUTH_KEY_FILE=${TARGET_PATH}
318 AUTH_KEY_DIR=$(dirname "${AUTH_KEY_FILE}")
319
320 # repopulate "$@" inside this function
321 eval set -- "$SSH_OPTS"
322
323 assert_scratch_ok installkeys_via_sftp || return 1
324 L_KEYS="$SCRATCH_DIR"/authorized_keys
325 L_SHARED_CON="$SCRATCH_DIR"/master-conn
326 $SSH -f -N -M -S "$L_SHARED_CON" "$@"
327 L_CLEANUP="$SSH -S '$L_SHARED_CON' -O exit 'ignored' >/dev/null 2>&1 ; $SCRATCH_CLEANUP"
328 #shellcheck disable=SC2064
329 trap "$L_CLEANUP" EXIT TERM INT QUIT
330 sftp -b - -o "ControlPath='$L_SHARED_CON'" "ignored" <<-EOF || return 1
331 -get "$AUTH_KEY_FILE" "$L_KEYS"
332 EOF
333 # add a newline or create file if it's missing, same like above
334 [ -z "$(tail -1c "$L_KEYS" 2>/dev/null)" ] || echo >> "$L_KEYS"
335 # append the keys being piped in here
336 cat >> "$L_KEYS"
337 sftp -b - -o "ControlPath='$L_SHARED_CON'" "ignored" <<-EOF || return 1
338 -mkdir "$AUTH_KEY_DIR"
339 chmod 700 "$AUTH_KEY_DIR"
340 put "$L_KEYS" "$AUTH_KEY_FILE"
341 chmod 600 "$AUTH_KEY_FILE"
342 EOF
343 #shellcheck disable=SC2064
344 eval "$L_CLEANUP" && trap "$SCRATCH_CLEANUP" EXIT TERM INT QUIT
345 }
346
347
348 # create a scratch dir for any temporary files needed
349 if SCRATCH_DIR=$(mktemp -d ~/.ssh/ssh-copy-id.XXXXXXXXXX) &&
350 [ "$SCRATCH_DIR" ] && [ -d "$SCRATCH_DIR" ]
351 then
352 chmod 0700 "$SCRATCH_DIR"
353 SCRATCH_CLEANUP="rm -rf \"$SCRATCH_DIR\""
354 #shellcheck disable=SC2064
355 trap "$SCRATCH_CLEANUP" EXIT TERM INT QUIT
356 else
357 printf '%s: ERROR: failed to create required temporary directory under ~/.ssh (HOME="%s")\n' "$0" "$HOME" >&2
358 exit 1
359 fi
360
361 REMOTE_VERSION=$($SSH -v -o PreferredAuthentications=',' -o ControlPath=none "$@" 2>&1 |
362 sed -ne 's/.*remote software version //p')
363
364 # shellcheck disable=SC2029
365 case "$REMOTE_VERSION" in
366 NetScreen*)
367 populate_new_ids 1
368 for KEY in $(printf "%s" "$NEW_IDS" | cut -d' ' -f2) ; do
369 KEY_NO=$((KEY_NO + 1))
370 printf '%s\n' "$KEY" | grep ssh-dss >/dev/null || {
371 printf '%s: WARNING: Non-dsa key (#%d) skipped (NetScreen only supports DSA keys)\n' "$0" "$KEY_NO" >&2
372 continue
373 }
374 [ "$DRY_RUN" ] || printf 'set ssh pka-dsa key %s\nsave\nexit\n' "$KEY" | $SSH -T "$@" >/dev/null 2>&1
375 if [ $? = 255 ] ; then
376 printf '%s: ERROR: installation of key #%d failed (please report a bug describing what caused this, so that we can make this message useful)\n' "$0" "$KEY_NO" >&2
377 else
378 ADDED=$((ADDED + 1))
379 fi
380 done
381 if [ -z "$ADDED" ] ; then
382 exit 1
383 fi
384 ;;
385 *)
386 # Assuming that the remote host treats $TARGET_PATH as one might expect
387 populate_new_ids 0
388 if ! [ "$DRY_RUN" ] ; then
389 printf '%s\n' "$NEW_IDS" | \
390 if [ "$SFTP" ] ; then
391 #shellcheck disable=SC2119
392 installkeys_via_sftp
393 else
394 $SSH "$@" "$(installkeys_sh)"
395 fi || exit 1
396 fi
397 ADDED=$(printf '%s\n' "$NEW_IDS" | wc -l)
398 ;;
399 esac
400
401 if [ "$DRY_RUN" ] ; then
402 cat <<-EOF
403 =-=-=-=-=-=-=-=
404 Would have added the following key(s):
405
406 $NEW_IDS
407 =-=-=-=-=-=-=-=
408 EOF
409 else
410 [ -z "$SFTP" ] || PORT_OPT=P
411 cat <<-EOF
412
413 Number of key(s) added: $ADDED
414
415 Now try logging into the machine, with: "${SFTP:-ssh} ${SEEN_OPT_I:+-i${PRIV_ID_FILE:+ $PRIV_ID_FILE} }${SSH_PORT:+-${PORT_OPT:-p} $SSH_PORT }${OPTS_USER_HOST}"
416 and check to make sure that only the key(s) you wanted were added.
417
418 EOF
419 fi
420
421 # =-=-=-=