47
43
from paramiko.sftp_client import SFTPClient
50
class StrangeHostname(errors.BzrError):
51
_fmt = "Refusing to connect to strange SSH hostname %(hostname)s"
54
46
SYSTEM_HOSTKEYS = {}
50
_paramiko_version = getattr(paramiko, '__version_info__', (0, 0, 0))
52
# Paramiko 1.5 tries to open a socket.AF_UNIX in order to connect
53
# to ssh-agent. That attribute doesn't exist on win32 (it does in cygwin)
54
# so we get an AttributeError exception. So we will not try to
55
# connect to an agent if we are on win32 and using Paramiko older than 1.6
56
_use_ssh_agent = (sys.platform != 'win32' or _paramiko_version >= (1, 6, 0))
58
59
class SSHVendorManager(object):
59
60
"""Manager for manage SSH vendors."""
61
62
# Note, although at first sign the class interface seems similar to
62
# breezy.registry.Registry it is not possible/convenient to directly use
63
# bzrlib.registry.Registry it is not possible/convenient to directly use
63
64
# the Registry because the class just has "get()" interface instead of the
64
65
# Registry's "get(key)".
119
126
elif 'SSH Secure Shell' in version:
120
127
trace.mutter('ssh implementation is SSH Corp.')
121
128
vendor = SSHCorpSubprocessVendor()
122
elif 'lsh' in version:
123
trace.mutter('ssh implementation is GNU lsh.')
124
vendor = LSHSubprocessVendor()
125
129
# As plink user prompts are not handled currently, don't auto-detect
126
130
# it by inspection below, but keep this vendor detection for if a path
127
# is given in BRZ_SSH. See https://bugs.launchpad.net/bugs/414743
131
# is given in BZR_SSH. See https://bugs.launchpad.net/bugs/414743
128
132
elif 'plink' in version and progname == 'plink':
129
133
# Checking if "plink" was the executed argument as Windows
130
# sometimes reports 'ssh -V' incorrectly with 'plink' in its
134
# sometimes reports 'ssh -V' incorrectly with 'plink' in it's
131
135
# version. See https://bugs.launchpad.net/bzr/+bug/107155
132
136
trace.mutter("ssh implementation is Putty's plink.")
133
137
vendor = PLinkSubprocessVendor()
141
145
def _get_vendor_from_path(self, path):
142
146
"""Return the vendor or None using the program at the given path"""
143
147
version = self._get_ssh_version_string([path, '-V'])
144
return self._get_vendor_by_version_string(version,
145
os.path.splitext(os.path.basename(path))[0])
148
return self._get_vendor_by_version_string(version,
149
os.path.splitext(os.path.basename(path))[0])
147
def get_vendor(self):
151
def get_vendor(self, environment=None):
148
152
"""Find out what version of SSH is on the system.
150
154
:raises SSHVendorNotFound: if no any SSH vendor is found
151
:raises UnknownSSH: if the BRZ_SSH environment variable contains
155
:raises UnknownSSH: if the BZR_SSH environment variable contains
152
156
unknown vendor name
154
158
if self._cached_ssh_vendor is None:
155
vendor = self._get_vendor_by_config()
159
vendor = self._get_vendor_by_environment(environment)
156
160
if vendor is None:
157
161
vendor = self._get_vendor_by_inspection()
158
162
if vendor is None:
258
262
sock = socket.socket()
260
264
sock.connect((host, port))
261
except socket.error as e:
265
except socket.error, e:
262
266
self._raise_connection_error(host, port=port, orig_error=e)
263
267
return SFTPClient(SocketAsChannelAdapter(sock))
266
269
register_ssh_vendor('loopback', LoopbackVendor())
272
class _ParamikoSSHConnection(object):
273
def __init__(self, channel):
274
self.channel = channel
276
def get_filelike_channels(self):
277
return self.channel.makefile('rb'), self.channel.makefile('wb')
280
return self.channel.close()
269
283
class ParamikoVendor(SSHVendor):
270
284
"""Vendor that uses paramiko."""
272
def _hexify(self, s):
273
return hexlify(s).upper()
275
286
def _connect(self, username, password, host, port):
276
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
287
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
281
292
t = paramiko.Transport((host, port or 22))
282
293
t.set_log_channel('bzr.paramiko')
284
except (paramiko.SSHException, socket.error) as e:
295
except (paramiko.SSHException, socket.error), e:
285
296
self._raise_connection_error(host, port=port, orig_error=e)
287
298
server_key = t.get_remote_server_key()
288
server_key_hex = self._hexify(server_key.get_fingerprint())
299
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
289
300
keytype = server_key.get_name()
290
301
if host in SYSTEM_HOSTKEYS and keytype in SYSTEM_HOSTKEYS[host]:
291
302
our_server_key = SYSTEM_HOSTKEYS[host][keytype]
292
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
293
elif host in BRZ_HOSTKEYS and keytype in BRZ_HOSTKEYS[host]:
294
our_server_key = BRZ_HOSTKEYS[host][keytype]
295
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
303
our_server_key_hex = paramiko.util.hexify(
304
our_server_key.get_fingerprint())
305
elif host in BZR_HOSTKEYS and keytype in BZR_HOSTKEYS[host]:
306
our_server_key = BZR_HOSTKEYS[host][keytype]
307
our_server_key_hex = paramiko.util.hexify(
308
our_server_key.get_fingerprint())
297
310
trace.warning('Adding %s host key for %s: %s'
298
311
% (keytype, host, server_key_hex))
299
add = getattr(BRZ_HOSTKEYS, 'add', None)
300
if add is not None: # paramiko >= 1.X.X
301
BRZ_HOSTKEYS.add(host, keytype, server_key)
312
add = getattr(BZR_HOSTKEYS, 'add', None)
313
if add is not None: # paramiko >= 1.X.X
314
BZR_HOSTKEYS.add(host, keytype, server_key)
303
BRZ_HOSTKEYS.setdefault(host, {})[keytype] = server_key
316
BZR_HOSTKEYS.setdefault(host, {})[keytype] = server_key
304
317
our_server_key = server_key
305
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
318
our_server_key_hex = paramiko.util.hexify(
319
our_server_key.get_fingerprint())
307
321
if server_key != our_server_key:
308
322
filename1 = os.path.expanduser('~/.ssh/known_hosts')
309
filename2 = _ssh_host_keys_config_dir()
323
filename2 = osutils.pathjoin(config.config_dir(), 'ssh_host_keys')
310
324
raise errors.TransportError(
311
325
'Host keys for %s do not match! %s != %s' %
312
326
(host, our_server_key_hex, server_key_hex),
330
344
cmdline = ' '.join(command)
331
345
channel.exec_command(cmdline)
332
346
return _ParamikoSSHConnection(channel)
333
except paramiko.SSHException as e:
347
except paramiko.SSHException, e:
334
348
self._raise_connection_error(host, port=port, orig_error=e,
335
349
msg='Unable to invoke remote bzr')
338
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
339
351
if paramiko is not None:
340
352
vendor = ParamikoVendor()
341
353
register_ssh_vendor('paramiko', vendor)
342
354
register_ssh_vendor('none', vendor)
343
355
register_default_ssh_vendor(vendor)
344
_ssh_connection_errors += (paramiko.SSHException,)
356
_sftp_connection_errors = (EOFError, paramiko.SSHException)
359
_sftp_connection_errors = (EOFError,)
348
362
class SubprocessVendor(SSHVendor):
349
363
"""Abstract base class for vendors that use pipes to a subprocess."""
351
# In general stderr should be inherited from the parent process so prompts
352
# are visible on the terminal. This can be overriden to another file for
353
# tests, but beware of using PIPE which may hang due to not being read.
354
_stderr_target = None
357
def _check_hostname(arg):
358
if arg.startswith('-'):
359
raise StrangeHostname(hostname=arg)
361
365
def _connect(self, argv):
362
# Attempt to make a socketpair to use as stdin/stdout for the SSH
363
# subprocess. We prefer sockets to pipes because they support
364
# non-blocking short reads, allowing us to optimistically read 64k (or
367
my_sock, subproc_sock = socket.socketpair()
368
osutils.set_fd_cloexec(my_sock)
369
except (AttributeError, socket.error):
370
# This platform doesn't support socketpair(), so just use ordinary
372
stdin = stdout = subprocess.PIPE
373
my_sock, subproc_sock = None, None
375
stdin = stdout = subproc_sock
376
proc = subprocess.Popen(argv, stdin=stdin, stdout=stdout,
377
stderr=self._stderr_target,
366
proc = subprocess.Popen(argv,
367
stdin=subprocess.PIPE,
368
stdout=subprocess.PIPE,
379
369
**os_specific_subprocess_params())
380
if subproc_sock is not None:
382
return SSHSubprocessConnection(proc, sock=my_sock)
370
return SSHSubprocess(proc)
384
372
def connect_sftp(self, username, password, host, port):
387
375
subsystem='sftp')
388
376
sock = self._connect(argv)
389
377
return SFTPClient(SocketAsChannelAdapter(sock))
390
except _ssh_connection_errors as e:
378
except _sftp_connection_errors, e:
379
self._raise_connection_error(host, port=port, orig_error=e)
380
except (OSError, IOError), e:
381
# If the machine is fast enough, ssh can actually exit
382
# before we try and send it the sftp request, which
383
# raises a Broken Pipe
384
if e.errno not in (errno.EPIPE,):
391
386
self._raise_connection_error(host, port=port, orig_error=e)
393
388
def connect_ssh(self, username, password, host, port, command):
395
390
argv = self._get_vendor_specific_argv(username, host, port,
397
392
return self._connect(argv)
398
except _ssh_connection_errors as e:
393
except (EOFError), e:
394
self._raise_connection_error(host, port=port, orig_error=e)
395
except (OSError, IOError), e:
396
# If the machine is fast enough, ssh can actually exit
397
# before we try and send it the sftp request, which
398
# raises a Broken Pipe
399
if e.errno not in (errno.EPIPE,):
399
401
self._raise_connection_error(host, port=port, orig_error=e)
401
403
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
417
419
args = [self.executable_path,
418
420
'-oForwardX11=no', '-oForwardAgent=no',
419
'-oClearAllForwardings=yes',
421
'-oClearAllForwardings=yes', '-oProtocol=2',
420
422
'-oNoHostAuthenticationForLocalhost=yes']
421
423
if port is not None:
422
424
args.extend(['-p', str(port)])
423
425
if username is not None:
424
426
args.extend(['-l', username])
425
427
if subsystem is not None:
426
args.extend(['-s', '--', host, subsystem])
428
args.extend(['-s', host, subsystem])
428
args.extend(['--', host] + command)
430
args.extend([host] + command)
432
433
register_ssh_vendor('openssh', OpenSSHSubprocessVendor())
451
451
args.extend([host] + command)
455
454
register_ssh_vendor('sshcorp', SSHCorpSubprocessVendor())
458
class LSHSubprocessVendor(SubprocessVendor):
459
"""SSH vendor that uses the 'lsh' executable from GNU"""
461
executable_path = 'lsh'
463
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
465
self._check_hostname(host)
466
args = [self.executable_path]
468
args.extend(['-p', str(port)])
469
if username is not None:
470
args.extend(['-l', username])
471
if subsystem is not None:
472
args.extend(['--subsystem', subsystem, host])
474
args.extend([host] + command)
478
register_ssh_vendor('lsh', LSHSubprocessVendor())
481
457
class PLinkSubprocessVendor(SubprocessVendor):
482
458
"""SSH vendor that uses the 'plink' executable from Putty."""
508
482
if username is None:
509
483
username = auth.get_user('ssh', host, port=port,
510
484
default=getpass.getuser())
511
agent = paramiko.Agent()
512
for key in agent.get_keys():
513
trace.mutter('Trying SSH agent key %s'
514
% hexlify(key.get_fingerprint()).upper())
516
paramiko_transport.auth_publickey(username, key)
518
except paramiko.SSHException as e:
486
agent = paramiko.Agent()
487
for key in agent.get_keys():
488
trace.mutter('Trying SSH agent key %s'
489
% paramiko.util.hexify(key.get_fingerprint()))
491
paramiko_transport.auth_publickey(username, key)
493
except paramiko.SSHException, e:
521
496
# okay, try finding id_rsa or id_dss? (posix only)
522
497
if _try_pkey_auth(paramiko_transport, paramiko.RSAKey, username, 'id_rsa'):
552
527
# requires something other than a single password, but we currently don't
554
529
if ('password' not in supported_auth_types and
555
'keyboard-interactive' not in supported_auth_types):
530
'keyboard-interactive' not in supported_auth_types):
556
531
raise errors.ConnectionError('Unable to authenticate to SSH host as'
557
'\n %s@%s\nsupported auth types: %s'
558
% (username, host, supported_auth_types))
532
'\n %s@%s\nsupported auth types: %s'
533
% (username, host, supported_auth_types))
562
537
paramiko_transport.auth_password(username, password)
564
except paramiko.SSHException as e:
539
except paramiko.SSHException, e:
567
542
# give up and ask for a password
607
def _ssh_host_keys_config_dir():
608
return osutils.pathjoin(bedding.config_dir(), 'ssh_host_keys')
611
581
def load_host_keys():
613
583
Load system host keys (probably doesn't work on windows) and any
614
584
"discovered" keys from previous sessions.
616
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
586
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
618
588
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(
619
589
os.path.expanduser('~/.ssh/known_hosts'))
621
591
trace.mutter('failed to load system host keys: ' + str(e))
622
brz_hostkey_path = _ssh_host_keys_config_dir()
592
bzr_hostkey_path = osutils.pathjoin(config.config_dir(), 'ssh_host_keys')
624
BRZ_HOSTKEYS = paramiko.util.load_host_keys(brz_hostkey_path)
626
trace.mutter('failed to load brz host keys: ' + str(e))
594
BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
596
trace.mutter('failed to load bzr host keys: ' + str(e))
632
602
Save "discovered" host keys in $(config)/ssh_host_keys/.
634
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
635
bzr_hostkey_path = _ssh_host_keys_config_dir()
636
bedding.ensure_config_dir_exists()
604
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
605
bzr_hostkey_path = osutils.pathjoin(config.config_dir(), 'ssh_host_keys')
606
config.ensure_config_dir_exists()
639
with open(bzr_hostkey_path, 'w') as f:
640
f.write('# SSH host keys collected by bzr\n')
641
for hostname, keys in BRZ_HOSTKEYS.items():
642
for keytype, key in keys.items():
643
f.write('%s %s %s\n' %
644
(hostname, keytype, key.get_base64()))
609
f = open(bzr_hostkey_path, 'w')
610
f.write('# SSH host keys collected by bzr\n')
611
for hostname, keys in BZR_HOSTKEYS.iteritems():
612
for keytype, key in keys.iteritems():
613
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
646
616
trace.mutter('failed to save bzr host keys: ' + str(e))
671
641
'close_fds': True,
676
645
_subproc_weakrefs = set()
679
def _close_ssh_proc(proc, sock):
680
"""Carefully close stdin/stdout and reap the SSH process.
682
If the pipes are already closed and/or the process has already been
683
wait()ed on, that's ok, and no error is raised. The goal is to do our best
684
to clean up (whether or not a clean up was already tried).
687
for closeable in (proc.stdin, proc.stdout, sock):
688
# We expect that either proc (a subprocess.Popen) will have stdin and
689
# stdout streams to close, or that we will have been passed a socket to
690
# close, with the option not in use being None.
691
if closeable is not None:
692
funcs.append(closeable.close)
693
funcs.append(proc.wait)
647
def _close_ssh_proc(proc):
648
for func in [proc.stdin.close, proc.stdout.close, proc.wait]:
698
# It's ok for the pipe to already be closed, or the process to
699
# already be finished.
703
class SSHConnection(object):
704
"""Abstract base class for SSH connections."""
706
def get_sock_or_pipes(self):
707
"""Returns a (kind, io_object) pair.
709
If kind == 'socket', then io_object is a socket.
711
If kind == 'pipes', then io_object is a pair of file-like objects
712
(read_from, write_to).
714
raise NotImplementedError(self.get_sock_or_pipes)
717
raise NotImplementedError(self.close)
720
class SSHSubprocessConnection(SSHConnection):
721
"""A connection to an ssh subprocess via pipes or a socket.
723
This class is also socket-like enough to be used with
724
SocketAsChannelAdapter (it has 'send' and 'recv' methods).
727
def __init__(self, proc, sock=None):
730
:param proc: a subprocess.Popen
731
:param sock: if proc.stdin/out is a socket from a socketpair, then sock
732
should breezy's half of that socketpair. If not passed, proc's
733
stdin/out is assumed to be ordinary pipes.
655
class SSHSubprocess(object):
656
"""A socket-like object that talks to an ssh subprocess via pipes."""
658
def __init__(self, proc):
737
660
# Add a weakref to proc that will attempt to do the same as self.close
738
661
# to avoid leaving processes lingering indefinitely.
740
662
def terminate(ref):
741
663
_subproc_weakrefs.remove(ref)
742
_close_ssh_proc(proc, sock)
664
_close_ssh_proc(proc)
743
665
_subproc_weakrefs.add(weakref.ref(self, terminate))
745
667
def send(self, data):
746
if self._sock is not None:
747
return self._sock.send(data)
749
return os.write(self.proc.stdin.fileno(), data)
668
return os.write(self.proc.stdin.fileno(), data)
751
670
def recv(self, count):
752
if self._sock is not None:
753
return self._sock.recv(count)
755
return os.read(self.proc.stdout.fileno(), count)
758
_close_ssh_proc(self.proc, self._sock)
760
def get_sock_or_pipes(self):
761
if self._sock is not None:
762
return 'socket', self._sock
764
return 'pipes', (self.proc.stdout, self.proc.stdin)
767
class _ParamikoSSHConnection(SSHConnection):
768
"""An SSH connection via paramiko."""
770
def __init__(self, channel):
771
self.channel = channel
773
def get_sock_or_pipes(self):
774
return ('socket', self.channel)
777
return self.channel.close()
671
return os.read(self.proc.stdout.fileno(), count)
674
_close_ssh_proc(self.proc)
676
def get_filelike_channels(self):
677
return (self.proc.stdout, self.proc.stdin)