/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/ssh.py

  • Committer: Matthew Fuller
  • Date: 2006-11-11 19:20:08 UTC
  • mto: This revision was merged to the branch mainline in revision 2136.
  • Revision ID: fullermd@over-yonder.net-20061111192008-klzw8naola7mde0f
Correct statement about the precedence of $EDITOR, and mention
$VISUAL.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Robey Pointer <robey@lag.net>
 
2
# Copyright (C) 2005, 2006 Canonical Ltd
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
 
 
18
"""Foundation SSH support for SFTP and smart server."""
 
19
 
 
20
import errno
 
21
import getpass
 
22
import os
 
23
import socket
 
24
import subprocess
 
25
import sys
 
26
 
 
27
from bzrlib.config import config_dir, ensure_config_dir_exists
 
28
from bzrlib.errors import (ConnectionError,
 
29
                           ParamikoNotPresent,
 
30
                           SocketConnectionError,
 
31
                           TransportError,
 
32
                           UnknownSSH,
 
33
                           )
 
34
 
 
35
from bzrlib.osutils import pathjoin
 
36
from bzrlib.trace import mutter, warning
 
37
import bzrlib.ui
 
38
 
 
39
try:
 
40
    import paramiko
 
41
except ImportError, e:
 
42
    # If we have an ssh subprocess, we don't strictly need paramiko for all ssh
 
43
    # access
 
44
    paramiko = None
 
45
else:
 
46
    from paramiko.sftp_client import SFTPClient
 
47
 
 
48
 
 
49
SYSTEM_HOSTKEYS = {}
 
50
BZR_HOSTKEYS = {}
 
51
 
 
52
 
 
53
_paramiko_version = getattr(paramiko, '__version_info__', (0, 0, 0))
 
54
 
 
55
# Paramiko 1.5 tries to open a socket.AF_UNIX in order to connect
 
56
# to ssh-agent. That attribute doesn't exist on win32 (it does in cygwin)
 
57
# so we get an AttributeError exception. So we will not try to
 
58
# connect to an agent if we are on win32 and using Paramiko older than 1.6
 
59
_use_ssh_agent = (sys.platform != 'win32' or _paramiko_version >= (1, 6, 0))
 
60
 
 
61
_ssh_vendors = {}
 
62
 
 
63
def register_ssh_vendor(name, vendor):
 
64
    """Register SSH vendor."""
 
65
    _ssh_vendors[name] = vendor
 
66
 
 
67
    
 
68
_ssh_vendor = None
 
69
def _get_ssh_vendor():
 
70
    """Find out what version of SSH is on the system."""
 
71
    global _ssh_vendor
 
72
    if _ssh_vendor is not None:
 
73
        return _ssh_vendor
 
74
 
 
75
    if 'BZR_SSH' in os.environ:
 
76
        vendor_name = os.environ['BZR_SSH']
 
77
        try:
 
78
            _ssh_vendor = _ssh_vendors[vendor_name]
 
79
        except KeyError:
 
80
            raise UnknownSSH(vendor_name)
 
81
        return _ssh_vendor
 
82
 
 
83
    try:
 
84
        p = subprocess.Popen(['ssh', '-V'],
 
85
                             stdin=subprocess.PIPE,
 
86
                             stdout=subprocess.PIPE,
 
87
                             stderr=subprocess.PIPE,
 
88
                             **os_specific_subprocess_params())
 
89
        returncode = p.returncode
 
90
        stdout, stderr = p.communicate()
 
91
    except OSError:
 
92
        returncode = -1
 
93
        stdout = stderr = ''
 
94
    if 'OpenSSH' in stderr:
 
95
        mutter('ssh implementation is OpenSSH')
 
96
        _ssh_vendor = OpenSSHSubprocessVendor()
 
97
    elif 'SSH Secure Shell' in stderr:
 
98
        mutter('ssh implementation is SSH Corp.')
 
99
        _ssh_vendor = SSHCorpSubprocessVendor()
 
100
 
 
101
    if _ssh_vendor is not None:
 
102
        return _ssh_vendor
 
103
 
 
104
    # XXX: 20051123 jamesh
 
105
    # A check for putty's plink or lsh would go here.
 
106
 
 
107
    mutter('falling back to paramiko implementation')
 
108
    _ssh_vendor = ParamikoVendor()
 
109
    return _ssh_vendor
 
110
 
 
111
 
 
112
def _ignore_sigint():
 
113
    # TODO: This should possibly ignore SIGHUP as well, but bzr currently
 
114
    # doesn't handle it itself.
 
115
    # <https://launchpad.net/products/bzr/+bug/41433/+index>
 
116
    import signal
 
117
    signal.signal(signal.SIGINT, signal.SIG_IGN)
 
118
    
 
119
 
 
120
 
 
121
class LoopbackSFTP(object):
 
122
    """Simple wrapper for a socket that pretends to be a paramiko Channel."""
 
123
 
 
124
    def __init__(self, sock):
 
125
        self.__socket = sock
 
126
 
 
127
    def send(self, data):
 
128
        return self.__socket.send(data)
 
129
 
 
130
    def recv(self, n):
 
131
        return self.__socket.recv(n)
 
132
 
 
133
    def recv_ready(self):
 
134
        return True
 
135
 
 
136
    def close(self):
 
137
        self.__socket.close()
 
138
 
 
139
 
 
140
class SSHVendor(object):
 
141
    """Abstract base class for SSH vendor implementations."""
 
142
    
 
143
    def connect_sftp(self, username, password, host, port):
 
144
        """Make an SSH connection, and return an SFTPClient.
 
145
        
 
146
        :param username: an ascii string
 
147
        :param password: an ascii string
 
148
        :param host: a host name as an ascii string
 
149
        :param port: a port number
 
150
        :type port: int
 
151
 
 
152
        :raises: ConnectionError if it cannot connect.
 
153
 
 
154
        :rtype: paramiko.sftp_client.SFTPClient
 
155
        """
 
156
        raise NotImplementedError(self.connect_sftp)
 
157
 
 
158
    def connect_ssh(self, username, password, host, port, command):
 
159
        """Make an SSH connection.
 
160
        
 
161
        :returns: something with a `close` method, and a `get_filelike_channels`
 
162
            method that returns a pair of (read, write) filelike objects.
 
163
        """
 
164
        raise NotImplementedError(self.connect_ssh)
 
165
        
 
166
    def _raise_connection_error(self, host, port=None, orig_error=None,
 
167
                                msg='Unable to connect to SSH host'):
 
168
        """Raise a SocketConnectionError with properly formatted host.
 
169
 
 
170
        This just unifies all the locations that try to raise ConnectionError,
 
171
        so that they format things properly.
 
172
        """
 
173
        raise SocketConnectionError(host=host, port=port, msg=msg,
 
174
                                    orig_error=orig_error)
 
175
 
 
176
 
 
177
class LoopbackVendor(SSHVendor):
 
178
    """SSH "vendor" that connects over a plain TCP socket, not SSH."""
 
179
    
 
180
    def connect_sftp(self, username, password, host, port):
 
181
        sock = socket.socket()
 
182
        try:
 
183
            sock.connect((host, port))
 
184
        except socket.error, e:
 
185
            self._raise_connection_error(host, port=port, orig_error=e)
 
186
        return SFTPClient(LoopbackSFTP(sock))
 
187
 
 
188
register_ssh_vendor('loopback', LoopbackVendor())
 
189
 
 
190
 
 
191
class _ParamikoSSHConnection(object):
 
192
    def __init__(self, channel):
 
193
        self.channel = channel
 
194
 
 
195
    def get_filelike_channels(self):
 
196
        return self.channel.makefile('rb'), self.channel.makefile('wb')
 
197
 
 
198
    def close(self):
 
199
        return self.channel.close()
 
200
 
 
201
 
 
202
class ParamikoVendor(SSHVendor):
 
203
    """Vendor that uses paramiko."""
 
204
 
 
205
    def _connect(self, username, password, host, port):
 
206
        global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
207
        
 
208
        load_host_keys()
 
209
 
 
210
        try:
 
211
            t = paramiko.Transport((host, port or 22))
 
212
            t.set_log_channel('bzr.paramiko')
 
213
            t.start_client()
 
214
        except (paramiko.SSHException, socket.error), e:
 
215
            self._raise_connection_error(host, port=port, orig_error=e)
 
216
            
 
217
        server_key = t.get_remote_server_key()
 
218
        server_key_hex = paramiko.util.hexify(server_key.get_fingerprint())
 
219
        keytype = server_key.get_name()
 
220
        if host in SYSTEM_HOSTKEYS and keytype in SYSTEM_HOSTKEYS[host]:
 
221
            our_server_key = SYSTEM_HOSTKEYS[host][keytype]
 
222
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
 
223
        elif host in BZR_HOSTKEYS and keytype in BZR_HOSTKEYS[host]:
 
224
            our_server_key = BZR_HOSTKEYS[host][keytype]
 
225
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
 
226
        else:
 
227
            warning('Adding %s host key for %s: %s' % (keytype, host, server_key_hex))
 
228
            if host not in BZR_HOSTKEYS:
 
229
                BZR_HOSTKEYS[host] = {}
 
230
            BZR_HOSTKEYS[host][keytype] = server_key
 
231
            our_server_key = server_key
 
232
            our_server_key_hex = paramiko.util.hexify(our_server_key.get_fingerprint())
 
233
            save_host_keys()
 
234
        if server_key != our_server_key:
 
235
            filename1 = os.path.expanduser('~/.ssh/known_hosts')
 
236
            filename2 = pathjoin(config_dir(), 'ssh_host_keys')
 
237
            raise TransportError('Host keys for %s do not match!  %s != %s' % \
 
238
                (host, our_server_key_hex, server_key_hex),
 
239
                ['Try editing %s or %s' % (filename1, filename2)])
 
240
 
 
241
        _paramiko_auth(username, password, host, t)
 
242
        return t
 
243
        
 
244
    def connect_sftp(self, username, password, host, port):
 
245
        t = self._connect(username, password, host, port)
 
246
        try:
 
247
            return t.open_sftp_client()
 
248
        except paramiko.SSHException, e:
 
249
            self._raise_connection_error(host, port=port, orig_error=e,
 
250
                                         msg='Unable to start sftp client')
 
251
 
 
252
    def connect_ssh(self, username, password, host, port, command):
 
253
        t = self._connect(username, password, host, port)
 
254
        try:
 
255
            channel = t.open_session()
 
256
            cmdline = ' '.join(command)
 
257
            channel.exec_command(cmdline)
 
258
            return _ParamikoSSHConnection(channel)
 
259
        except paramiko.SSHException, e:
 
260
            self._raise_connection_error(host, port=port, orig_error=e,
 
261
                                         msg='Unable to invoke remote bzr')
 
262
 
 
263
if paramiko is not None:
 
264
    register_ssh_vendor('paramiko', ParamikoVendor())
 
265
 
 
266
 
 
267
class SubprocessVendor(SSHVendor):
 
268
    """Abstract base class for vendors that use pipes to a subprocess."""
 
269
    
 
270
    def _connect(self, argv):
 
271
        proc = subprocess.Popen(argv,
 
272
                                stdin=subprocess.PIPE,
 
273
                                stdout=subprocess.PIPE,
 
274
                                **os_specific_subprocess_params())
 
275
        return SSHSubprocess(proc)
 
276
 
 
277
    def connect_sftp(self, username, password, host, port):
 
278
        try:
 
279
            argv = self._get_vendor_specific_argv(username, host, port,
 
280
                                                  subsystem='sftp')
 
281
            sock = self._connect(argv)
 
282
            return SFTPClient(sock)
 
283
        except (EOFError, paramiko.SSHException), e:
 
284
            self._raise_connection_error(host, port=port, orig_error=e)
 
285
        except (OSError, IOError), e:
 
286
            # If the machine is fast enough, ssh can actually exit
 
287
            # before we try and send it the sftp request, which
 
288
            # raises a Broken Pipe
 
289
            if e.errno not in (errno.EPIPE,):
 
290
                raise
 
291
            self._raise_connection_error(host, port=port, orig_error=e)
 
292
 
 
293
    def connect_ssh(self, username, password, host, port, command):
 
294
        try:
 
295
            argv = self._get_vendor_specific_argv(username, host, port,
 
296
                                                  command=command)
 
297
            return self._connect(argv)
 
298
        except (EOFError), e:
 
299
            self._raise_connection_error(host, port=port, orig_error=e)
 
300
        except (OSError, IOError), e:
 
301
            # If the machine is fast enough, ssh can actually exit
 
302
            # before we try and send it the sftp request, which
 
303
            # raises a Broken Pipe
 
304
            if e.errno not in (errno.EPIPE,):
 
305
                raise
 
306
            self._raise_connection_error(host, port=port, orig_error=e)
 
307
 
 
308
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
 
309
                                  command=None):
 
310
        """Returns the argument list to run the subprocess with.
 
311
        
 
312
        Exactly one of 'subsystem' and 'command' must be specified.
 
313
        """
 
314
        raise NotImplementedError(self._get_vendor_specific_argv)
 
315
 
 
316
register_ssh_vendor('none', ParamikoVendor())
 
317
 
 
318
 
 
319
class OpenSSHSubprocessVendor(SubprocessVendor):
 
320
    """SSH vendor that uses the 'ssh' executable from OpenSSH."""
 
321
    
 
322
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
 
323
                                  command=None):
 
324
        assert subsystem is not None or command is not None, (
 
325
            'Must specify a command or subsystem')
 
326
        if subsystem is not None:
 
327
            assert command is None, (
 
328
                'subsystem and command are mutually exclusive')
 
329
        args = ['ssh',
 
330
                '-oForwardX11=no', '-oForwardAgent=no',
 
331
                '-oClearAllForwardings=yes', '-oProtocol=2',
 
332
                '-oNoHostAuthenticationForLocalhost=yes']
 
333
        if port is not None:
 
334
            args.extend(['-p', str(port)])
 
335
        if username is not None:
 
336
            args.extend(['-l', username])
 
337
        if subsystem is not None:
 
338
            args.extend(['-s', host, subsystem])
 
339
        else:
 
340
            args.extend([host] + command)
 
341
        return args
 
342
 
 
343
register_ssh_vendor('openssh', OpenSSHSubprocessVendor())
 
344
 
 
345
 
 
346
class SSHCorpSubprocessVendor(SubprocessVendor):
 
347
    """SSH vendor that uses the 'ssh' executable from SSH Corporation."""
 
348
 
 
349
    def _get_vendor_specific_argv(self, username, host, port, subsystem=None,
 
350
                                  command=None):
 
351
        assert subsystem is not None or command is not None, (
 
352
            'Must specify a command or subsystem')
 
353
        if subsystem is not None:
 
354
            assert command is None, (
 
355
                'subsystem and command are mutually exclusive')
 
356
        args = ['ssh', '-x']
 
357
        if port is not None:
 
358
            args.extend(['-p', str(port)])
 
359
        if username is not None:
 
360
            args.extend(['-l', username])
 
361
        if subsystem is not None:
 
362
            args.extend(['-s', subsystem, host])
 
363
        else:
 
364
            args.extend([host] + command)
 
365
        return args
 
366
    
 
367
register_ssh_vendor('ssh', SSHCorpSubprocessVendor())
 
368
 
 
369
 
 
370
def _paramiko_auth(username, password, host, paramiko_transport):
 
371
    # paramiko requires a username, but it might be none if nothing was supplied
 
372
    # use the local username, just in case.
 
373
    # We don't override username, because if we aren't using paramiko,
 
374
    # the username might be specified in ~/.ssh/config and we don't want to
 
375
    # force it to something else
 
376
    # Also, it would mess up the self.relpath() functionality
 
377
    username = username or getpass.getuser()
 
378
 
 
379
    if _use_ssh_agent:
 
380
        agent = paramiko.Agent()
 
381
        for key in agent.get_keys():
 
382
            mutter('Trying SSH agent key %s' % paramiko.util.hexify(key.get_fingerprint()))
 
383
            try:
 
384
                paramiko_transport.auth_publickey(username, key)
 
385
                return
 
386
            except paramiko.SSHException, e:
 
387
                pass
 
388
    
 
389
    # okay, try finding id_rsa or id_dss?  (posix only)
 
390
    if _try_pkey_auth(paramiko_transport, paramiko.RSAKey, username, 'id_rsa'):
 
391
        return
 
392
    if _try_pkey_auth(paramiko_transport, paramiko.DSSKey, username, 'id_dsa'):
 
393
        return
 
394
 
 
395
    if password:
 
396
        try:
 
397
            paramiko_transport.auth_password(username, password)
 
398
            return
 
399
        except paramiko.SSHException, e:
 
400
            pass
 
401
 
 
402
    # give up and ask for a password
 
403
    password = bzrlib.ui.ui_factory.get_password(
 
404
            prompt='SSH %(user)s@%(host)s password',
 
405
            user=username, host=host)
 
406
    try:
 
407
        paramiko_transport.auth_password(username, password)
 
408
    except paramiko.SSHException, e:
 
409
        raise ConnectionError('Unable to authenticate to SSH host as %s@%s' %
 
410
                              (username, host), e)
 
411
 
 
412
 
 
413
def _try_pkey_auth(paramiko_transport, pkey_class, username, filename):
 
414
    filename = os.path.expanduser('~/.ssh/' + filename)
 
415
    try:
 
416
        key = pkey_class.from_private_key_file(filename)
 
417
        paramiko_transport.auth_publickey(username, key)
 
418
        return True
 
419
    except paramiko.PasswordRequiredException:
 
420
        password = bzrlib.ui.ui_factory.get_password(
 
421
                prompt='SSH %(filename)s password',
 
422
                filename=filename)
 
423
        try:
 
424
            key = pkey_class.from_private_key_file(filename, password)
 
425
            paramiko_transport.auth_publickey(username, key)
 
426
            return True
 
427
        except paramiko.SSHException:
 
428
            mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
 
429
    except paramiko.SSHException:
 
430
        mutter('SSH authentication via %s key failed.' % (os.path.basename(filename),))
 
431
    except IOError:
 
432
        pass
 
433
    return False
 
434
 
 
435
 
 
436
def load_host_keys():
 
437
    """
 
438
    Load system host keys (probably doesn't work on windows) and any
 
439
    "discovered" keys from previous sessions.
 
440
    """
 
441
    global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
442
    try:
 
443
        SYSTEM_HOSTKEYS = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
 
444
    except Exception, e:
 
445
        mutter('failed to load system host keys: ' + str(e))
 
446
    bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
 
447
    try:
 
448
        BZR_HOSTKEYS = paramiko.util.load_host_keys(bzr_hostkey_path)
 
449
    except Exception, e:
 
450
        mutter('failed to load bzr host keys: ' + str(e))
 
451
        save_host_keys()
 
452
 
 
453
 
 
454
def save_host_keys():
 
455
    """
 
456
    Save "discovered" host keys in $(config)/ssh_host_keys/.
 
457
    """
 
458
    global SYSTEM_HOSTKEYS, BZR_HOSTKEYS
 
459
    bzr_hostkey_path = pathjoin(config_dir(), 'ssh_host_keys')
 
460
    ensure_config_dir_exists()
 
461
 
 
462
    try:
 
463
        f = open(bzr_hostkey_path, 'w')
 
464
        f.write('# SSH host keys collected by bzr\n')
 
465
        for hostname, keys in BZR_HOSTKEYS.iteritems():
 
466
            for keytype, key in keys.iteritems():
 
467
                f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
 
468
        f.close()
 
469
    except IOError, e:
 
470
        mutter('failed to save bzr host keys: ' + str(e))
 
471
 
 
472
 
 
473
def os_specific_subprocess_params():
 
474
    """Get O/S specific subprocess parameters."""
 
475
    if sys.platform == 'win32':
 
476
        # setting the process group and closing fds is not supported on 
 
477
        # win32
 
478
        return {}
 
479
    else:
 
480
        # We close fds other than the pipes as the child process does not need 
 
481
        # them to be open.
 
482
        #
 
483
        # We also set the child process to ignore SIGINT.  Normally the signal
 
484
        # would be sent to every process in the foreground process group, but
 
485
        # this causes it to be seen only by bzr and not by ssh.  Python will
 
486
        # generate a KeyboardInterrupt in bzr, and we will then have a chance
 
487
        # to release locks or do other cleanup over ssh before the connection
 
488
        # goes away.  
 
489
        # <https://launchpad.net/products/bzr/+bug/5987>
 
490
        #
 
491
        # Running it in a separate process group is not good because then it
 
492
        # can't get non-echoed input of a password or passphrase.
 
493
        # <https://launchpad.net/products/bzr/+bug/40508>
 
494
        return {'preexec_fn': _ignore_sigint,
 
495
                'close_fds': True,
 
496
                }
 
497
 
 
498
 
 
499
class SSHSubprocess(object):
 
500
    """A socket-like object that talks to an ssh subprocess via pipes."""
 
501
 
 
502
    def __init__(self, proc):
 
503
        self.proc = proc
 
504
 
 
505
    def send(self, data):
 
506
        return os.write(self.proc.stdin.fileno(), data)
 
507
 
 
508
    def recv_ready(self):
 
509
        # TODO: jam 20051215 this function is necessary to support the
 
510
        # pipelined() function. In reality, it probably should use
 
511
        # poll() or select() to actually return if there is data
 
512
        # available, otherwise we probably don't get any benefit
 
513
        return True
 
514
 
 
515
    def recv(self, count):
 
516
        return os.read(self.proc.stdout.fileno(), count)
 
517
 
 
518
    def close(self):
 
519
        self.proc.stdin.close()
 
520
        self.proc.stdout.close()
 
521
        self.proc.wait()
 
522
 
 
523
    def get_filelike_channels(self):
 
524
        return (self.proc.stdout, self.proc.stdin)
 
525