1
# Copyright (C) 2006-2011 Robey Pointer <robey@lag.net>
2
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
"""Foundation SSH support for SFTP and smart server."""
20
from __future__ import absolute_import
29
from binascii import hexlify
42
except ImportError as e:
43
# If we have an ssh subprocess, we don't strictly need paramiko for all ssh
47
from paramiko.sftp_client import SFTPClient
50
class StrangeHostname(errors.BzrError):
51
_fmt = "Refusing to connect to strange SSH hostname %(hostname)s"
58
class SSHVendorManager(object):
59
"""Manager for manage SSH vendors."""
61
# Note, although at first sign the class interface seems similar to
62
# breezy.registry.Registry it is not possible/convenient to directly use
63
# the Registry because the class just has "get()" interface instead of the
64
# Registry's "get(key)".
67
self._ssh_vendors = {}
68
self._cached_ssh_vendor = None
69
self._default_ssh_vendor = None
71
def register_default_vendor(self, vendor):
72
"""Register default SSH vendor."""
73
self._default_ssh_vendor = vendor
75
def register_vendor(self, name, vendor):
76
"""Register new SSH vendor by name."""
77
self._ssh_vendors[name] = vendor
79
def clear_cache(self):
80
"""Clear previously cached lookup result."""
81
self._cached_ssh_vendor = None
83
def _get_vendor_by_environment(self, environment=None):
84
"""Return the vendor or None based on BRZ_SSH environment variable.
86
:raises UnknownSSH: if the BRZ_SSH environment variable contains
89
if environment is None:
90
environment = os.environ
91
if 'BRZ_SSH' in environment:
92
vendor_name = environment['BRZ_SSH']
94
vendor = self._ssh_vendors[vendor_name]
96
vendor = self._get_vendor_from_path(vendor_name)
98
raise errors.UnknownSSH(vendor_name)
99
vendor.executable_path = vendor_name
103
def _get_ssh_version_string(self, args):
104
"""Return SSH version string from the subprocess."""
106
p = subprocess.Popen(args,
107
stdout=subprocess.PIPE,
108
stderr=subprocess.PIPE,
110
**os_specific_subprocess_params())
111
stdout, stderr = p.communicate()
113
stdout = stderr = b''
114
return (stdout + stderr).decode(osutils.get_terminal_encoding())
116
def _get_vendor_by_version_string(self, version, progname):
117
"""Return the vendor or None based on output from the subprocess.
119
:param version: The output of 'ssh -V' like command.
120
:param args: Command line that was run.
123
if 'OpenSSH' in version:
124
trace.mutter('ssh implementation is OpenSSH')
125
vendor = OpenSSHSubprocessVendor()
126
elif 'SSH Secure Shell' in version:
127
trace.mutter('ssh implementation is SSH Corp.')
128
vendor = SSHCorpSubprocessVendor()
129
elif 'lsh' in version:
130
trace.mutter('ssh implementation is GNU lsh.')
131
vendor = LSHSubprocessVendor()
132
# As plink user prompts are not handled currently, don't auto-detect
133
# it by inspection below, but keep this vendor detection for if a path
134
# is given in BRZ_SSH. See https://bugs.launchpad.net/bugs/414743
135
elif 'plink' in version and progname == 'plink':
136
# Checking if "plink" was the executed argument as Windows
137
# sometimes reports 'ssh -V' incorrectly with 'plink' in its
138
# version. See https://bugs.launchpad.net/bzr/+bug/107155
139
trace.mutter("ssh implementation is Putty's plink.")
140
vendor = PLinkSubprocessVendor()
143
def _get_vendor_by_inspection(self):
144
"""Return the vendor or None by checking for known SSH implementations."""
145
version = self._get_ssh_version_string(['ssh', '-V'])
146
return self._get_vendor_by_version_string(version, "ssh")
148
def _get_vendor_from_path(self, path):
149
"""Return the vendor or None using the program at the given path"""
150
version = self._get_ssh_version_string([path, '-V'])
151
return self._get_vendor_by_version_string(version,
152
os.path.splitext(os.path.basename(path))[0])
154
def get_vendor(self, environment=None):
155
"""Find out what version of SSH is on the system.
157
:raises SSHVendorNotFound: if no any SSH vendor is found
158
:raises UnknownSSH: if the BRZ_SSH environment variable contains
161
if self._cached_ssh_vendor is None:
162
vendor = self._get_vendor_by_environment(environment)
164
vendor = self._get_vendor_by_inspection()
166
trace.mutter('falling back to default implementation')
167
vendor = self._default_ssh_vendor
169
raise errors.SSHVendorNotFound()
170
self._cached_ssh_vendor = vendor
171
return self._cached_ssh_vendor
174
_ssh_vendor_manager = SSHVendorManager()
175
_get_ssh_vendor = _ssh_vendor_manager.get_vendor
176
register_default_ssh_vendor = _ssh_vendor_manager.register_default_vendor
177
register_ssh_vendor = _ssh_vendor_manager.register_vendor
180
def _ignore_signals():
181
# TODO: This should possibly ignore SIGHUP as well, but bzr currently
182
# doesn't handle it itself.
183
# <https://launchpad.net/products/bzr/+bug/41433/+index>
185
signal.signal(signal.SIGINT, signal.SIG_IGN)
186
# GZ 2010-02-19: Perhaps make this check if breakin is installed instead
187
if signal.getsignal(signal.SIGQUIT) != signal.SIG_DFL:
188
signal.signal(signal.SIGQUIT, signal.SIG_IGN)
191
class SocketAsChannelAdapter(object):
192
"""Simple wrapper for a socket that pretends to be a paramiko Channel."""
194
def __init__(self, sock):
198
return "bzr SocketAsChannelAdapter"
200
def send(self, data):
201
return self.__socket.send(data)
205
return self.__socket.recv(n)
206
except socket.error as e:
207
if e.args[0] in (errno.EPIPE, errno.ECONNRESET, errno.ECONNABORTED,
209
# Connection has closed. Paramiko expects an empty string in
210
# this case, not an exception.
214
def recv_ready(self):
215
# TODO: jam 20051215 this function is necessary to support the
216
# pipelined() function. In reality, it probably should use
217
# poll() or select() to actually return if there is data
218
# available, otherwise we probably don't get any benefit
222
self.__socket.close()
225
class SSHVendor(object):
226
"""Abstract base class for SSH vendor implementations."""
228
def connect_sftp(self, username, password, host, port):
229
"""Make an SSH connection, and return an SFTPClient.
231
:param username: an ascii string
232
:param password: an ascii string
233
:param host: a host name as an ascii string
234
:param port: a port number
237
:raises: ConnectionError if it cannot connect.
239
:rtype: paramiko.sftp_client.SFTPClient
241
raise NotImplementedError(self.connect_sftp)
243
def connect_ssh(self, username, password, host, port, command):
244
"""Make an SSH connection.
246
:returns: an SSHConnection.
248
raise NotImplementedError(self.connect_ssh)
250
def _raise_connection_error(self, host, port=None, orig_error=None,
251
msg='Unable to connect to SSH host'):
252
"""Raise a SocketConnectionError with properly formatted host.
254
This just unifies all the locations that try to raise ConnectionError,
255
so that they format things properly.
257
raise errors.SocketConnectionError(host=host, port=port, msg=msg,
258
orig_error=orig_error)
261
class LoopbackVendor(SSHVendor):
262
"""SSH "vendor" that connects over a plain TCP socket, not SSH."""
264
def connect_sftp(self, username, password, host, port):
265
sock = socket.socket()
267
sock.connect((host, port))
268
except socket.error as e:
269
self._raise_connection_error(host, port=port, orig_error=e)
270
return SFTPClient(SocketAsChannelAdapter(sock))
273
register_ssh_vendor('loopback', LoopbackVendor())
276
class ParamikoVendor(SSHVendor):
277
"""Vendor that uses paramiko."""
279
def _hexify(self, s):
280
return hexlify(s).upper()
282
def _connect(self, username, password, host, port):
283
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
288
t = paramiko.Transport((host, port or 22))
289
t.set_log_channel('bzr.paramiko')
291
except (paramiko.SSHException, socket.error) as e:
292
self._raise_connection_error(host, port=port, orig_error=e)
294
server_key = t.get_remote_server_key()
295
server_key_hex = self._hexify(server_key.get_fingerprint())
296
keytype = server_key.get_name()
297
if host in SYSTEM_HOSTKEYS and keytype in SYSTEM_HOSTKEYS[host]:
298
our_server_key = SYSTEM_HOSTKEYS[host][keytype]
299
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
300
elif host in BRZ_HOSTKEYS and keytype in BRZ_HOSTKEYS[host]:
301
our_server_key = BRZ_HOSTKEYS[host][keytype]
302
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
304
trace.warning('Adding %s host key for %s: %s'
305
% (keytype, host, server_key_hex))
306
add = getattr(BRZ_HOSTKEYS, 'add', None)
307
if add is not None: # paramiko >= 1.X.X
308
BRZ_HOSTKEYS.add(host, keytype, server_key)
310
BRZ_HOSTKEYS.setdefault(host, {})[keytype] = server_key
311
our_server_key = server_key
312
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
314
if server_key != our_server_key:
315
filename1 = os.path.expanduser('~/.ssh/known_hosts')
316
filename2 = _ssh_host_keys_config_dir()
317
raise errors.TransportError(
318
'Host keys for %s do not match! %s != %s' %
319
(host, our_server_key_hex, server_key_hex),
320
['Try editing %s or %s' % (filename1, filename2)])
322
_paramiko_auth(username, password, host, port, t)
325
def connect_sftp(self, username, password, host, port):
326
t = self._connect(username, password, host, port)
328
return t.open_sftp_client()
329
except paramiko.SSHException as e:
330
self._raise_connection_error(host, port=port, orig_error=e,
331
msg='Unable to start sftp client')
333
def connect_ssh(self, username, password, host, port, command):
334
t = self._connect(username, password, host, port)
336
channel = t.open_session()
337
cmdline = ' '.join(command)
338
channel.exec_command(cmdline)
339
return _ParamikoSSHConnection(channel)
340
except paramiko.SSHException as e:
341
self._raise_connection_error(host, port=port, orig_error=e,
342
msg='Unable to invoke remote bzr')
345
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
346
if paramiko is not None:
347
vendor = ParamikoVendor()
348
register_ssh_vendor('paramiko', vendor)
349
register_ssh_vendor('none', vendor)
350
register_default_ssh_vendor(vendor)
351
_ssh_connection_errors += (paramiko.SSHException,)
355
class SubprocessVendor(SSHVendor):
356
"""Abstract base class for vendors that use pipes to a subprocess."""
358
# In general stderr should be inherited from the parent process so prompts
359
# are visible on the terminal. This can be overriden to another file for
360
# tests, but beware of using PIPE which may hang due to not being read.
361
_stderr_target = None
364
def _check_hostname(arg):
365
if arg.startswith('-'):
366
raise StrangeHostname(hostname=arg)
368
def _connect(self, argv):
369
# Attempt to make a socketpair to use as stdin/stdout for the SSH
370
# subprocess. We prefer sockets to pipes because they support
371
# non-blocking short reads, allowing us to optimistically read 64k (or
374
my_sock, subproc_sock = socket.socketpair()
375
osutils.set_fd_cloexec(my_sock)
376
except (AttributeError, socket.error):
377
# This platform doesn't support socketpair(), so just use ordinary
379
stdin = stdout = subprocess.PIPE
380
my_sock, subproc_sock = None, None
382
stdin = stdout = subproc_sock
383
proc = subprocess.Popen(argv, stdin=stdin, stdout=stdout,
384
stderr=self._stderr_target,
386
**os_specific_subprocess_params())
387
if subproc_sock is not None:
389
return SSHSubprocessConnection(proc, sock=my_sock)
391
def connect_sftp(self, username, password, host, port):
393
argv = self._get_vendor_specific_argv(username, host, port,
395
sock = self._connect(argv)
396
return SFTPClient(SocketAsChannelAdapter(sock))
397
except _ssh_connection_errors as e:
398
self._raise_connection_error(host, port=port, orig_error=e)
400
def connect_ssh(self, username, password, host, port, command):
402
argv = self._get_vendor_specific_argv(username, host, port,
404
return self._connect(argv)
405
except _ssh_connection_errors as e:
406
self._raise_connection_error(host, port=port, orig_error=e)
408
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
410
"""Returns the argument list to run the subprocess with.
412
Exactly one of 'subsystem' and 'command' must be specified.
414
raise NotImplementedError(self._get_vendor_specific_argv)
417
class OpenSSHSubprocessVendor(SubprocessVendor):
418
"""SSH vendor that uses the 'ssh' executable from OpenSSH."""
420
executable_path = 'ssh'
422
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
424
args = [self.executable_path,
425
'-oForwardX11=no', '-oForwardAgent=no',
426
'-oClearAllForwardings=yes',
427
'-oNoHostAuthenticationForLocalhost=yes']
429
args.extend(['-p', str(port)])
430
if username is not None:
431
args.extend(['-l', username])
432
if subsystem is not None:
433
args.extend(['-s', '--', host, subsystem])
435
args.extend(['--', host] + command)
439
register_ssh_vendor('openssh', OpenSSHSubprocessVendor())
442
class SSHCorpSubprocessVendor(SubprocessVendor):
443
"""SSH vendor that uses the 'ssh' executable from SSH Corporation."""
445
executable_path = 'ssh'
447
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
449
self._check_hostname(host)
450
args = [self.executable_path, '-x']
452
args.extend(['-p', str(port)])
453
if username is not None:
454
args.extend(['-l', username])
455
if subsystem is not None:
456
args.extend(['-s', subsystem, host])
458
args.extend([host] + command)
462
register_ssh_vendor('sshcorp', SSHCorpSubprocessVendor())
465
class LSHSubprocessVendor(SubprocessVendor):
466
"""SSH vendor that uses the 'lsh' executable from GNU"""
468
executable_path = 'lsh'
470
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
472
self._check_hostname(host)
473
args = [self.executable_path]
475
args.extend(['-p', str(port)])
476
if username is not None:
477
args.extend(['-l', username])
478
if subsystem is not None:
479
args.extend(['--subsystem', subsystem, host])
481
args.extend([host] + command)
485
register_ssh_vendor('lsh', LSHSubprocessVendor())
488
class PLinkSubprocessVendor(SubprocessVendor):
489
"""SSH vendor that uses the 'plink' executable from Putty."""
491
executable_path = 'plink'
493
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
495
self._check_hostname(host)
496
args = [self.executable_path, '-x', '-a', '-ssh', '-2', '-batch']
498
args.extend(['-P', str(port)])
499
if username is not None:
500
args.extend(['-l', username])
501
if subsystem is not None:
502
args.extend(['-s', host, subsystem])
504
args.extend([host] + command)
508
register_ssh_vendor('plink', PLinkSubprocessVendor())
511
def _paramiko_auth(username, password, host, port, paramiko_transport):
512
auth = config.AuthenticationConfig()
513
# paramiko requires a username, but it might be none if nothing was
514
# supplied. If so, use the local username.
516
username = auth.get_user('ssh', host, port=port,
517
default=getpass.getuser())
518
agent = paramiko.Agent()
519
for key in agent.get_keys():
520
trace.mutter('Trying SSH agent key %s'
521
% hexlify(key.get_fingerprint()).upper())
523
paramiko_transport.auth_publickey(username, key)
525
except paramiko.SSHException as e:
528
# okay, try finding id_rsa or id_dss? (posix only)
529
if _try_pkey_auth(paramiko_transport, paramiko.RSAKey, username, 'id_rsa'):
531
if _try_pkey_auth(paramiko_transport, paramiko.DSSKey, username, 'id_dsa'):
534
# If we have gotten this far, we are about to try for passwords, do an
535
# auth_none check to see if it is even supported.
536
supported_auth_types = []
538
# Note that with paramiko <1.7.5 this logs an INFO message:
539
# Authentication type (none) not permitted.
540
# So we explicitly disable the logging level for this action
541
old_level = paramiko_transport.logger.level
542
paramiko_transport.logger.setLevel(logging.WARNING)
544
paramiko_transport.auth_none(username)
546
paramiko_transport.logger.setLevel(old_level)
547
except paramiko.BadAuthenticationType as e:
548
# Supported methods are in the exception
549
supported_auth_types = e.allowed_types
550
except paramiko.SSHException as e:
551
# Don't know what happened, but just ignore it
553
# We treat 'keyboard-interactive' and 'password' auth methods identically,
554
# because Paramiko's auth_password method will automatically try
555
# 'keyboard-interactive' auth (using the password as the response) if
556
# 'password' auth is not available. Apparently some Debian and Gentoo
557
# OpenSSH servers require this.
558
# XXX: It's possible for a server to require keyboard-interactive auth that
559
# requires something other than a single password, but we currently don't
561
if ('password' not in supported_auth_types and
562
'keyboard-interactive' not in supported_auth_types):
563
raise errors.ConnectionError('Unable to authenticate to SSH host as'
564
'\n %s@%s\nsupported auth types: %s'
565
% (username, host, supported_auth_types))
569
paramiko_transport.auth_password(username, password)
571
except paramiko.SSHException as e:
574
# give up and ask for a password
575
password = auth.get_password('ssh', host, username, port=port)
576
# get_password can still return None, which means we should not prompt
577
if password is not None:
579
paramiko_transport.auth_password(username, password)
580
except paramiko.SSHException as e:
581
raise errors.ConnectionError(
582
'Unable to authenticate to SSH host as'
583
'\n %s@%s\n' % (username, host), e)
585
raise errors.ConnectionError('Unable to authenticate to SSH host as'
586
' %s@%s' % (username, host))
589
def _try_pkey_auth(paramiko_transport, pkey_class, username, filename):
590
filename = os.path.expanduser('~/.ssh/' + filename)
592
key = pkey_class.from_private_key_file(filename)
593
paramiko_transport.auth_publickey(username, key)
595
except paramiko.PasswordRequiredException:
596
password = ui.ui_factory.get_password(
597
prompt=u'SSH %(filename)s password',
598
filename=filename.decode(osutils._fs_enc))
600
key = pkey_class.from_private_key_file(filename, password)
601
paramiko_transport.auth_publickey(username, key)
603
except paramiko.SSHException:
604
trace.mutter('SSH authentication via %s key failed.'
605
% (os.path.basename(filename),))
606
except paramiko.SSHException:
607
trace.mutter('SSH authentication via %s key failed.'
608
% (os.path.basename(filename),))
614
def _ssh_host_keys_config_dir():
615
return osutils.pathjoin(bedding.config_dir(), 'ssh_host_keys')
618
def load_host_keys():
620
Load system host keys (probably doesn't work on windows) and any
621
"discovered" keys from previous sessions.
623
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
625
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(
626
os.path.expanduser('~/.ssh/known_hosts'))
628
trace.mutter('failed to load system host keys: ' + str(e))
629
brz_hostkey_path = _ssh_host_keys_config_dir()
631
BRZ_HOSTKEYS = paramiko.util.load_host_keys(brz_hostkey_path)
633
trace.mutter('failed to load brz host keys: ' + str(e))
637
def save_host_keys():
639
Save "discovered" host keys in $(config)/ssh_host_keys/.
641
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
642
bzr_hostkey_path = _ssh_host_keys_config_dir()
643
bedding.ensure_config_dir_exists()
646
with open(bzr_hostkey_path, 'w') as f:
647
f.write('# SSH host keys collected by bzr\n')
648
for hostname, keys in BRZ_HOSTKEYS.items():
649
for keytype, key in keys.items():
650
f.write('%s %s %s\n' %
651
(hostname, keytype, key.get_base64()))
653
trace.mutter('failed to save bzr host keys: ' + str(e))
656
def os_specific_subprocess_params():
657
"""Get O/S specific subprocess parameters."""
658
if sys.platform == 'win32':
659
# setting the process group and closing fds is not supported on
663
# We close fds other than the pipes as the child process does not need
666
# We also set the child process to ignore SIGINT. Normally the signal
667
# would be sent to every process in the foreground process group, but
668
# this causes it to be seen only by bzr and not by ssh. Python will
669
# generate a KeyboardInterrupt in bzr, and we will then have a chance
670
# to release locks or do other cleanup over ssh before the connection
672
# <https://launchpad.net/products/bzr/+bug/5987>
674
# Running it in a separate process group is not good because then it
675
# can't get non-echoed input of a password or passphrase.
676
# <https://launchpad.net/products/bzr/+bug/40508>
677
return {'preexec_fn': _ignore_signals,
683
_subproc_weakrefs = set()
686
def _close_ssh_proc(proc, sock):
687
"""Carefully close stdin/stdout and reap the SSH process.
689
If the pipes are already closed and/or the process has already been
690
wait()ed on, that's ok, and no error is raised. The goal is to do our best
691
to clean up (whether or not a clean up was already tried).
694
for closeable in (proc.stdin, proc.stdout, sock):
695
# We expect that either proc (a subprocess.Popen) will have stdin and
696
# stdout streams to close, or that we will have been passed a socket to
697
# close, with the option not in use being None.
698
if closeable is not None:
699
funcs.append(closeable.close)
700
funcs.append(proc.wait)
705
# It's ok for the pipe to already be closed, or the process to
706
# already be finished.
710
class SSHConnection(object):
711
"""Abstract base class for SSH connections."""
713
def get_sock_or_pipes(self):
714
"""Returns a (kind, io_object) pair.
716
If kind == 'socket', then io_object is a socket.
718
If kind == 'pipes', then io_object is a pair of file-like objects
719
(read_from, write_to).
721
raise NotImplementedError(self.get_sock_or_pipes)
724
raise NotImplementedError(self.close)
727
class SSHSubprocessConnection(SSHConnection):
728
"""A connection to an ssh subprocess via pipes or a socket.
730
This class is also socket-like enough to be used with
731
SocketAsChannelAdapter (it has 'send' and 'recv' methods).
734
def __init__(self, proc, sock=None):
737
:param proc: a subprocess.Popen
738
:param sock: if proc.stdin/out is a socket from a socketpair, then sock
739
should breezy's half of that socketpair. If not passed, proc's
740
stdin/out is assumed to be ordinary pipes.
744
# Add a weakref to proc that will attempt to do the same as self.close
745
# to avoid leaving processes lingering indefinitely.
748
_subproc_weakrefs.remove(ref)
749
_close_ssh_proc(proc, sock)
750
_subproc_weakrefs.add(weakref.ref(self, terminate))
752
def send(self, data):
753
if self._sock is not None:
754
return self._sock.send(data)
756
return os.write(self.proc.stdin.fileno(), data)
758
def recv(self, count):
759
if self._sock is not None:
760
return self._sock.recv(count)
762
return os.read(self.proc.stdout.fileno(), count)
765
_close_ssh_proc(self.proc, self._sock)
767
def get_sock_or_pipes(self):
768
if self._sock is not None:
769
return 'socket', self._sock
771
return 'pipes', (self.proc.stdout, self.proc.stdin)
774
class _ParamikoSSHConnection(SSHConnection):
775
"""An SSH connection via paramiko."""
777
def __init__(self, channel):
778
self.channel = channel
780
def get_sock_or_pipes(self):
781
return ('socket', self.channel)
784
return self.channel.close()