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
59248613SdesDEFAULT_PUB_ID_FILE=$(ls -t ${HOME}/.ssh/id*.pub 2>/dev/null | grep -v -- '-cert.pub$' | head -n 1)
60248613Sdes
61248613Sdesusage () {
62248613Sdes  printf 'Usage: %s [-h|-?|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname\n' "$0" >&2
63248613Sdes  exit 1
64248613Sdes}
65248613Sdes
66248613Sdes# escape any single quotes in an argument
67248613Sdesquote() {
68248613Sdes  printf "%s\n" "$1" | sed -e "s/'/'\\\\''/g"
69248613Sdes}
70248613Sdes
71248613Sdesuse_id_file() {
72248613Sdes  local L_ID_FILE="$1"
73248613Sdes
74248613Sdes  if expr "$L_ID_FILE" : ".*\.pub$" >/dev/null ; then
75248613Sdes    PUB_ID_FILE="$L_ID_FILE"
76248613Sdes  else
77248613Sdes    PUB_ID_FILE="$L_ID_FILE.pub"
78180740Sdes  fi
79248613Sdes
80248613Sdes  PRIV_ID_FILE=$(dirname "$PUB_ID_FILE")/$(basename "$PUB_ID_FILE" .pub)
81248613Sdes
82248613Sdes  # check that the files are readable
83248613Sdes  for f in $PUB_ID_FILE $PRIV_ID_FILE ; do
84248613Sdes    ErrMSG=$( { : < $f ; } 2>&1 ) || {
85248613Sdes      printf "\n%s: ERROR: failed to open ID file '%s': %s\n\n" "$0" "$f" "$(printf "%s\n" "$ErrMSG" | sed -e 's/.*: *//')"
86248613Sdes      exit 1
87248613Sdes    }
88248613Sdes  done
89248613Sdes  GET_ID="cat \"$PUB_ID_FILE\""
90248613Sdes}
91248613Sdes
92248613Sdesif [ -n "$SSH_AUTH_SOCK" ] && ssh-add -L >/dev/null 2>&1 ; then
93248613Sdes  GET_ID="ssh-add -L"
94180740Sdesfi
95180740Sdes
96248613Sdeswhile test "$#" -gt 0
97248613Sdesdo
98248613Sdes  [ "${SEEN_OPT_I}" ] && expr "$1" : "[-]i" >/dev/null && {
99248613Sdes        printf "\n%s: ERROR: -i option must not be specified more than once\n\n" "$0"
100248613Sdes        usage
101248613Sdes  }
102248613Sdes
103248613Sdes  OPT= OPTARG=
104248613Sdes  # implement something like getopt to avoid Solaris pain
105248613Sdes  case "$1" in
106248613Sdes    -i?*|-o?*|-p?*)
107248613Sdes      OPT="$(printf -- "$1"|cut -c1-2)"
108248613Sdes      OPTARG="$(printf -- "$1"|cut -c3-)"
109248613Sdes      shift
110248613Sdes      ;;
111248613Sdes    -o|-p)
112248613Sdes      OPT="$1"
113248613Sdes      OPTARG="$2"
114248613Sdes      shift 2
115248613Sdes      ;;
116248613Sdes    -i)
117248613Sdes      OPT="$1"
118248613Sdes      test "$#" -le 2 || expr "$2" : "[-]" >/dev/null || {
119248613Sdes        OPTARG="$2"
120248613Sdes        shift
121248613Sdes      }
122248613Sdes      shift
123248613Sdes      ;;
124248613Sdes    -n|-h|-\?)
125248613Sdes      OPT="$1"
126248613Sdes      OPTARG=
127248613Sdes      shift
128248613Sdes      ;;
129248613Sdes    --)
130248613Sdes      shift
131248613Sdes      while test "$#" -gt 0
132248613Sdes      do
133248613Sdes        SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
134248613Sdes        shift
135248613Sdes      done
136248613Sdes      break
137248613Sdes      ;;
138248613Sdes    -*)
139248613Sdes      printf "\n%s: ERROR: invalid option (%s)\n\n" "$0" "$1"
140248613Sdes      usage
141248613Sdes      ;;
142248613Sdes    *)
143248613Sdes      SAVEARGS="${SAVEARGS:+$SAVEARGS }'$(quote "$1")'"
144248613Sdes      shift
145248613Sdes      continue
146248613Sdes      ;;
147248613Sdes  esac
148248613Sdes
149248613Sdes  case "$OPT" in
150248613Sdes    -i)
151248613Sdes      SEEN_OPT_I="yes"
152248613Sdes      use_id_file "${OPTARG:-$DEFAULT_PUB_ID_FILE}"
153248613Sdes      ;;
154248613Sdes    -o|-p)
155248613Sdes      SSH_OPTS="${SSH_OPTS:+$SSH_OPTS }$OPT '$(quote "$OPTARG")'"
156248613Sdes      ;;
157248613Sdes    -n)
158248613Sdes      DRY_RUN=1
159248613Sdes      ;;
160248613Sdes    -h|-\?)
161248613Sdes      usage
162248613Sdes      ;;
163248613Sdes  esac
164248613Sdesdone 
165248613Sdes
166248613Sdeseval set -- "$SAVEARGS"
167248613Sdes
168255670Sdesif [ $# = 0 ] ; then
169250737Sdes  usage
170250737Sdesfi
171248613Sdesif [ $# != 1 ] ; then
172248613Sdes  printf '%s: ERROR: Too many arguments.  Expecting a target hostname, got: %s\n\n' "$0" "$SAVEARGS" >&2
173248613Sdes  usage
174180740Sdesfi
175180740Sdes
176248613Sdes# drop trailing colon
177248613SdesUSER_HOST=$(printf "%s\n" "$1" | sed 's/:$//')
178248613Sdes# tack the hostname onto SSH_OPTS
179248613SdesSSH_OPTS="${SSH_OPTS:+$SSH_OPTS }'$(quote "$USER_HOST")'"
180248613Sdes# and populate "$@" for later use (only way to get proper quoting of options)
181248613Sdeseval set -- "$SSH_OPTS"
182248613Sdes
183248613Sdesif [ -z "$(eval $GET_ID)" ] && [ -r "${PUB_ID_FILE:=$DEFAULT_PUB_ID_FILE}" ] ; then
184248613Sdes  use_id_file "$PUB_ID_FILE"
185180740Sdesfi
186180740Sdes
187248613Sdesif [ -z "$(eval $GET_ID)" ] ; then
188248613Sdes  printf '%s: ERROR: No identities found\n' "$0" >&2
189180740Sdes  exit 1
190180740Sdesfi
191180740Sdes
192248613Sdes# populate_new_ids() uses several global variables ($USER_HOST, $SSH_OPTS ...)
193248613Sdes# and has the side effect of setting $NEW_IDS
194248613Sdespopulate_new_ids() {
195248613Sdes  local L_SUCCESS="$1"
196180740Sdes
197248613Sdes  # repopulate "$@" inside this function 
198248613Sdes  eval set -- "$SSH_OPTS"
199214979Sdes
200248613Sdes  umask 0177
201248613Sdes  local L_TMP_ID_FILE=$(mktemp ~/.ssh/ssh-copy-id_id.XXXXXXXXXX)
202250737Sdes  if test $? -ne 0 || test "x$L_TMP_ID_FILE" = "x" ; then
203250737Sdes    echo "mktemp failed" 1>&2
204250737Sdes    exit 1
205250737Sdes  fi
206250737Sdes  trap "rm -f $L_TMP_ID_FILE ${L_TMP_ID_FILE}.pub" EXIT TERM INT QUIT
207248613Sdes  printf '%s: INFO: attempting to log in with the new key(s), to filter out any that are already installed\n' "$0" >&2
208248613Sdes  NEW_IDS=$(
209248613Sdes    eval $GET_ID | {
210248613Sdes      while read ID ; do
211248613Sdes        printf '%s\n' "$ID" > $L_TMP_ID_FILE
212180740Sdes
213248613Sdes        # the next line assumes $PRIV_ID_FILE only set if using a single id file - this
214248613Sdes        # assumption will break if we implement the possibility of multiple -i options.
215248613Sdes        # The point being that if file based, ssh needs the private key, which it cannot
216248613Sdes        # find if only given the contents of the .pub file in an unrelated tmpfile
217248613Sdes        ssh -i "${PRIV_ID_FILE:-$L_TMP_ID_FILE}" \
218248613Sdes            -o PreferredAuthentications=publickey \
219248613Sdes            -o IdentitiesOnly=yes "$@" exit 2>$L_TMP_ID_FILE.stderr </dev/null
220248613Sdes        if [ "$?" = "$L_SUCCESS" ] ; then
221248613Sdes          : > $L_TMP_ID_FILE
222248613Sdes        else
223248613Sdes          grep 'Permission denied' $L_TMP_ID_FILE.stderr >/dev/null || {
224248613Sdes            sed -e 's/^/ERROR: /' <$L_TMP_ID_FILE.stderr >$L_TMP_ID_FILE
225248613Sdes            cat >/dev/null #consume the other keys, causing loop to end
226248613Sdes          }
227248613Sdes        fi
228180740Sdes
229248613Sdes        cat $L_TMP_ID_FILE
230248613Sdes      done
231248613Sdes    }
232248613Sdes  )
233248613Sdes  rm -f $L_TMP_ID_FILE* && trap - EXIT TERM INT QUIT
234180740Sdes
235248613Sdes  if expr "$NEW_IDS" : "^ERROR: " >/dev/null ; then
236248613Sdes    printf '\n%s: %s\n\n' "$0" "$NEW_IDS" >&2
237248613Sdes    exit 1
238248613Sdes  fi
239248613Sdes  if [ -z "$NEW_IDS" ] ; then
240248613Sdes    printf '\n%s: WARNING: All keys were skipped because they already exist on the remote system.\n\n' "$0" >&2
241248613Sdes    exit 0
242248613Sdes  fi
243248613Sdes  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
244248613Sdes}
245214979Sdes
246248613SdesREMOTE_VERSION=$(ssh -v -o PreferredAuthentications=',' "$@" 2>&1 |
247248613Sdes                 sed -ne 's/.*remote software version //p')
248248613Sdes
249248613Sdescase "$REMOTE_VERSION" in
250248613Sdes  NetScreen*)
251248613Sdes    populate_new_ids 1
252248613Sdes    for KEY in $(printf "%s" "$NEW_IDS" | cut -d' ' -f2) ; do
253248613Sdes      KEY_NO=$(($KEY_NO + 1))
254248613Sdes      printf "%s\n" "$KEY" | grep ssh-dss >/dev/null || {
255248613Sdes         printf '%s: WARNING: Non-dsa key (#%d) skipped (NetScreen only supports DSA keys)\n' "$0" "$KEY_NO" >&2
256248613Sdes         continue
257248613Sdes      }
258248613Sdes      [ "$DRY_RUN" ] || printf 'set ssh pka-dsa key %s\nsave\nexit\n' "$KEY" | ssh -T "$@" >/dev/null 2>&1
259248613Sdes      if [ $? = 255 ] ; then
260248613Sdes        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
261248613Sdes      else
262248613Sdes        ADDED=$(($ADDED + 1))
263248613Sdes      fi
264248613Sdes    done
265248613Sdes    if [ -z "$ADDED" ] ; then
266248613Sdes      exit 1
267248613Sdes    fi
268248613Sdes    ;;
269248613Sdes  *)
270248613Sdes    # Assuming that the remote host treats ~/.ssh/authorized_keys as one might expect
271248613Sdes    populate_new_ids 0
272248613Sdes    [ "$DRY_RUN" ] || printf '%s\n' "$NEW_IDS" | ssh "$@" "
273248613Sdes		umask 077 ;
274248613Sdes		mkdir -p .ssh && cat >> .ssh/authorized_keys || exit 1 ;
275248613Sdes		if type restorecon >/dev/null 2>&1 ; then restorecon -F .ssh .ssh/authorized_keys ; fi" \
276248613Sdes      || exit 1
277248613Sdes    ADDED=$(printf '%s\n' "$NEW_IDS" | wc -l)
278248613Sdes    ;;
279248613Sdesesac
280248613Sdes
281248613Sdesif [ "$DRY_RUN" ] ; then
282248613Sdes  cat <<-EOF
283248613Sdes	=-=-=-=-=-=-=-=
284248613Sdes	Would have added the following key(s):
285248613Sdes
286248613Sdes	$NEW_IDS
287248613Sdes	=-=-=-=-=-=-=-=
288248613Sdes	EOF
289248613Sdeselse
290248613Sdes  cat <<-EOF
291248613Sdes
292248613Sdes	Number of key(s) added: $ADDED
293248613Sdes
294248613Sdes	Now try logging into the machine, with:   "ssh $SSH_OPTS"
295248613Sdes	and check to make sure that only the key(s) you wanted were added.
296248613Sdes
297248613Sdes	EOF
298248613Sdesfi
299248613Sdes
300248613Sdes# =-=-=-=
301