Example #1
0
    def __init__(self, sock):
        """
        Create an SFTP client from an existing `.Channel`.  The channel
        should already have requested the ``"sftp"`` subsystem.

        An alternate way to create an SFTP client context is by using
        `from_transport`.

        :param .Channel sock: an open `.Channel` using the ``"sftp"`` subsystem

        :raises SSHException: if there's an exception while negotiating
            sftp
        """
        BaseSFTP.__init__(self)
        self.sock = sock
        self.ultra_debug = False
        self.request_number = 1
        # lock for request_number
        self._lock = threading.Lock()
        self._cwd = None
        # request # -> SFTPFile
        self._expecting = weakref.WeakValueDictionary()
        if type(sock) is Channel:
            # override default logger
            transport = self.sock.get_transport()
            self.logger = util.get_logger(transport.get_log_channel() + '.sftp')
            self.ultra_debug = transport.get_hexdump()
        try:
            server_version = self._send_version()
        except EOFError:
            raise SSHException('EOF during negotiation')
        self._log(INFO, 'Opened sftp connection (server version %d)' % server_version)
Example #2
0
    def __init__(self, channel, name, server, sftp_si=SFTPServerInterface, *largs, **kwargs):
        """
        The constructor for SFTPServer is meant to be called from within the
        `.Transport` as a subsystem handler.  ``server`` and any additional
        parameters or keyword parameters are passed from the original call to
        `.Transport.set_subsystem_handler`.

        :param .Channel channel: channel passed from the `.Transport`.
        :param str name: name of the requested subsystem.
        :param .ServerInterface server:
            the server object associated with this channel and subsystem
        :param class sftp_si:
            a subclass of `.SFTPServerInterface` to use for handling individual
            requests.
        """
        BaseSFTP.__init__(self)
        SubsystemHandler.__init__(self, channel, name, server)
        transport = channel.get_transport()
        self.logger = util.get_logger(transport.get_log_channel() + '.sftp')
        self.ultra_debug = transport.get_hexdump()
        self.next_handle = 1
        # map of handle-string to SFTPHandle for files & folders:
        self.file_table = {}
        self.folder_table = {}
        self.server = sftp_si(server, *largs, **kwargs)
Example #3
0
    def __init__(self, sock):
        """
        Create an SFTP client from an existing `.Channel`.  The channel
        should already have requested the ``"sftp"`` subsystem.

        An alternate way to create an SFTP client context is by using
        `from_transport`.

        :param .Channel sock: an open `.Channel` using the ``"sftp"`` subsystem

        :raises SSHException: if there's an exception while negotiating
            sftp
        """
        BaseSFTP.__init__(self)
        self.sock = sock
        self.ultra_debug = False
        self.request_number = 1
        # lock for request_number
        self._lock = threading.Lock()
        self._cwd = None
        # request # -> SFTPFile
        self._expecting = weakref.WeakValueDictionary()
        if type(sock) is Channel:
            # override default logger
            transport = self.sock.get_transport()
            self.logger = util.get_logger(transport.get_log_channel() +
                                          '.sftp')
            self.ultra_debug = transport.get_hexdump()
        try:
            server_version = self._send_version()
        except EOFError:
            raise SSHException('EOF during negotiation')
        self._log(
            INFO,
            'Opened sftp connection (server version %d)' % server_version)
Example #4
0
    def test_1_write(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger('paramiko.transport'))
        p.set_hexdump(True)
        encryptor = Cipher(algorithms.AES(zero_byte * 16),
                           modes.CBC(x55 * 16),
                           backend=default_backend()).encryptor()
        p.set_outbound_cipher(encryptor, 16, sha1, 12, x1f * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(byte_chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        p.send_message(m)
        data = rsock.recv(100)
        # 32 + 12 bytes of MAC = 44
        self.assertEqual(44, len(data))
        self.assertEqual(
            b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0',
            data[:16])
Example #5
0
    def test_1_write(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)

        p = Packetizer(wsock)
        p.set_log(util.get_logger("paramiko.transport"))
        p.set_hexdump(True)
        cipher = AES.new(b"\x00" * 16, AES.MODE_CBC, b"\x55" * 16)
        p.set_outbound_cipher(cipher, 16, SHA, 12, b"\x1f" * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(chr(100).encode())
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)

        p.send_message(m)

        data = rsock.recv(100)
        # 32 + 12 bytes of MAC = 44
        self.assertEquals(44, len(data))
        self.assertEquals(b"\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0", data[:16])
Example #6
0
    def test_1_write(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger("paramiko.transport"))
        p.set_hexdump(True)
        encryptor = Cipher(
            algorithms.AES(zero_byte * 16),
            modes.CBC(x55 * 16),
            backend=default_backend(),
        ).encryptor()
        p.set_outbound_cipher(encryptor, 16, sha1, 12, x1f * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(byte_chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        p.send_message(m)
        data = rsock.recv(100)
        # 32 + 12 bytes of MAC = 44
        self.assertEqual(44, len(data))
        self.assertEqual(
            b"\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0",
            data[:16],
        )
Example #7
0
    def __init__(self,
                 channel,
                 name,
                 server,
                 sftp_si=SFTPServerInterface,
                 *largs,
                 **kwargs):
        """
        The constructor for SFTPServer is meant to be called from within the
        `.Transport` as a subsystem handler.  ``server`` and any additional
        parameters or keyword parameters are passed from the original call to
        `.Transport.set_subsystem_handler`.

        :param .Channel channel: channel passed from the `.Transport`.
        :param str name: name of the requested subsystem.
        :param .ServerInterface server:
            the server object associated with this channel and subsystem
        :param class sftp_si:
            a subclass of `.SFTPServerInterface` to use for handling individual
            requests.
        """
        BaseSFTP.__init__(self)
        SubsystemHandler.__init__(self, channel, name, server)
        transport = channel.get_transport()
        self.logger = util.get_logger(transport.get_log_channel() + '.sftp')
        self.ultra_debug = transport.get_hexdump()
        self.next_handle = 1
        # map of handle-string to SFTPHandle for files & folders:
        self.file_table = {}
        self.folder_table = {}
        self.server = sftp_si(server, *largs, **kwargs)
Example #8
0
    def test_3_closed(self):
        if sys.platform.startswith("win"):  # no SIGALRM on windows
            return
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger("paramiko.transport"))
        p.set_hexdump(True)
        encryptor = Cipher(
            algorithms.AES(zero_byte * 16),
            modes.CBC(x55 * 16),
            backend=default_backend(),
        ).encryptor()
        p.set_outbound_cipher(encryptor, 16, sha1, 12, x1f * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(byte_chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        wsock.send = lambda x: 0
        from functools import wraps
        import errno
        import os
        import signal

        class TimeoutError(Exception):
            def __init__(self, error_message):
                if hasattr(errno, "ETIME"):
                    self.message = os.sterror(errno.ETIME)
                else:
                    self.messaage = error_message

        def timeout(seconds=1, error_message="Timer expired"):
            def decorator(func):
                def _handle_timeout(signum, frame):
                    raise TimeoutError(error_message)

                def wrapper(*args, **kwargs):
                    signal.signal(signal.SIGALRM, _handle_timeout)
                    signal.alarm(seconds)
                    try:
                        result = func(*args, **kwargs)
                    finally:
                        signal.alarm(0)
                    return result

                return wraps(func)(wrapper)

            return decorator

        send = timeout()(p.send_message)
        self.assertRaises(EOFError, send, m)
Example #9
0
    def test_3_closed(self):
        if sys.platform.startswith("win"):  # no SIGALRM on windows
            return
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger("paramiko.transport"))
        p.set_hexdump(True)
        encryptor = Cipher(
            algorithms.AES(zero_byte * 16),
            modes.CBC(x55 * 16),
            backend=default_backend(),
        ).encryptor()
        p.set_outbound_cipher(encryptor, 16, sha1, 12, x1f * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(byte_chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        wsock.send = lambda x: 0
        from functools import wraps
        import errno
        import os
        import signal

        class TimeoutError(Exception):
            def __init__(self, error_message):
                if hasattr(errno, "ETIME"):
                    self.message = os.sterror(errno.ETIME)
                else:
                    self.messaage = error_message

        def timeout(seconds=1, error_message="Timer expired"):
            def decorator(func):
                def _handle_timeout(signum, frame):
                    raise TimeoutError(error_message)

                def wrapper(*args, **kwargs):
                    signal.signal(signal.SIGALRM, _handle_timeout)
                    signal.alarm(seconds)
                    try:
                        result = func(*args, **kwargs)
                    finally:
                        signal.alarm(0)
                    return result

                return wraps(func)(wrapper)

            return decorator

        send = timeout()(p.send_message)
        self.assertRaises(EOFError, send, m)
Example #10
0
    def set_name(self, name):
        """
        Set a name for this channel.  Currently it's only used to set the name
        of the log level used for debugging.  The name can be fetched with the
        L{get_name} method.

        @param name: new channel name.
        @type name: str
        """
        self.name = name
        self.logger = util.get_logger(self.transport.get_log_channel() + '.' + self.name)
Example #11
0
    def set_name(self, name):
        """
        Set a name for this channel.  Currently it's only used to set the name
        of the log level used for debugging.  The name can be fetched with the
        L{get_name} method.

        @param name: new channel name.
        @type name: str
        """
        self.name = name
        self.logger = util.get_logger(self.transport.get_log_channel() + '.' +
                                      self.name)
Example #12
0
 def test_2_read(self):
     rsock = LoopSocket()
     wsock = LoopSocket()
     rsock.link(wsock)
     p = Packetizer(rsock)
     p.set_log(util.get_logger('paramiko.transport'))
     p.set_hexdump(True)
     cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16)
     p.set_inbound_cipher(cipher, 16, sha1, 12, x1f * 20)
     wsock.send(b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0\x90\xd2\x16\x56\x0d\x71\x73\x61\x38\x7c\x4c\x3d\xfb\x97\x7d\xe2\x6e\x03\xb1\xa0\xc2\x1c\xd6\x41\x41\x4c\xb4\x59')
     cmd, m = p.read_message()
     self.assertEqual(100, cmd)
     self.assertEqual(100, m.get_int())
     self.assertEqual(1, m.get_int())
     self.assertEqual(900, m.get_int())
Example #13
0
 def test_2_read(self):
     rsock = LoopSocket()
     wsock = LoopSocket()
     rsock.link(wsock)
     p = Packetizer(rsock)
     p.set_log(util.get_logger('paramiko.transport'))
     p.set_hexdump(True)
     cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16)
     p.set_inbound_cipher(cipher, 16, SHA, 12, x1f * 20)
     wsock.send(
         b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0\x90\xd2\x16\x56\x0d\x71\x73\x61\x38\x7c\x4c\x3d\xfb\x97\x7d\xe2\x6e\x03\xb1\xa0\xc2\x1c\xd6\x41\x41\x4c\xb4\x59'
     )
     cmd, m = p.read_message()
     self.assertEqual(100, cmd)
     self.assertEqual(100, m.get_int())
     self.assertEqual(1, m.get_int())
     self.assertEqual(900, m.get_int())
 def test_2_read (self):
     rsock = LoopSocket()
     wsock = LoopSocket()
     rsock.link(wsock)
     p = Packetizer(rsock)
     p.set_log(util.get_logger('paramiko.transport'))
     p.set_hexdump(True)
     cipher = AES.new('\x00' * 16, AES.MODE_CBC, '\x55' * 16)
     p.set_inbound_cipher(cipher, 16, SHA, 12, '\x1f' * 20)
     
     wsock.send('C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \
                '\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y')
     cmd, m = p.read_message()
     self.assertEquals(100, cmd)
     self.assertEquals(100, m.get_int())
     self.assertEquals(1, m.get_int())
     self.assertEquals(900, m.get_int())
Example #15
0
    def test_3_closed(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger('paramiko.transport'))
        p.set_hexdump(True)
        cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16)
        p.set_outbound_cipher(cipher, 16, sha1, 12, x1f * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(byte_chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        wsock.send = lambda x: 0
        from functools import wraps
        import errno
        import os
        import signal

        class TimeoutError(Exception):
            pass

        def timeout(seconds=1, error_message=os.strerror(errno.ETIME)):
            def decorator(func):
                def _handle_timeout(signum, frame):
                    raise TimeoutError(error_message)

                def wrapper(*args, **kwargs):
                    signal.signal(signal.SIGALRM, _handle_timeout)
                    signal.alarm(seconds)
                    try:
                        result = func(*args, **kwargs)
                    finally:
                        signal.alarm(0)
                    return result

                return wraps(func)(wrapper)

            return decorator

        send = timeout()(p.send_message)
        self.assertRaises(EOFError, send, m)
Example #16
0
    def test_2_read(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(rsock)
        p.set_log(util.get_logger('paramiko.transport'))
        p.set_hexdump(True)
        cipher = AES.new('\x00' * 16, AES.MODE_CBC, '\x55' * 16)
        p.set_inbound_cipher(cipher, 16, SHA, 12, '\x1f' * 20)

        wsock.send('C\x91\x97\xbd[P\xac%\x87\xc2\xc4k\xc7\xe98\xc0' + \
                   '\x90\xd2\x16V\rqsa8|L=\xfb\x97}\xe2n\x03\xb1\xa0\xc2\x1c\xd6AAL\xb4Y')
        cmd, m = p.read_message()
        self.assertEquals(100, cmd)
        self.assertEquals(100, m.get_int())
        self.assertEquals(1, m.get_int())
        self.assertEquals(900, m.get_int())
Example #17
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            elif keytype == "ssh-xmss":
                key = XMSS(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
Example #18
0
 def test_2_read(self):
     rsock = LoopSocket()
     wsock = LoopSocket()
     rsock.link(wsock)
     p = Packetizer(rsock)
     p.set_log(util.get_logger("paramiko.transport"))
     p.set_hexdump(True)
     decryptor = Cipher(algorithms.AES(zero_byte * 16), modes.CBC(x55 * 16), backend=default_backend()).decryptor()
     p.set_inbound_cipher(decryptor, 16, sha1, 12, x1f * 20)
     wsock.send(
         b"\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0\x90\xd2\x16\x56\x0d\x71\x73\x61\x38\x7c\x4c\x3d\xfb\x97\x7d\xe2\x6e\x03\xb1\xa0\xc2\x1c\xd6\x41\x41\x4c\xb4\x59"
     )
     cmd, m = p.read_message()
     self.assertEqual(100, cmd)
     self.assertEqual(100, m.get_int())
     self.assertEqual(1, m.get_int())
     self.assertEqual(900, m.get_int())
Example #19
0
    def __init__(self, chanid):
        """
        Create a new channel.  The channel is not associated with any
        particular session or `.Transport` until the Transport attaches it.
        Normally you would only call this method from the constructor of a
        subclass of `.Channel`.

        :param int chanid:
            the ID of this channel, as passed by an existing `.Transport`.
        """
        #: Channel ID
        self.chanid = chanid
        #: Remote channel ID
        self.remote_chanid = 0
        #: `.Transport` managing this channel
        self.transport = None
        #: Whether the connection is presently active
        self.active = False
        self.eof_received = 0
        self.eof_sent = 0
        self.in_buffer = BufferedPipe()
        self.in_stderr_buffer = BufferedPipe()
        self.timeout = None
        #: Whether the connection has been closed
        self.closed = False
        # Whether a close message has been sent; guarded with
        # transport.clear_to_send_lock
        self._close_sent = False
        self.ultra_debug = False
        self.lock = threading.Lock()
        self.out_buffer_cv = threading.Condition(self.lock)
        self.in_window_size = 0
        self.out_window_size = 0
        self.in_max_packet_size = 0
        self.out_max_packet_size = 0
        self.in_window_threshold = 0
        self.in_window_sofar = 0
        self.status_event = threading.Event()
        self._name = str(chanid)
        self.logger = util.get_logger('paramiko.transport')
        self._pipe = None
        self.event = threading.Event()
        self.event_ready = False
        self.combine_stderr = False
        self.exit_status = -1
        self.origin_addr = None
Example #20
0
    def test_3_closed(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger('paramiko.transport'))
        p.set_hexdump(True)
        cipher = AES.new(zero_byte * 16, AES.MODE_CBC, x55 * 16)
        p.set_outbound_cipher(cipher, 16, sha1, 12, x1f * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(byte_chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        wsock.send = lambda x: 0
        from functools import wraps
        import errno
        import os
        import signal

        class TimeoutError(Exception):
            pass

        def timeout(seconds=1, error_message=os.strerror(errno.ETIME)):
            def decorator(func):
                def _handle_timeout(signum, frame):
                    raise TimeoutError(error_message)

                def wrapper(*args, **kwargs):
                    signal.signal(signal.SIGALRM, _handle_timeout)
                    signal.alarm(seconds)
                    try:
                        result = func(*args, **kwargs)
                    finally:
                        signal.alarm(0)
                    return result

                return wraps(func)(wrapper)

            return decorator
        send = timeout()(p.send_message)
        self.assertRaises(EOFError, send, m)
Example #21
0
 def test_4_read_exception(self):
     """
     assert that the Packetizer raises an SSHException when receiving mangled input
     """
     rsock = LoopSocket()
     wsock = LoopSocket()
     rsock.link(wsock)
     p = Packetizer(rsock)
     p.set_log(util.get_logger('paramiko.transport'))
     p.set_hexdump(True)
     decryptor = Cipher(algorithms.AES(zero_byte * 16),
                        modes.CBC(x55 * 16),
                        backend=default_backend()).decryptor()
     p.set_inbound_cipher(decryptor, 16, sha1, 12, x1f * 20)
     wsock.send(
         b'\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43\x43'
     )
     self.assertRaises(SSHException, p.read_message)
Example #22
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the OpenSSH known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        :param str line: a line from an OpenSSH known_hosts file
        """
        log = get_logger("paramiko.hostkeys")
        fields = line.split(" ")
        if len(fields) < 3:
            # Bad number of fields
            msg = "Not enough fields found in known_hosts in line {} ({!r})"
            log.info(msg.format(lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(",")

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == "ssh-rsa":
                key = RSAKey(data=decodebytes(key))
            elif keytype == "ssh-dss":
                key = DSSKey(data=decodebytes(key))
            elif keytype in ECDSAKey.supported_key_format_identifiers():
                key = ECDSAKey(data=decodebytes(key), validate_point=False)
            elif keytype == "ssh-ed25519":
                key = Ed25519Key(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type {}".format(keytype))
                return None

        except binascii.Error as e:
            raise InvalidHostKey(line, e)

        return cls(names, key)
Example #23
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the openssh known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        @param line: a line from an OpenSSH known_hosts file
        @type line: str
        """
        log = get_logger('paramiko.hostkeys')
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            log.info("Not enough fields found in known_hosts in line %s (%r)" %
                     (lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == 'ssh-rsa':
                key = RSAKey(data=decodebytes(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=decodebytes(key))
            elif keytype == 'ecdsa-sha2-nistp256':
                key = ECDSAKey(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type %s" % (keytype, ))
                return None

        except binascii.Error:
            raise InvalidHostKey(line, sys.exc_info()[1])

        return cls(names, key)
Example #24
0
    def __init__(self, chanid):
        """
        Create a new channel.  The channel is not associated with any
        particular session or `.Transport` until the Transport attaches it.
        Normally you would only call this method from the constructor of a
        subclass of `.Channel`.

        :param int chanid:
            the ID of this channel, as passed by an existing `.Transport`.
        """
        #: Channel ID
        self.chanid = chanid
        #: Remote channel ID
        self.remote_chanid = 0
        #: `.Transport` managing this channel
        self.transport = None
        #: Whether the connection is presently active
        self.active = False
        self.eof_received = 0
        self.eof_sent = 0
        self.in_buffer = BufferedPipe()
        self.in_stderr_buffer = BufferedPipe()
        self.timeout = None
        #: Whether the connection has been closed
        self.closed = False
        self.ultra_debug = False
        self.lock = threading.Lock()
        self.out_buffer_cv = threading.Condition(self.lock)
        self.in_window_size = 0
        self.out_window_size = 0
        self.in_max_packet_size = 0
        self.out_max_packet_size = 0
        self.in_window_threshold = 0
        self.in_window_sofar = 0
        self.status_event = threading.Event()
        self._name = str(chanid)
        self.logger = util.get_logger('paramiko.transport')
        self._pipe = None
        self.event = threading.Event()
        self.event_ready = False
        self.combine_stderr = False
        self.exit_status = -1
        self.origin_addr = None
Example #25
0
    def from_line(cls, line, lineno=None):
        """
        Parses the given line of text to find the names for the host,
        the type of key, and the key data. The line is expected to be in the
        format used by the openssh known_hosts file.

        Lines are expected to not have leading or trailing whitespace.
        We don't bother to check for comments or empty lines.  All of
        that should be taken care of before sending the line to us.

        @param line: a line from an OpenSSH known_hosts file
        @type line: str
        """
        log = get_logger('paramiko.hostkeys')
        fields = line.split(' ')
        if len(fields) < 3:
            # Bad number of fields
            log.info("Not enough fields found in known_hosts in line %s (%r)" %
                     (lineno, line))
            return None
        fields = fields[:3]

        names, keytype, key = fields
        names = names.split(',')

        # Decide what kind of key we're looking at and create an object
        # to hold it accordingly.
        try:
            key = b(key)
            if keytype == 'ssh-rsa':
                key = RSAKey(data=decodebytes(key))
            elif keytype == 'ssh-dss':
                key = DSSKey(data=decodebytes(key))
            elif keytype == 'ecdsa-sha2-nistp256':
                key = ECDSAKey(data=decodebytes(key))
            else:
                log.info("Unable to handle key of type %s" % (keytype,))
                return None

        except binascii.Error:
            raise InvalidHostKey(line, sys.exc_info()[1])

        return cls(names, key)
Example #26
0
 def test_2_read(self):
     rsock = LoopSocket()
     wsock = LoopSocket()
     rsock.link(wsock)
     p = Packetizer(rsock)
     p.set_log(util.get_logger('paramiko.transport'))
     p.set_hexdump(True)
     decryptor = Cipher(algorithms.AES(zero_byte * 16),
                        modes.CBC(x55 * 16),
                        backend=default_backend()).decryptor()
     p.set_inbound_cipher(decryptor, 16, sha1, 12, x1f * 20)
     wsock.send(
         b'\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0\x90\xd2\x16\x56\x0d\x71\x73\x61\x38\x7c\x4c\x3d\xfb\x97\x7d\xe2\x6e\x03\xb1\xa0\xc2\x1c\xd6\x41\x41\x4c\xb4\x59'
     )
     cmd, m = p.read_message()
     self.assertEqual(100, cmd)
     self.assertEqual(100, m.get_int())
     self.assertEqual(1, m.get_int())
     self.assertEqual(900, m.get_int())
Example #27
0
    def __init__(self, chanid):
        """
        Create a new channel.  The channel is not associated with any
        particular session or L{Transport} until the Transport attaches it.
        Normally you would only call this method from the constructor of a
        subclass of L{Channel}.

        @param chanid: the ID of this channel, as passed by an existing
            L{Transport}.
        @type chanid: int
        """
        self.chanid = chanid
        self.remote_chanid = 0
        self.transport = None
        self.active = False
        self.eof_received = 0
        self.eof_sent = 0
        self.in_buffer = BufferedPipe()
        self.in_stderr_buffer = BufferedPipe()
        self.timeout = None
        self.closed = False
        self.ultra_debug = False
        self.lock = threading.Lock()
        self.out_buffer_cv = threading.Condition(self.lock)
        self.in_window_size = 0
        self.out_window_size = 0
        self.in_max_packet_size = 0
        self.out_max_packet_size = 0
        self.in_window_threshold = 0
        self.in_window_sofar = 0
        self.status_event = threading.Event()
        self._name = str(chanid)
        self.logger = util.get_logger("paramiko.transport")
        self._pipe = None
        self.event = threading.Event()
        self.event_ready = False
        self.combine_stderr = False
        self.exit_status = -1
        self.origin_addr = None
Example #28
0
    def __init__(self, chanid):
        """
        Create a new channel.  The channel is not associated with any
        particular session or L{Transport} until the Transport attaches it.
        Normally you would only call this method from the constructor of a
        subclass of L{Channel}.

        @param chanid: the ID of this channel, as passed by an existing
            L{Transport}.
        @type chanid: int
        """
        self.chanid = chanid
        self.remote_chanid = 0
        self.transport = None
        self.active = False
        self.eof_received = 0
        self.eof_sent = 0
        self.in_buffer = BufferedPipe()
        self.in_stderr_buffer = BufferedPipe()
        self.timeout = None
        self.closed = False
        self.ultra_debug = False
        self.lock = threading.Lock()
        self.out_buffer_cv = threading.Condition(self.lock)
        self.in_window_size = 0
        self.out_window_size = 0
        self.in_max_packet_size = 0
        self.out_max_packet_size = 0
        self.in_window_threshold = 0
        self.in_window_sofar = 0
        self.status_event = threading.Event()
        self._name = str(chanid)
        self.logger = util.get_logger('paramiko.transport')
        self._pipe = None
        self.event = threading.Event()
        self.event_ready = False
        self.combine_stderr = False
        self.exit_status = -1
        self.origin_addr = None
Example #29
0
    def test_1_write(self):
        rsock = LoopSocket()
        wsock = LoopSocket()
        rsock.link(wsock)
        p = Packetizer(wsock)
        p.set_log(util.get_logger('paramiko.transport'))
        p.set_hexdump(True)
        cipher = AES.new('\x00' * 16, AES.MODE_CBC, '\x55' * 16)
        p.set_outbound_cipher(cipher, 16, SHA, 12, '\x1f' * 20)

        # message has to be at least 16 bytes long, so we'll have at least one
        # block of data encrypted that contains zero random padding bytes
        m = Message()
        m.add_byte(chr(100))
        m.add_int(100)
        m.add_int(1)
        m.add_int(900)
        p.send_message(m)
        data = rsock.recv(100)
        # 32 + 12 bytes of MAC = 44
        self.assertEquals(44, len(data))
        self.assertEquals(
            '\x43\x91\x97\xbd\x5b\x50\xac\x25\x87\xc2\xc4\x6b\xc7\xe9\x38\xc0',
            data[:16])
Example #30
0
 def _set_transport(self, transport):
     self.transport = weakref.proxy(transport)
     self.logger = util.get_logger(self.transport.get_log_channel())
Example #31
0
 def _set_transport(self, transport):
     self.transport = weakref.proxy(transport)
     self.logger = util.get_logger(self.transport.get_log_channel())
Example #32
0
 def _set_transport(self, transport):
     self.transport = transport
     self.logger = util.get_logger(self.transport.get_log_channel())
Example #33
0
 def _set_transport(self, transport):
     self.transport = transport
     self.logger = util.get_logger(self.transport.get_log_channel())
Example #34
0
 def __init__(self):
     self.pp = ProxyProtocolHeader
     self.header_length = 16
     self.logger = get_logger("paramiko.proxy_protocol")
Example #35
0
 def __init__(self):
     self.logger = util.get_logger('paramiko.sftp')
     self.sock = None
     self.ultra_debug = False
Example #36
0
 def __init__(self):
     self.logger = util.get_logger('paramiko.sftp')
     self.sock = None
     self.ultra_debug = False