1180740Sdes#!/bin/sh
2180740Sdes
3248613Sdes# Copyright (c) 1999-2013 Philip Hands <phil@hands.com>
4248613Sdes#               2013 Martin Kletzander <mkletzan@redhat.com>
5248613Sdes#               2010 Adeodato =?iso-8859-1?Q?Sim=F3?= <asp16@alu.ua.es>
6248613Sdes#               2010 Eric Moret <eric.moret@gmail.com>
7248613Sdes#               2009 Xr <xr@i-jeuxvideo.com>
8248613Sdes#               2007 Justin Pryzby <justinpryzby@users.sourceforge.net>
9248613Sdes#               2004 Reini Urban <rurban@x-ray.at>
10248613Sdes#               2003 Colin Watson <cjwatson@debian.org>
11248613Sdes# All rights reserved.
12248613Sdes#
13248613Sdes# Redistribution and use in source and binary forms, with or without
14248613Sdes# modification, are permitted provided that the following conditions
15248613Sdes# are met:
16248613Sdes# 1. Redistributions of source code must retain the above copyright
17248613Sdes#    notice, this list of conditions and the following disclaimer.
18248613Sdes# 2. Redistributions in binary form must reproduce the above copyright
19248613Sdes#    notice, this list of conditions and the following disclaimer in the
20248613Sdes#    documentation and/or other materials provided with the distribution.
21248613Sdes#
22248613Sdes# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23248613Sdes# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24248613Sdes# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25248613Sdes# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26248613Sdes# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27248613Sdes# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28248613Sdes# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29248613Sdes# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30248613Sdes# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31248613Sdes# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32180740Sdes
33248613Sdes# Shell script to install your public key(s) on a remote machine
34248613Sdes# See the ssh-copy-id(1) man page for details
35180740Sdes
36248613Sdes# check that we have something mildly sane as our shell, or try to find something better
37248613Sdesif false ^ printf "%s: WARNING: ancient shell, hunting for a more modern one... " "$0"
38248613Sdesthen
39248613Sdes  SANE_SH=${SANE_SH:-/usr/bin/ksh}
40248613Sdes  if printf 'true ^ false\n' | "$SANE_SH"
41248613Sdes  then
42248613Sdes    printf "'%s' seems viable.\n" "$SANE_SH"
43248613Sdes    exec "$SANE_SH" "$0" "$@"
44248613Sdes  else
45248613Sdes    cat <<-EOF
46248613Sdes	oh dear.
47248613Sdes
48248613Sdes	  If you have a more recent shell available, that supports \$(...) etc.
49248613Sdes	  please try setting the environment variable SANE_SH to the path of that
50248613Sdes	  shell, and then retry running this script. If that works, please report
51248613Sdes	  a bug describing your setup, and the shell you used to make it work.
52248613Sdes
53248613Sdes	EOF
54248613Sdes    printf "%s: ERROR: Less dimwitted shell required.\n" "$0"
55248613Sdes    exit 1
56180740Sdes  fi
57248613Sdesfi
58248613Sdes
59296781SdesDEFAULT_PUB_ID_FILE="$HOME/$(cd "$HOME" ; ls -t .ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)"
60248613Sdes
61248613Sdesusage () {
62296781Sdes  printf 'Usage: %s [-h|-?|-f|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname\n' "$0" >&2
63296781Sdes  printf '\t-f: force mode -- copy keys without trying to check if they are already installed\n' >&2
64296781Sdes  printf '\t-n: dry run    -- no keys are actually copied\n' >&2
65296781Sdes  printf '\t-h|-?: print this help\n' >&2
66248613Sdes  exit 1
67248613Sdes}
68248613Sdes
69248613Sdes# escape any single quotes in an argument
70248613Sdesquote() {
71248613Sdes  printf "%s\n" "$1" | sed -e "s/'/'\\\\''/g"
72248613Sdes}
73248613Sdes
74248613Sdesuse_id_file() {
75248613Sdes  local L_ID_FILE="$1"
76248613Sdes
77248613Sdes  if expr "$L_ID_FILE" : ".*\.pub$" >/dev/null ; then
78248613Sdes    PUB_ID_FILE="$L_ID_FILE"
79248613Sdes  else
80248613Sdes    PUB_ID_FILE="$L_ID_FILE.pub"
81180740Sdes  fi
82248613Sdes
83296781Sdes  [ "$FORCED" ] || PRIV_ID_FILE=$(dirname "$PUB_ID_FILE")/$(basename "$PUB_ID_FILE" .pub)
84248613Sdes
85248613Sdes  # check that the files are readable
86296781Sdes  for f in "$PUB_ID_FILE" ${PRIV_ID_FILE:+"$PRIV_ID_FILE"} ; do
87296781Sdes    ErrMSG=$( { : < "$f" ; } 2>&1 ) || {
88296781Sdes      local L_PRIVMSG=""
89296781Sdes      [ "$f" = "$PRIV_ID_FILE" ] && L_PRIVMSG="	(to install the contents of '$PUB_ID_FILE' anyway, look at the -f option)"
90296781Sdes      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/.*: *//')"
91248613Sdes      exit 1
92248613Sdes    }
93248613Sdes  done
94296781Sdes  printf '%s: INFO: Source of key(s) to be installed: "%s"\n' "$0" "$PUB_ID_FILE" >&2
95248613Sdes  GET_ID="cat \"$PUB_ID_FILE\""
96248613Sdes}
97248613Sdes
98248613Sdesif [ -n "$SSH_AUTH_SOCK" ] && ssh-add -L >/dev/null 2>&1 ; then
99248613Sdes  GET_ID="ssh-add -L"
100180740Sdesfi
101180740Sdes
102248613Sdeswhile test "$#" -gt 0
103248613Sdesdo
104248613Sdes  [ "${SEEN_OPT_I}" ] && expr "$1" : "[-]i" >/dev/null && {
105248613Sdes        printf "\n%s: ERROR: -i option must not be specified more than once\n\n" "$0"
106248613Sdes        usage
107248613Sdes  }
108248613Sdes
109248613Sdes  OPT= OPTARG=
110248613Sdes  # implement something like getopt to avoid Solaris pain
111248613Sdes  case "$1" in
112248613Sdes    -i?*|-o?*|-p?*)
113248613Sdes      OPT="$(printf -- "$1"|cut -c1-2)"
114248613Sdes      OPTARG="$(printf -- "$1"|cut -c3-)"
115248613Sdes      shift
116248613Sdes      ;;
117248613Sdes    -o|-p)
118248613Sdes      OPT="$1"
119248613Sdes      OPTARG="$2"
120248613Sdes      shift 2
121248613Sdes      ;;
122248613Sdes    -i)
123248613Sdes      OPT="$1"
124248613Sdes      test "$#" -le 2 || expr "$2" : "[-]" >/dev/null || {
125248613Sdes        OPTARG="$2"
126248613Sdes        shift
127248613Sdes      }
128248613Sdes      shift
129248613Sdes      ;;
130296781Sdes    -f|-n|-h|-\?)
131248613Sdes      OPT="$1"
132248613Sdes      OPTARG=
133248613Sdes      shift
134248613Sdes      ;;
135248613Sdes    --)
136248613Sdes      shift
137248613Sdes      while test "$#" -gt 0
138248613Sdes      do
139248613Sdes        SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
140248613Sdes        shift
141248613Sdes      done
142248613Sdes      break
143248613Sdes      ;;
144248613Sdes    -*)
145248613Sdes      printf "\n%s: ERROR: invalid option (%s)\n\n" "$0" "$1"
146248613Sdes      usage
147248613Sdes      ;;
148248613Sdes    *)
149248613Sdes      SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
150248613Sdes      shift
151248613Sdes      continue
152248613Sdes      ;;
153248613Sdes  esac
154248613Sdes
155248613Sdes  case "$OPT" in
156248613Sdes    -i)
157248613Sdes      SEEN_OPT_I="yes"
158248613Sdes      use_id_file "${OPTARG:-$DEFAULT_PUB_ID_FILE}"
159248613Sdes      ;;
160248613Sdes    -o|-p)
161248613Sdes      SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }$OPT '$(quote "$OPTARG")'"
162248613Sdes      ;;
163296781Sdes    -f)
164296781Sdes      FORCED=1
165296781Sdes      ;;
166248613Sdes    -n)
167248613Sdes      DRY_RUN=1
168248613Sdes      ;;
169248613Sdes    -h|-\?)
170248613Sdes      usage
171248613Sdes      ;;
172248613Sdes  esac
173248613Sdesdone 
174248613Sdes
175248613Sdeseval set -- "$SAVEARGS"
176248613Sdes
177255670Sdesif [ $# = 0 ] ; then
178250737Sdes  usage
179250737Sdesfi
180248613Sdesif [ $# != 1 ] ; then
181248613Sdes  printf '%s: ERROR: Too many arguments.  Expecting a target hostname, got: %s\n\n' "$0" "$SAVEARGS" >&2
182248613Sdes  usage
183180740Sdesfi
184180740Sdes
185248613Sdes# drop trailing colon
186248613SdesUSER_HOST=$(printf "%s\n" "$1" | sed 's/:$//')
187248613Sdes# tack the hostname onto SSH_OPTS
188248613SdesSSH_OPTS="${SSH_OPTS:+$SSH_OPTS }'$(quote "$USER_HOST")'"
189248613Sdes# and populate "$@" for later use (only way to get proper quoting of options)
190248613Sdeseval set -- "$SSH_OPTS"
191248613Sdes
192248613Sdesif [ -z "$(eval $GET_ID)" ] && [ -r "${PUB_ID_FILE:=$DEFAULT_PUB_ID_FILE}" ] ; then
193248613Sdes  use_id_file "$PUB_ID_FILE"
194180740Sdesfi
195180740Sdes
196248613Sdesif [ -z "$(eval $GET_ID)" ] ; then
197248613Sdes  printf '%s: ERROR: No identities found\n' "$0" >&2
198180740Sdes  exit 1
199180740Sdesfi
200180740Sdes
201248613Sdes# populate_new_ids() uses several global variables ($USER_HOST, $SSH_OPTS ...)
202248613Sdes# and has the side effect of setting $NEW_IDS
203248613Sdespopulate_new_ids() {
204248613Sdes  local L_SUCCESS="$1"
205180740Sdes
206296781Sdes  if [ "$FORCED" ] ; then
207296781Sdes    NEW_IDS=$(eval $GET_ID)
208296781Sdes    return
209296781Sdes  fi
210296781Sdes
211248613Sdes  # repopulate "$@" inside this function 
212248613Sdes  eval set -- "$SSH_OPTS"
213214979Sdes
214248613Sdes  umask 0177
215248613Sdes  local L_TMP_ID_FILE=$(mktemp ~/.ssh/ssh-copy-id_id.XXXXXXXXXX)
216250737Sdes  if test $? -ne 0 || test "x$L_TMP_ID_FILE" = "x" ; then
217296781Sdes    printf '%s: ERROR: mktemp failed\n' "$0" >&2
218250737Sdes    exit 1
219250737Sdes  fi
220296781Sdes  local L_CLEANUP="rm -f \"$L_TMP_ID_FILE\" \"${L_TMP_ID_FILE}.stderr\""
221296781Sdes  trap "$L_CLEANUP" EXIT TERM INT QUIT
222248613Sdes  printf '%s: INFO: attempting to log in with the new key(s), to filter out any that are already installed\n' "$0" >&2
223248613Sdes  NEW_IDS=$(
224248613Sdes    eval $GET_ID | {
225296781Sdes      while read ID || [ "$ID" ] ; do
226296781Sdes        printf '%s\n' "$ID" > "$L_TMP_ID_FILE"
227180740Sdes
228248613Sdes        # the next line assumes $PRIV_ID_FILE only set if using a single id file - this
229248613Sdes        # assumption will break if we implement the possibility of multiple -i options.
230248613Sdes        # The point being that if file based, ssh needs the private key, which it cannot
231248613Sdes        # find if only given the contents of the .pub file in an unrelated tmpfile
232248613Sdes        ssh -i "${PRIV_ID_FILE:-$L_TMP_ID_FILE}" \
233296781Sdes            -o ControlPath=none \
234296781Sdes            -o LogLevel=INFO \
235248613Sdes            -o PreferredAuthentications=publickey \
236323124Sdes            -o IdentitiesOnly=yes "$@" exit 2>"$L_TMP_ID_FILE.stderr" </dev/null
237248613Sdes        if [ "$?" = "$L_SUCCESS" ] ; then
238323124Sdes          : > "$L_TMP_ID_FILE"
239248613Sdes        else
240323124Sdes          grep 'Permission denied' "$L_TMP_ID_FILE.stderr" >/dev/null || {
241323124Sdes            sed -e 's/^/ERROR: /' <"$L_TMP_ID_FILE.stderr" >"$L_TMP_ID_FILE"
242248613Sdes            cat >/dev/null #consume the other keys, causing loop to end
243248613Sdes          }
244248613Sdes        fi
245180740Sdes
246323124Sdes        cat "$L_TMP_ID_FILE"
247248613Sdes      done
248248613Sdes    }
249248613Sdes  )
250296781Sdes  eval "$L_CLEANUP" && trap - EXIT TERM INT QUIT
251180740Sdes
252248613Sdes  if expr "$NEW_IDS" : "^ERROR: " >/dev/null ; then
253248613Sdes    printf '\n%s: %s\n\n' "$0" "$NEW_IDS" >&2
254248613Sdes    exit 1
255248613Sdes  fi
256248613Sdes  if [ -z "$NEW_IDS" ] ; then
257296781Sdes    printf '\n%s: WARNING: All keys were skipped because they already exist on the remote system.\n' "$0" >&2
258296781Sdes    printf '\t\t(if you think this is a mistake, you may want to use -f option)\n\n' "$0" >&2
259248613Sdes    exit 0
260248613Sdes  fi
261248613Sdes  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
262248613Sdes}
263214979Sdes
264296781SdesREMOTE_VERSION=$(ssh -v -o PreferredAuthentications=',' -o ControlPath=none "$@" 2>&1 |
265248613Sdes                 sed -ne 's/.*remote software version //p')
266248613Sdes
267248613Sdescase "$REMOTE_VERSION" in
268248613Sdes  NetScreen*)
269248613Sdes    populate_new_ids 1
270248613Sdes    for KEY in $(printf "%s" "$NEW_IDS" | cut -d' ' -f2) ; do
271248613Sdes      KEY_NO=$(($KEY_NO + 1))
272248613Sdes      printf "%s\n" "$KEY" | grep ssh-dss >/dev/null || {
273248613Sdes         printf '%s: WARNING: Non-dsa key (#%d) skipped (NetScreen only supports DSA keys)\n' "$0" "$KEY_NO" >&2
274248613Sdes         continue
275248613Sdes      }
276248613Sdes      [ "$DRY_RUN" ] || printf 'set ssh pka-dsa key %s\nsave\nexit\n' "$KEY" | ssh -T "$@" >/dev/null 2>&1
277248613Sdes      if [ $? = 255 ] ; then
278248613Sdes        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
279248613Sdes      else
280248613Sdes        ADDED=$(($ADDED + 1))
281248613Sdes      fi
282248613Sdes    done
283248613Sdes    if [ -z "$ADDED" ] ; then
284248613Sdes      exit 1
285248613Sdes    fi
286248613Sdes    ;;
287248613Sdes  *)
288248613Sdes    # Assuming that the remote host treats ~/.ssh/authorized_keys as one might expect
289248613Sdes    populate_new_ids 0
290296781Sdes    # in ssh below - to defend against quirky remote shells: use 'exec sh -c' to get POSIX; 'cd' to be at $HOME; and all on one line, because tcsh.
291296781Sdes    [ "$DRY_RUN" ] || printf '%s\n' "$NEW_IDS" | \
292296781Sdes      ssh "$@" "exec sh -c 'cd ; umask 077 ; mkdir -p .ssh && cat >> .ssh/authorized_keys || exit 1 ; if type restorecon >/dev/null 2>&1 ; then restorecon -F .ssh .ssh/authorized_keys ; fi'" \
293248613Sdes      || exit 1
294248613Sdes    ADDED=$(printf '%s\n' "$NEW_IDS" | wc -l)
295248613Sdes    ;;
296248613Sdesesac
297248613Sdes
298248613Sdesif [ "$DRY_RUN" ] ; then
299248613Sdes  cat <<-EOF
300248613Sdes	=-=-=-=-=-=-=-=
301248613Sdes	Would have added the following key(s):
302248613Sdes
303248613Sdes	$NEW_IDS
304248613Sdes	=-=-=-=-=-=-=-=
305248613Sdes	EOF
306248613Sdeselse
307248613Sdes  cat <<-EOF
308248613Sdes
309248613Sdes	Number of key(s) added: $ADDED
310248613Sdes
311248613Sdes	Now try logging into the machine, with:   "ssh $SSH_OPTS"
312248613Sdes	and check to make sure that only the key(s) you wanted were added.
313248613Sdes
314248613Sdes	EOF
315248613Sdesfi
316248613Sdes
317248613Sdes# =-=-=-=
318