43
47
from paramiko.sftp_client import SFTPClient
50
class StrangeHostname(errors.BzrError):
51
_fmt = "Refusing to connect to strange SSH hostname %(hostname)s"
46
54
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))
59
58
class SSHVendorManager(object):
60
59
"""Manager for manage SSH vendors."""
62
61
# Note, although at first sign the class interface seems similar to
63
# bzrlib.registry.Registry it is not possible/convenient to directly use
62
# breezy.registry.Registry it is not possible/convenient to directly use
64
63
# the Registry because the class just has "get()" interface instead of the
65
64
# Registry's "get(key)".
126
126
elif 'SSH Secure Shell' in version:
127
127
trace.mutter('ssh implementation is SSH Corp.')
128
128
vendor = SSHCorpSubprocessVendor()
129
elif 'lsh' in version:
130
trace.mutter('ssh implementation is GNU lsh.')
131
vendor = LSHSubprocessVendor()
129
132
# As plink user prompts are not handled currently, don't auto-detect
130
133
# it by inspection below, but keep this vendor detection for if a path
131
# is given in BZR_SSH. See https://bugs.launchpad.net/bugs/414743
134
# is given in BRZ_SSH. See https://bugs.launchpad.net/bugs/414743
132
135
elif 'plink' in version and progname == 'plink':
133
136
# Checking if "plink" was the executed argument as Windows
134
# sometimes reports 'ssh -V' incorrectly with 'plink' in it's
137
# sometimes reports 'ssh -V' incorrectly with 'plink' in its
135
138
# version. See https://bugs.launchpad.net/bzr/+bug/107155
136
139
trace.mutter("ssh implementation is Putty's plink.")
137
140
vendor = PLinkSubprocessVendor()
145
148
def _get_vendor_from_path(self, path):
146
149
"""Return the vendor or None using the program at the given path"""
147
150
version = self._get_ssh_version_string([path, '-V'])
148
return self._get_vendor_by_version_string(version,
149
os.path.splitext(os.path.basename(path))[0])
151
return self._get_vendor_by_version_string(version,
152
os.path.splitext(os.path.basename(path))[0])
151
154
def get_vendor(self, environment=None):
152
155
"""Find out what version of SSH is on the system.
154
157
:raises SSHVendorNotFound: if no any SSH vendor is found
155
:raises UnknownSSH: if the BZR_SSH environment variable contains
158
:raises UnknownSSH: if the BRZ_SSH environment variable contains
156
159
unknown vendor name
158
161
if self._cached_ssh_vendor is None:
262
265
sock = socket.socket()
264
267
sock.connect((host, port))
265
except socket.error, e:
268
except socket.error as e:
266
269
self._raise_connection_error(host, port=port, orig_error=e)
267
270
return SFTPClient(SocketAsChannelAdapter(sock))
269
273
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()
283
276
class ParamikoVendor(SSHVendor):
284
277
"""Vendor that uses paramiko."""
279
def _hexify(self, s):
280
return hexlify(s).upper()
286
282
def _connect(self, username, password, host, port):
287
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
283
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
292
288
t = paramiko.Transport((host, port or 22))
293
289
t.set_log_channel('bzr.paramiko')
295
except (paramiko.SSHException, socket.error), e:
291
except (paramiko.SSHException, socket.error) as e:
296
292
self._raise_connection_error(host, port=port, orig_error=e)
298
294
server_key = t.get_remote_server_key()
299
server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
295
server_key_hex = self._hexify(server_key.get_fingerprint())
300
296
keytype = server_key.get_name()
301
297
if host in SYSTEM_HOSTKEYS and keytype in SYSTEM_HOSTKEYS[host]:
302
298
our_server_key = SYSTEM_HOSTKEYS[host][keytype]
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())
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())
310
304
trace.warning('Adding %s host key for %s: %s'
311
305
% (keytype, host, server_key_hex))
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)
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)
316
BZR_HOSTKEYS.setdefault(host, {})[keytype] = server_key
310
BRZ_HOSTKEYS.setdefault(host, {})[keytype] = server_key
317
311
our_server_key = server_key
318
our_server_key_hex = paramiko.util.hexify(
319
our_server_key.get_fingerprint())
312
our_server_key_hex = self._hexify(our_server_key.get_fingerprint())
321
314
if server_key != our_server_key:
322
315
filename1 = os.path.expanduser('~/.ssh/known_hosts')
323
filename2 = osutils.pathjoin(config.config_dir(), 'ssh_host_keys')
316
filename2 = _ssh_host_keys_config_dir()
324
317
raise errors.TransportError(
325
318
'Host keys for %s do not match! %s != %s' %
326
319
(host, our_server_key_hex, server_key_hex),
344
337
cmdline = ' '.join(command)
345
338
channel.exec_command(cmdline)
346
339
return _ParamikoSSHConnection(channel)
347
except paramiko.SSHException, e:
340
except paramiko.SSHException as e:
348
341
self._raise_connection_error(host, port=port, orig_error=e,
349
342
msg='Unable to invoke remote bzr')
345
_ssh_connection_errors = (EOFError, OSError, IOError, socket.error)
351
346
if paramiko is not None:
352
347
vendor = ParamikoVendor()
353
348
register_ssh_vendor('paramiko', vendor)
354
349
register_ssh_vendor('none', vendor)
355
350
register_default_ssh_vendor(vendor)
356
_sftp_connection_errors = (EOFError, paramiko.SSHException)
351
_ssh_connection_errors += (paramiko.SSHException,)
359
_sftp_connection_errors = (EOFError,)
362
355
class SubprocessVendor(SSHVendor):
363
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)
365
368
def _connect(self, argv):
366
proc = subprocess.Popen(argv,
367
stdin=subprocess.PIPE,
368
stdout=subprocess.PIPE,
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,
369
386
**os_specific_subprocess_params())
370
return SSHSubprocess(proc)
387
if subproc_sock is not None:
389
return SSHSubprocessConnection(proc, sock=my_sock)
372
391
def connect_sftp(self, username, password, host, port):
375
394
subsystem='sftp')
376
395
sock = self._connect(argv)
377
396
return SFTPClient(SocketAsChannelAdapter(sock))
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,):
397
except _ssh_connection_errors as e:
386
398
self._raise_connection_error(host, port=port, orig_error=e)
388
400
def connect_ssh(self, username, password, host, port, command):
390
402
argv = self._get_vendor_specific_argv(username, host, port,
392
404
return self._connect(argv)
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,):
405
except _ssh_connection_errors as e:
401
406
self._raise_connection_error(host, port=port, orig_error=e)
403
408
def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
419
424
args = [self.executable_path,
420
425
'-oForwardX11=no', '-oForwardAgent=no',
421
'-oClearAllForwardings=yes', '-oProtocol=2',
426
'-oClearAllForwardings=yes',
422
427
'-oNoHostAuthenticationForLocalhost=yes']
423
428
if port is not None:
424
429
args.extend(['-p', str(port)])
425
430
if username is not None:
426
431
args.extend(['-l', username])
427
432
if subsystem is not None:
428
args.extend(['-s', host, subsystem])
433
args.extend(['-s', '--', host, subsystem])
430
args.extend([host] + command)
435
args.extend(['--', host] + command)
433
439
register_ssh_vendor('openssh', OpenSSHSubprocessVendor())
451
458
args.extend([host] + command)
454
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())
457
488
class PLinkSubprocessVendor(SubprocessVendor):
458
489
"""SSH vendor that uses the 'plink' executable from Putty."""
482
515
if username is None:
483
516
username = auth.get_user('ssh', host, port=port,
484
517
default=getpass.getuser())
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:
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:
496
528
# okay, try finding id_rsa or id_dss? (posix only)
497
529
if _try_pkey_auth(paramiko_transport, paramiko.RSAKey, username, 'id_rsa'):
527
559
# requires something other than a single password, but we currently don't
529
561
if ('password' not in supported_auth_types and
530
'keyboard-interactive' not in supported_auth_types):
562
'keyboard-interactive' not in supported_auth_types):
531
563
raise errors.ConnectionError('Unable to authenticate to SSH host as'
532
'\n %s@%s\nsupported auth types: %s'
533
% (username, host, supported_auth_types))
564
'\n %s@%s\nsupported auth types: %s'
565
% (username, host, supported_auth_types))
537
569
paramiko_transport.auth_password(username, password)
539
except paramiko.SSHException, e:
571
except paramiko.SSHException as e:
542
574
# give up and ask for a password
614
def _ssh_host_keys_config_dir():
615
return osutils.pathjoin(bedding.config_dir(), 'ssh_host_keys')
581
618
def load_host_keys():
583
620
Load system host keys (probably doesn't work on windows) and any
584
621
"discovered" keys from previous sessions.
586
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
623
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
588
625
SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(
589
626
os.path.expanduser('~/.ssh/known_hosts'))
591
628
trace.mutter('failed to load system host keys: ' + str(e))
592
bzr_hostkey_path = osutils.pathjoin(config.config_dir(), 'ssh_host_keys')
629
brz_hostkey_path = _ssh_host_keys_config_dir()
594
BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
596
trace.mutter('failed to load bzr host keys: ' + str(e))
631
BRZ_HOSTKEYS = paramiko.util.load_host_keys(brz_hostkey_path)
633
trace.mutter('failed to load brz host keys: ' + str(e))
602
639
Save "discovered" host keys in $(config)/ssh_host_keys/.
604
global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
605
bzr_hostkey_path = osutils.pathjoin(config.config_dir(), 'ssh_host_keys')
606
config.ensure_config_dir_exists()
641
global SYSTEM_HOSTKEYS, BRZ_HOSTKEYS
642
bzr_hostkey_path = _ssh_host_keys_config_dir()
643
bedding.ensure_config_dir_exists()
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
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()))
616
653
trace.mutter('failed to save bzr host keys: ' + str(e))
641
678
'close_fds': True,
645
683
_subproc_weakrefs = set()
647
def _close_ssh_proc(proc):
648
for func in [proc.stdin.close, proc.stdout.close, proc.wait]:
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)
655
class SSHSubprocess(object):
656
"""A socket-like object that talks to an ssh subprocess via pipes."""
658
def __init__(self, proc):
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.
660
744
# Add a weakref to proc that will attempt to do the same as self.close
661
745
# to avoid leaving processes lingering indefinitely.
662
747
def terminate(ref):
663
748
_subproc_weakrefs.remove(ref)
664
_close_ssh_proc(proc)
749
_close_ssh_proc(proc, sock)
665
750
_subproc_weakrefs.add(weakref.ref(self, terminate))
667
752
def send(self, data):
668
return os.write(self.proc.stdin.fileno(), data)
753
if self._sock is not None:
754
return self._sock.send(data)
756
return os.write(self.proc.stdin.fileno(), data)
670
758
def recv(self, count):
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)
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()