1#!/bin/sh
2
3# Copyright (c) 1999-2013 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
59DEFAULT_PUB_ID_FILE=$(ls -t ${HOME}/.ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)
60
61usage () {
62  printf 'Usage: %s [-h|-?|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname\n' "$0" >&2
63  exit 1
64}
65
66# escape any single quotes in an argument
67quote() {
68  printf "%s\n" "$1" | sed -e "s/'/'\\\\''/g"
69}
70
71use_id_file() {
72  local L_ID_FILE="$1"
73
74  if expr "$L_ID_FILE" : ".*\.pub$" >/dev/null ; then
75    PUB_ID_FILE="$L_ID_FILE"
76  else
77    PUB_ID_FILE="$L_ID_FILE.pub"
78  fi
79
80  PRIV_ID_FILE=$(dirname "$PUB_ID_FILE")/$(basename "$PUB_ID_FILE" .pub)
81
82  # check that the files are readable
83  for f in $PUB_ID_FILE $PRIV_ID_FILE ; do
84    ErrMSG=$( { : < $f ; } 2>&1 ) || {
85      printf "\n%s: ERROR: failed to open ID file '%s': %s\n\n" "$0" "$f" "$(printf "%s\n" "$ErrMSG" | sed -e 's/.*: *//')"
86      exit 1
87    }
88  done
89  GET_ID="cat \"$PUB_ID_FILE\""
90}
91
92if [ -n "$SSH_AUTH_SOCK" ] && ssh-add -L >/dev/null 2>&1 ; then
93  GET_ID="ssh-add -L"
94fi
95
96while test "$#" -gt 0
97do
98  [ "${SEEN_OPT_I}" ] && expr "$1" : "[-]i" >/dev/null && {
99        printf "\n%s: ERROR: -i option must not be specified more than once\n\n" "$0"
100        usage
101  }
102
103  OPT= OPTARG=
104  # implement something like getopt to avoid Solaris pain
105  case "$1" in
106    -i?*|-o?*|-p?*)
107      OPT="$(printf -- "$1"|cut -c1-2)"
108      OPTARG="$(printf -- "$1"|cut -c3-)"
109      shift
110      ;;
111    -o|-p)
112      OPT="$1"
113      OPTARG="$2"
114      shift 2
115      ;;
116    -i)
117      OPT="$1"
118      test "$#" -le 2 || expr "$2" : "[-]" >/dev/null || {
119        OPTARG="$2"
120        shift
121      }
122      shift
123      ;;
124    -n|-h|-\?)
125      OPT="$1"
126      OPTARG=
127      shift
128      ;;
129    --)
130      shift
131      while test "$#" -gt 0
132      do
133        SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
134        shift
135      done
136      break
137      ;;
138    -*)
139      printf "\n%s: ERROR: invalid option (%s)\n\n" "$0" "$1"
140      usage
141      ;;
142    *)
143      SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
144      shift
145      continue
146      ;;
147  esac
148
149  case "$OPT" in
150    -i)
151      SEEN_OPT_I="yes"
152      use_id_file "${OPTARG:-$DEFAULT_PUB_ID_FILE}"
153      ;;
154    -o|-p)
155      SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }$OPT '$(quote "$OPTARG")'"
156      ;;
157    -n)
158      DRY_RUN=1
159      ;;
160    -h|-\?)
161      usage
162      ;;
163  esac
164done 
165
166eval set -- "$SAVEARGS"
167
168if [ $# = 0 ] ; then
169  usage
170fi
171if [ $# != 1 ] ; then
172  printf '%s: ERROR: Too many arguments.  Expecting a target hostname, got: %s\n\n' "$0" "$SAVEARGS" >&2
173  usage
174fi
175
176# drop trailing colon
177USER_HOST=$(printf "%s\n" "$1" | sed 's/:$//')
178# tack the hostname onto SSH_OPTS
179SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }'$(quote "$USER_HOST")'"
180# and populate "$@" for later use (only way to get proper quoting of options)
181eval set -- "$SSH_OPTS"
182
183if [ -z "$(eval $GET_ID)" ] && [ -r "${PUB_ID_FILE:=$DEFAULT_PUB_ID_FILE}" ] ; then
184  use_id_file "$PUB_ID_FILE"
185fi
186
187if [ -z "$(eval $GET_ID)" ] ; then
188  printf '%s: ERROR: No identities found\n' "$0" >&2
189  exit 1
190fi
191
192# populate_new_ids() uses several global variables ($USER_HOST, $SSH_OPTS ...)
193# and has the side effect of setting $NEW_IDS
194populate_new_ids() {
195  local L_SUCCESS="$1"
196
197  # repopulate "$@" inside this function 
198  eval set -- "$SSH_OPTS"
199
200  umask 0177
201  local L_TMP_ID_FILE=$(mktemp ~/.ssh/ssh-copy-id_id.XXXXXXXXXX)
202  if test $? -ne 0 || test "x$L_TMP_ID_FILE" = "x" ; then
203    echo "mktemp failed" 1>&2
204    exit 1
205  fi
206  trap "rm -f $L_TMP_ID_FILE ${L_TMP_ID_FILE}.pub" EXIT TERM INT QUIT
207  printf '%s: INFO: attempting to log in with the new key(s), to filter out any that are already installed\n' "$0" >&2
208  NEW_IDS=$(
209    eval $GET_ID | {
210      while read ID ; do
211        printf '%s\n' "$ID" > $L_TMP_ID_FILE
212
213        # the next line assumes $PRIV_ID_FILE only set if using a single id file - this
214        # assumption will break if we implement the possibility of multiple -i options.
215        # The point being that if file based, ssh needs the private key, which it cannot
216        # find if only given the contents of the .pub file in an unrelated tmpfile
217        ssh -i "${PRIV_ID_FILE:-$L_TMP_ID_FILE}" \
218            -o PreferredAuthentications=publickey \
219            -o IdentitiesOnly=yes "$@" exit 2>$L_TMP_ID_FILE.stderr </dev/null
220        if [ "$?" = "$L_SUCCESS" ] ; then
221          : > $L_TMP_ID_FILE
222        else
223          grep 'Permission denied' $L_TMP_ID_FILE.stderr >/dev/null || {
224            sed -e 's/^/ERROR: /' <$L_TMP_ID_FILE.stderr >$L_TMP_ID_FILE
225            cat >/dev/null #consume the other keys, causing loop to end
226          }
227        fi
228
229        cat $L_TMP_ID_FILE
230      done
231    }
232  )
233  rm -f $L_TMP_ID_FILE* && trap - EXIT TERM INT QUIT
234
235  if expr "$NEW_IDS" : "^ERROR: " >/dev/null ; then
236    printf '\n%s: %s\n\n' "$0" "$NEW_IDS" >&2
237    exit 1
238  fi
239  if [ -z "$NEW_IDS" ] ; then
240    printf '\n%s: WARNING: All keys were skipped because they already exist on the remote system.\n\n' "$0" >&2
241    exit 0
242  fi
243  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
244}
245
246REMOTE_VERSION=$(ssh -v -o PreferredAuthentications=',' "$@" 2>&1 |
247                 sed -ne 's/.*remote software version //p')
248
249case "$REMOTE_VERSION" in
250  NetScreen*)
251    populate_new_ids 1
252    for KEY in $(printf "%s" "$NEW_IDS" | cut -d' ' -f2) ; do
253      KEY_NO=$(($KEY_NO + 1))
254      printf "%s\n" "$KEY" | grep ssh-dss >/dev/null || {
255         printf '%s: WARNING: Non-dsa key (#%d) skipped (NetScreen only supports DSA keys)\n' "$0" "$KEY_NO" >&2
256         continue
257      }
258      [ "$DRY_RUN" ] || printf 'set ssh pka-dsa key %s\nsave\nexit\n' "$KEY" | ssh -T "$@" >/dev/null 2>&1
259      if [ $? = 255 ] ; then
260        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
261      else
262        ADDED=$(($ADDED + 1))
263      fi
264    done
265    if [ -z "$ADDED" ] ; then
266      exit 1
267    fi
268    ;;
269  *)
270    # Assuming that the remote host treats ~/.ssh/authorized_keys as one might expect
271    populate_new_ids 0
272    [ "$DRY_RUN" ] || printf '%s\n' "$NEW_IDS" | ssh "$@" "
273		umask 077 ;
274		mkdir -p .ssh && cat >> .ssh/authorized_keys || exit 1 ;
275		if type restorecon >/dev/null 2>&1 ; then restorecon -F .ssh .ssh/authorized_keys ; fi" \
276      || exit 1
277    ADDED=$(printf '%s\n' "$NEW_IDS" | wc -l)
278    ;;
279esac
280
281if [ "$DRY_RUN" ] ; then
282  cat <<-EOF
283	=-=-=-=-=-=-=-=
284	Would have added the following key(s):
285
286	$NEW_IDS
287	=-=-=-=-=-=-=-=
288	EOF
289else
290  cat <<-EOF
291
292	Number of key(s) added: $ADDED
293
294	Now try logging into the machine, with:   "ssh $SSH_OPTS"
295	and check to make sure that only the key(s) you wanted were added.
296
297	EOF
298fi
299
300# =-=-=-=
301