1#!/bin/sh
2
3# Copyright (c) 1999-2016 Philip Hands <phil@hands.com>
4#               2013 Martin Kletzander <mkletzan@redhat.com>
5#               2010 Adeodato =?iso-8859-1?Q?Sim=F3?= <asp16@alu.ua.es>
6#               2010 Eric Moret <eric.moret@gmail.com>
7#               2009 Xr <xr@i-jeuxvideo.com>
8#               2007 Justin Pryzby <justinpryzby@users.sourceforge.net>
9#               2004 Reini Urban <rurban@x-ray.at>
10#               2003 Colin Watson <cjwatson@debian.org>
11# All rights reserved.
12#
13# Redistribution and use in source and binary forms, with or without
14# modification, are permitted provided that the following conditions
15# are met:
16# 1. Redistributions of source code must retain the above copyright
17#    notice, this list of conditions and the following disclaimer.
18# 2. Redistributions in binary form must reproduce the above copyright
19#    notice, this list of conditions and the following disclaimer in the
20#    documentation and/or other materials provided with the distribution.
21#
22# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33# Shell script to install your public key(s) on a remote machine
34# See the ssh-copy-id(1) man page for details
35
36# check that we have something mildly sane as our shell, or try to find something better
37if false ^ printf "%s: WARNING: ancient shell, hunting for a more modern one... " "$0"
38then
39  SANE_SH=${SANE_SH:-/usr/bin/ksh}
40  if printf 'true ^ false\n' | "$SANE_SH"
41  then
42    printf "'%s' seems viable.\n" "$SANE_SH"
43    exec "$SANE_SH" "$0" "$@"
44  else
45    cat <<-EOF
46	oh dear.
47
48	  If you have a more recent shell available, that supports \$(...) etc.
49	  please try setting the environment variable SANE_SH to the path of that
50	  shell, and then retry running this script. If that works, please report
51	  a bug describing your setup, and the shell you used to make it work.
52
53	EOF
54    printf "%s: ERROR: Less dimwitted shell required.\n" "$0"
55    exit 1
56  fi
57fi
58
59most_recent_id="$(cd "$HOME" ; ls -t .ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)"
60DEFAULT_PUB_ID_FILE="${most_recent_id:+$HOME/}$most_recent_id"
61
62usage () {
63  printf 'Usage: %s [-h|-?|-f|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname\n' "$0" >&2
64  printf '\t-f: force mode -- copy keys without trying to check if they are already installed\n' >&2
65  printf '\t-n: dry run    -- no keys are actually copied\n' >&2
66  printf '\t-h|-?: print this help\n' >&2
67  exit 1
68}
69
70# escape any single quotes in an argument
71quote() {
72  printf "%s\n" "$1" | sed -e "s/'/'\\\\''/g"
73}
74
75use_id_file() {
76  local L_ID_FILE="$1"
77
78  if [ -z "$L_ID_FILE" ] ; then
79    printf "%s: ERROR: no ID file found\n" "$0"
80    exit 1
81  fi
82
83  if expr "$L_ID_FILE" : ".*\.pub$" >/dev/null ; then
84    PUB_ID_FILE="$L_ID_FILE"
85  else
86    PUB_ID_FILE="$L_ID_FILE.pub"
87  fi
88
89  [ "$FORCED" ] || PRIV_ID_FILE=$(dirname "$PUB_ID_FILE")/$(basename "$PUB_ID_FILE" .pub)
90
91  # check that the files are readable
92  for f in "$PUB_ID_FILE" ${PRIV_ID_FILE:+"$PRIV_ID_FILE"} ; do
93    ErrMSG=$( { : < "$f" ; } 2>&1 ) || {
94      local L_PRIVMSG=""
95      [ "$f" = "$PRIV_ID_FILE" ] && L_PRIVMSG="	(to install the contents of '$PUB_ID_FILE' anyway, look at the -f option)"
96      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/.*: *//')"
97      exit 1
98    }
99  done
100  printf '%s: INFO: Source of key(s) to be installed: "%s"\n' "$0" "$PUB_ID_FILE" >&2
101  GET_ID="cat \"$PUB_ID_FILE\""
102}
103
104if [ -n "$SSH_AUTH_SOCK" ] && ssh-add -L >/dev/null 2>&1 ; then
105  GET_ID="ssh-add -L"
106fi
107
108while test "$#" -gt 0
109do
110  [ "${SEEN_OPT_I}" ] && expr "$1" : "[-]i" >/dev/null && {
111        printf "\n%s: ERROR: -i option must not be specified more than once\n\n" "$0"
112        usage
113  }
114
115  OPT= OPTARG=
116  # implement something like getopt to avoid Solaris pain
117  case "$1" in
118    -i?*|-o?*|-p?*)
119      OPT="$(printf -- "$1"|cut -c1-2)"
120      OPTARG="$(printf -- "$1"|cut -c3-)"
121      shift
122      ;;
123    -o|-p)
124      OPT="$1"
125      OPTARG="$2"
126      shift 2
127      ;;
128    -i)
129      OPT="$1"
130      test "$#" -le 2 || expr "$2" : "[-]" >/dev/null || {
131        OPTARG="$2"
132        shift
133      }
134      shift
135      ;;
136    -f|-n|-h|-\?)
137      OPT="$1"
138      OPTARG=
139      shift
140      ;;
141    --)
142      shift
143      while test "$#" -gt 0
144      do
145        SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
146        shift
147      done
148      break
149      ;;
150    -*)
151      printf "\n%s: ERROR: invalid option (%s)\n\n" "$0" "$1"
152      usage
153      ;;
154    *)
155      SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
156      shift
157      continue
158      ;;
159  esac
160
161  case "$OPT" in
162    -i)
163      SEEN_OPT_I="yes"
164      use_id_file "${OPTARG:-$DEFAULT_PUB_ID_FILE}"
165      ;;
166    -o|-p)
167      SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }$OPT '$(quote "$OPTARG")'"
168      ;;
169    -f)
170      FORCED=1
171      ;;
172    -n)
173      DRY_RUN=1
174      ;;
175    -h|-\?)
176      usage
177      ;;
178  esac
179done
180
181eval set -- "$SAVEARGS"
182
183if [ $# = 0 ] ; then
184  usage
185fi
186if [ $# != 1 ] ; then
187  printf '%s: ERROR: Too many arguments.  Expecting a target hostname, got: %s\n\n' "$0" "$SAVEARGS" >&2
188  usage
189fi
190
191# drop trailing colon
192USER_HOST=$(printf "%s\n" "$1" | sed 's/:$//')
193# tack the hostname onto SSH_OPTS
194SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }'$(quote "$USER_HOST")'"
195# and populate "$@" for later use (only way to get proper quoting of options)
196eval set -- "$SSH_OPTS"
197
198if [ -z "$(eval $GET_ID)" ] && [ -r "${PUB_ID_FILE:=$DEFAULT_PUB_ID_FILE}" ] ; then
199  use_id_file "$PUB_ID_FILE"
200fi
201
202if [ -z "$(eval $GET_ID)" ] ; then
203  printf '%s: ERROR: No identities found\n' "$0" >&2
204  exit 1
205fi
206
207# populate_new_ids() uses several global variables ($USER_HOST, $SSH_OPTS ...)
208# and has the side effect of setting $NEW_IDS
209populate_new_ids() {
210  local L_SUCCESS="$1"
211
212  if [ "$FORCED" ] ; then
213    NEW_IDS=$(eval $GET_ID)
214    return
215  fi
216
217  # repopulate "$@" inside this function
218  eval set -- "$SSH_OPTS"
219
220  umask 0177
221  local L_TMP_ID_FILE=$(mktemp ~/.ssh/ssh-copy-id_id.XXXXXXXXXX)
222  if test $? -ne 0 || test "x$L_TMP_ID_FILE" = "x" ; then
223    printf '%s: ERROR: mktemp failed\n' "$0" >&2
224    exit 1
225  fi
226  local L_CLEANUP="rm -f \"$L_TMP_ID_FILE\" \"${L_TMP_ID_FILE}.stderr\""
227  trap "$L_CLEANUP" EXIT TERM INT QUIT
228  printf '%s: INFO: attempting to log in with the new key(s), to filter out any that are already installed\n' "$0" >&2
229  NEW_IDS=$(
230    eval $GET_ID | {
231      while read ID || [ "$ID" ] ; do
232        printf '%s\n' "$ID" > "$L_TMP_ID_FILE"
233
234        # the next line assumes $PRIV_ID_FILE only set if using a single id file - this
235        # assumption will break if we implement the possibility of multiple -i options.
236        # The point being that if file based, ssh needs the private key, which it cannot
237        # find if only given the contents of the .pub file in an unrelated tmpfile
238        ssh -i "${PRIV_ID_FILE:-$L_TMP_ID_FILE}" \
239            -o ControlPath=none \
240            -o LogLevel=INFO \
241            -o PreferredAuthentications=publickey \
242            -o IdentitiesOnly=yes "$@" exit 2>"$L_TMP_ID_FILE.stderr" </dev/null
243        if [ "$?" = "$L_SUCCESS" ] ; then
244          : > "$L_TMP_ID_FILE"
245        else
246          grep 'Permission denied' "$L_TMP_ID_FILE.stderr" >/dev/null || {
247            sed -e 's/^/ERROR: /' <"$L_TMP_ID_FILE.stderr" >"$L_TMP_ID_FILE"
248            cat >/dev/null #consume the other keys, causing loop to end
249          }
250        fi
251
252        cat "$L_TMP_ID_FILE"
253      done
254    }
255  )
256  eval "$L_CLEANUP" && trap - EXIT TERM INT QUIT
257
258  if expr "$NEW_IDS" : "^ERROR: " >/dev/null ; then
259    printf '\n%s: %s\n\n' "$0" "$NEW_IDS" >&2
260    exit 1
261  fi
262  if [ -z "$NEW_IDS" ] ; then
263    printf '\n%s: WARNING: All keys were skipped because they already exist on the remote system.\n' "$0" >&2
264    printf '\t\t(if you think this is a mistake, you may want to use -f option)\n\n' "$0" >&2
265    exit 0
266  fi
267  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
268}
269
270REMOTE_VERSION=$(ssh -v -o PreferredAuthentications=',' -o ControlPath=none "$@" 2>&1 |
271                 sed -ne 's/.*remote software version //p')
272
273case "$REMOTE_VERSION" in
274  NetScreen*)
275    populate_new_ids 1
276    for KEY in $(printf "%s" "$NEW_IDS" | cut -d' ' -f2) ; do
277      KEY_NO=$(($KEY_NO + 1))
278      printf "%s\n" "$KEY" | grep ssh-dss >/dev/null || {
279         printf '%s: WARNING: Non-dsa key (#%d) skipped (NetScreen only supports DSA keys)\n' "$0" "$KEY_NO" >&2
280         continue
281      }
282      [ "$DRY_RUN" ] || printf 'set ssh pka-dsa key %s\nsave\nexit\n' "$KEY" | ssh -T "$@" >/dev/null 2>&1
283      if [ $? = 255 ] ; then
284        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
285      else
286        ADDED=$(($ADDED + 1))
287      fi
288    done
289    if [ -z "$ADDED" ] ; then
290      exit 1
291    fi
292    ;;
293  *)
294    # Assuming that the remote host treats ~/.ssh/authorized_keys as one might expect
295    populate_new_ids 0
296    # in ssh below - to defend against quirky remote shells: use 'exec sh -c' to get POSIX;
297    #     'cd' to be at $HOME; add a newline if it's missing; and all on one line, because tcsh.
298    [ "$DRY_RUN" ] || printf '%s\n' "$NEW_IDS" | \
299      ssh "$@" "exec sh -c 'cd ; umask 077 ; mkdir -p .ssh && { [ -z "'`tail -1c .ssh/authorized_keys 2>/dev/null`'" ] || echo >> .ssh/authorized_keys ; } && cat >> .ssh/authorized_keys || exit 1 ; if type restorecon >/dev/null 2>&1 ; then restorecon -F .ssh .ssh/authorized_keys ; fi'" \
300      || exit 1
301    ADDED=$(printf '%s\n' "$NEW_IDS" | wc -l)
302    ;;
303esac
304
305if [ "$DRY_RUN" ] ; then
306  cat <<-EOF
307	=-=-=-=-=-=-=-=
308	Would have added the following key(s):
309
310	$NEW_IDS
311	=-=-=-=-=-=-=-=
312	EOF
313else
314  cat <<-EOF
315
316	Number of key(s) added: $ADDED
317
318	Now try logging into the machine, with:   "ssh $SSH_OPTS"
319	and check to make sure that only the key(s) you wanted were added.
320
321	EOF
322fi
323
324# =-=-=-=
325