Exemple #1
0
    def exec_command(self, command):
        """
        Execute a command on the server.  If the server allows it, the channel
        will then be directly connected to the stdin, stdout, and stderr of
        the command being executed.
        
        When the command finishes executing, the channel will be closed and
        can't be reused.  You must open a new channel if you wish to execute
        another command.

        @param command: a shell command to execute.
        @type command: str

        @raise SSHException: if the request was rejected or the channel was
            closed
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('exec')
        m.add_boolean(True)
        m.add_string(command)
        self.event.clear()
        self.transport._send_user_message(m)
        self._wait_for_event()
Exemple #2
0
 def _parse_service_accept(self, m):
     service = m.get_string()
     if service == 'ssh-userauth':
         self.transport._log(DEBUG, 'userauth is OK')
         m = Message()
         m.add_byte(chr(MSG_USERAUTH_REQUEST))
         m.add_string(self.username)
         m.add_string('ssh-connection')
         m.add_string(self.auth_method)
         if self.auth_method == 'password':
             m.add_boolean(False)
             password = self.password
             if isinstance(password, unicode):
                 password = password.encode('UTF-8')
             m.add_string(password)
         elif self.auth_method == 'publickey':
             m.add_boolean(True)
             m.add_string(self.private_key.get_name())
             m.add_string(str(self.private_key))
             blob = self._get_session_blob(self.private_key, 'ssh-connection', self.username)
             sig = self.private_key.sign_ssh_data(self.transport.rng, blob)
             m.add_string(str(sig))
         elif self.auth_method == 'keyboard-interactive':
             m.add_string('')
             m.add_string(self.submethods)
         elif self.auth_method == 'none':
             pass
         else:
             raise SSHException('Unknown auth method "%s"' % self.auth_method)
         self.transport._send_message(m)
     else:
         self.transport._log(DEBUG, 'Service request "%s" accepted (?)' % service)
Exemple #3
0
    def test_1_encode(self):
        msg = Message()
        msg.add_int(23)
        msg.add_int(123789456)
        msg.add_string("q")
        msg.add_string("hello")
        msg.add_string("x" * 1000)
        self.assertEqual(msg.asbytes(), self.__a)

        msg = Message()
        msg.add_boolean(True)
        msg.add_boolean(False)
        msg.add_byte(byte_chr(0xf3))

        msg.add_bytes(zero_byte + byte_chr(0x3f))
        msg.add_list(["huey", "dewey", "louie"])
        self.assertEqual(msg.asbytes(), self.__b)

        msg = Message()
        msg.add_int64(5)
        msg.add_int64(0xf5e4d3c2b109)
        msg.add_mpint(17)
        msg.add_mpint(0xf5e4d3c2b109)
        msg.add_mpint(-0x65e4d3c2b109)
        self.assertEqual(msg.asbytes(), self.__c)
Exemple #4
0
 def _parse_kexdh_gex_init(self, m):
     self.e = m.get_mpint()
     if (self.e < 1) or (self.e > self.p - 1):
         raise SSHException('Client kex "e" is out of range')
     self._generate_x()
     self.f = pow(self.g, self.x, self.p)
     K = pow(self.e, self.x, self.p)
     key = str(self.transport.get_server_key())
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K)
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init,
            key)
     if not self.old_style:
         hm.add_int(self.min_bits)
     hm.add_int(self.preferred_bits)
     if not self.old_style:
         hm.add_int(self.max_bits)
     hm.add_mpint(self.p)
     hm.add_mpint(self.g)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     H = SHA.new(str(hm)).digest()
     self.transport._set_K_H(K, H)
     # sign it
     sig = self.transport.get_server_key().sign_ssh_data(self.transport.randpool, H)
     # send reply
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_REPLY))
     m.add_string(key)
     m.add_mpint(self.f)
     m.add_string(str(sig))
     self.transport._send_message(m)
     self.transport._activate_outbound()
Exemple #5
0
    def get_pty(self, term='vt100', width=80, height=24, width_pixels=0,
                height_pixels=0):
        """
        Request a pseudo-terminal from the server.  This is usually used right
        after creating a client channel, to ask the server to provide some
        basic terminal semantics for a shell invoked with `invoke_shell`.
        It isn't necessary (or desirable) to call this method if you're going
        to exectue a single command with `exec_command`.

        :param str term: the terminal type to emulate (for example, ``'vt100'``)
        :param int width: width (in characters) of the terminal screen
        :param int height: height (in characters) of the terminal screen
        :param int width_pixels: width (in pixels) of the terminal screen
        :param int height_pixels: height (in pixels) of the terminal screen

        :raises SSHException:
            if the request was rejected or the channel was closed
        """
        m = Message()
        m.add_byte(cMSG_CHANNEL_REQUEST)
        m.add_int(self.remote_chanid)
        m.add_string('pty-req')
        m.add_boolean(True)
        m.add_string(term)
        m.add_int(width)
        m.add_int(height)
        m.add_int(width_pixels)
        m.add_int(height_pixels)
        m.add_string(bytes())
        self._event_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Exemple #6
0
    def recv_stderr(self, nbytes):
        """
        Receive data from the channel's stderr stream.  Only channels using
        `exec_command` or `invoke_shell` without a pty will ever have data
        on the stderr stream.  The return value is a string representing the
        data received.  The maximum amount of data to be received at once is
        specified by ``nbytes``.  If a string of length zero is returned, the
        channel stream has closed.

        :param int nbytes: maximum number of bytes to read.
        :return: received data as a `str`

        :raises socket.timeout: if no data is ready before the timeout set by
            `settimeout`.

        .. versionadded:: 1.1
        """
        try:
            out = self.in_stderr_buffer.read(nbytes, self.timeout)
        except PipeTimeout:
            raise socket.timeout()

        ack = self._check_add_window(len(out))
        # no need to hold the channel lock when sending this
        if ack > 0:
            m = Message()
            m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST)
            m.add_int(self.remote_chanid)
            m.add_int(ack)
            self.transport._send_user_message(m)

        return out
Exemple #7
0
 def start_kex(self):
     """
     Start the GSS-API / SSPI Authenticated Diffie-Hellman Key Exchange.
     """
     self._generate_x()
     if self.transport.server_mode:
         # compute f = g^x mod p, but don't send it yet
         self.f = pow(self.G, self.x, self.P)
         self.transport._expect_packet(MSG_KEXGSS_INIT)
         return
     # compute e = g^x mod p (where g=2), and send it
     self.e = pow(self.G, self.x, self.P)
     # Initialize GSS-API Key Exchange
     self.gss_host = self.transport.gss_host
     m = Message()
     m.add_byte(c_MSG_KEXGSS_INIT)
     m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host))
     m.add_mpint(self.e)
     self.transport._send_message(m)
     self.transport._expect_packet(
         MSG_KEXGSS_HOSTKEY,
         MSG_KEXGSS_CONTINUE,
         MSG_KEXGSS_COMPLETE,
         MSG_KEXGSS_ERROR,
     )
Exemple #8
0
 def test_handle_13(self):
     # Test handling a SSH2_AGENTC_SIGN_REQUEST
     msg = Message()
     # Please sign some data
     msg.add_byte(byte_chr(13))
     # The id of the key to sign with
     key = list(self.agent.identities.values())[0][0].asbytes()
     msg.add_int(len(key))
     msg.add_bytes(bytes(key))
     # A blob of binary to sign
     blob = b'\x0e' * 10
     msg.add_int(len(blob))
     msg.add_bytes(blob)
     # Go go go
     mtype, msg = self.send(msg)
     self.assertEqual(mtype, 14)
     self.assertEqual(binascii.hexlify(msg.get_binary()), force_bytes((
         '000000077373682d7273610000010031d4c2bfad183557a7055f005c3d0d838d5'
         '701bd7b8a09d6d7f06699c691842c18e2bb62504a4beba0fbf5aeaf62f8106352'
         'b99f60d1fdc2dac1f5ad29566022eff25f62fac38cb2db849ed6b862af5e6bd36'
         '09b249a099848aa6fcfdfe1d93d2538ab4e614ecc95a4282abf8742c7bb591db9'
         '3e049e70a559d29134d207018a650b77fd9a7b6be8a2b1f75efbd66fa5a1e9e96'
         '3a5245ebe76294e0d150dfa2348bc7303203263b11952f0300e7b3a9efab81827'
         'b9e53d8c1cb8b2a1551c22cbab9e747fcff79bf57373f7ec8cb2a0dc9b42a7264'
         'afa4b7913693b709c5418eda02175b0a183549643127be92e79936ffc91479629'
         'c2acdc6aa5c83250a8edfe'
     )))
Exemple #9
0
 def send_stderr(self, s):
     """
     Send data to the channel on the "stderr" stream.  This is normally
     only used by servers to send output from shell commands -- clients
     won't use this.  Returns the number of bytes sent, or 0 if the channel
     stream is closed.  Applications are responsible for checking that all
     data has been sent: if only some of the data was transmitted, the
     application needs to attempt delivery of the remaining data.
     
     :param str s: data to send.
     :return: number of bytes actually sent, as an `int`.
     
     :raises socket.timeout:
         if no data could be sent before the timeout set by `settimeout`.
     
     .. versionadded:: 1.1
     """
     size = len(s)
     self.lock.acquire()
     try:
         size = self._wait_for_send_window(size)
         if size == 0:
             # eof or similar
             return 0
         m = Message()
         m.add_byte(chr(MSG_CHANNEL_EXTENDED_DATA))
         m.add_int(self.remote_chanid)
         m.add_int(1)
         m.add_string(s[:size])
     finally:
         self.lock.release()
     # Note: We release self.lock before calling _send_user_message.
     # Otherwise, we can deadlock during re-keying.
     self.transport._send_user_message(m)
     return size
Exemple #10
0
 def send_stderr(self, s):
     """
     Send data to the channel on the "stderr" stream.  This is normally
     only used by servers to send output from shell commands -- clients
     won't use this.  Returns the number of bytes sent, or 0 if the channel
     stream is closed.  Applications are responsible for checking that all
     data has been sent: if only some of the data was transmitted, the
     application needs to attempt delivery of the remaining data.
     
     @param s: data to send.
     @type s: str
     @return: number of bytes actually sent.
     @rtype: int
     
     @raise socket.timeout: if no data could be sent before the timeout set
         by L{settimeout}.
     
     @since: 1.1
     """
     size = len(s)
     self.lock.acquire()
     try:
         size = self._wait_for_send_window(size)
         if size == 0:
             # eof or similar
             return 0
         m = Message()
         m.add_byte(chr(MSG_CHANNEL_EXTENDED_DATA))
         m.add_int(self.remote_chanid)
         m.add_int(1)
         m.add_string(s[:size])
         self.transport._send_user_message(m)
     finally:
         self.lock.release()
     return size
Exemple #11
0
    def request_x11(self, screen_number=0, auth_protocol=None, auth_cookie=None, single_connection=False, handler=None):
        """
        Request an x11 session on this channel.  If the server allows it,
        further x11 requests can be made from the server to the client,
        when an x11 application is run in a shell session.
        
        From RFC4254::

            It is RECOMMENDED that the 'x11 authentication cookie' that is
            sent be a fake, random cookie, and that the cookie be checked and
            replaced by the real cookie when a connection request is received.
        
        If you omit the auth_cookie, a new secure random 128-bit value will be
        generated, used, and returned.  You will need to use this value to
        verify incoming x11 requests and replace them with the actual local
        x11 cookie (which requires some knoweldge of the x11 protocol).
        
        If a handler is passed in, the handler is called from another thread
        whenever a new x11 connection arrives.  The default handler queues up
        incoming x11 connections, which may be retrieved using
        `.Transport.accept`.  The handler's calling signature is::
        
            handler(channel: Channel, (address: str, port: int))
        
        :param int screen_number: the x11 screen number (0, 10, etc)
        :param str auth_protocol:
            the name of the X11 authentication method used; if none is given,
            ``"MIT-MAGIC-COOKIE-1"`` is used
        :param str auth_cookie:
            hexadecimal string containing the x11 auth cookie; if none is
            given, a secure random 128-bit value is generated
        :param bool single_connection:
            if True, only a single x11 connection will be forwarded (by
            default, any number of x11 connections can arrive over this
            session)
        :param function handler:
            an optional handler to use for incoming X11 connections
        :return: the auth_cookie used
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException("Channel is not open")
        if auth_protocol is None:
            auth_protocol = "MIT-MAGIC-COOKIE-1"
        if auth_cookie is None:
            auth_cookie = binascii.hexlify(os.urandom(16))

        m = Message()
        m.add_byte(cMSG_CHANNEL_REQUEST)
        m.add_int(self.remote_chanid)
        m.add_string("x11-req")
        m.add_boolean(True)
        m.add_boolean(single_connection)
        m.add_string(auth_protocol)
        m.add_string(auth_cookie)
        m.add_int(screen_number)
        self._event_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
        self.transport._set_x11_handler(handler)
        return auth_cookie
Exemple #12
0
    def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0):
        """
        Resize the pseudo-terminal.  This can be used to change the width and
        height of the terminal emulation created in a previous `get_pty` call.

        :param int width: new width (in characters) of the terminal screen
        :param int height: new height (in characters) of the terminal screen
        :param int width_pixels: new width (in pixels) of the terminal screen
        :param int height_pixels: new height (in pixels) of the terminal screen

        :raises SSHException:
            if the request was rejected or the channel was closed
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('window-change')
        m.add_boolean(False)
        m.add_int(width)
        m.add_int(height)
        m.add_int(width_pixels)
        m.add_int(height_pixels)
        self.transport._send_user_message(m)
Exemple #13
0
 def _parse_userauth_gssapi_token(self, m):
     client_token = m.get_string()
     # use the client token as input to establish a secure
     # context.
     sshgss = self.sshgss
     try:
         token = sshgss.ssh_accept_sec_context(
             self.gss_host, client_token, self.auth_username
         )
     except Exception as e:
         self.transport.saved_exception = e
         result = AUTH_FAILED
         self._restore_delegate_auth_handler()
         self._send_auth_result(self.auth_username, self.method, result)
         raise
     if token is not None:
         m = Message()
         m.add_byte(cMSG_USERAUTH_GSSAPI_TOKEN)
         m.add_string(token)
         self.transport._expected_packet = (
             MSG_USERAUTH_GSSAPI_TOKEN,
             MSG_USERAUTH_GSSAPI_MIC,
             MSG_USERAUTH_REQUEST,
         )
         self.transport._send_message(m)
Exemple #14
0
    def recv_stderr(self, nbytes):
        """
        Receive data from the channel's stderr stream.  Only channels using
        L{exec_command} or L{invoke_shell} without a pty will ever have data
        on the stderr stream.  The return value is a string representing the
        data received.  The maximum amount of data to be received at once is
        specified by C{nbytes}.  If a string of length zero is returned, the
        channel stream has closed.

        @param nbytes: maximum number of bytes to read.
        @type nbytes: int
        @return: data.
        @rtype: str

        @raise socket.timeout: if no data is ready before the timeout set by
            L{settimeout}.

        @since: 1.1
        """
        try:
            out = self.in_stderr_buffer.read(nbytes, self.timeout)
        except PipeTimeout as e:
            raise socket.timeout()

        ack = self._check_add_window(len(out))
        # no need to hold the channel lock when sending this
        if ack > 0:
            m = Message()
            m.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST))
            m.add_int(self.remote_chanid)
            m.add_int(ack)
            self.transport._send_user_message(m)

        return out
Exemple #15
0
    def resize_pty(self, width=80, height=24):
        """
        Resize the pseudo-terminal.  This can be used to change the width and
        height of the terminal emulation created in a previous L{get_pty} call.

        @param width: new width (in characters) of the terminal screen
        @type width: int
        @param height: new height (in characters) of the terminal screen
        @type height: int
        @return: C{True} if the operation succeeded; C{False} if not.
        @rtype: bool
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('window-change')
        m.add_boolean(1)
        m.add_int(width)
        m.add_int(height)
        m.add_int(0).add_int(0)
        self.event.clear()
        self.transport._send_user_message(m)
        while True:
            self.event.wait(0.1)
            if self.closed:
                return False
            if self.event.isSet():
                return True
Exemple #16
0
    def invoke_subsystem(self, subsystem):
        """
        Request a subsystem on the server (for example, C{sftp}).  If the
        server allows it, the channel will then be directly connected to the
        requested subsystem.
        
        When the subsystem finishes, the channel will be closed and can't be
        reused.

        @param subsystem: name of the subsystem being requested.
        @type subsystem: str
        @return: C{True} if the operation succeeded; C{False} if not.
        @rtype: bool
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('subsystem')
        m.add_boolean(1)
        m.add_string(subsystem)
        self.event.clear()
        self.transport._send_user_message(m)
        while True:
            self.event.wait(0.1)
            if self.closed:
                return False
            if self.event.isSet():
                return True
Exemple #17
0
    def invoke_shell(self):
        """
        Request an interactive shell session on this channel.  If the server
        allows it, the channel will then be directly connected to the stdin,
        stdout, and stderr of the shell.

        Normally you would call `get_pty` before this, in which case the
        shell will operate through the pty, and the channel will be connected
        to the stdin and stdout of the pty.

        When the shell exits, the channel will be closed and can't be reused.
        You must open a new channel if you wish to open another shell.

        :raises:
            `.SSHException` -- if the request was rejected or the channel was
            closed
        """
        m = Message()
        m.add_byte(cMSG_CHANNEL_REQUEST)
        m.add_int(self.remote_chanid)
        m.add_string("shell")
        m.add_boolean(True)
        self._event_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Exemple #18
0
    def resize_pty(self, width=80, height=24):
        """
        Resize the pseudo-terminal.  This can be used to change the width and
        height of the terminal emulation created in a previous L{get_pty} call.

        @param width: new width (in characters) of the terminal screen
        @type width: int
        @param height: new height (in characters) of the terminal screen
        @type height: int

        @raise SSHException: if the request was rejected or the channel was
            closed
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('window-change')
        m.add_boolean(True)
        m.add_int(width)
        m.add_int(height)
        m.add_int(0).add_int(0)
        self.event.clear()
        self.transport._send_user_message(m)
        self._wait_for_event()
Exemple #19
0
    def exec_command(self, command):
        """
        Execute a command on the server.  If the server allows it, the channel
        will then be directly connected to the stdin, stdout, and stderr of
        the command being executed.

        When the command finishes executing, the channel will be closed and
        can't be reused.  You must open a new channel if you wish to execute
        another command.

        :param str command: a shell command to execute.

        :raises:
            `.SSHException` -- if the request was rejected or the channel was
            closed
        """
        m = Message()
        m.add_byte(cMSG_CHANNEL_REQUEST)
        m.add_int(self.remote_chanid)
        m.add_string("exec")
        m.add_boolean(True)
        m.add_string(command)
        self._event_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
 def _parse_kexecdh_init(self, m):
     Q_C_bytes = m.get_string()
     self.Q_C = ec.EllipticCurvePublicNumbers.from_encoded_point(
         self.curve, Q_C_bytes
     )
     K_S = self.transport.get_server_key().asbytes()
     K = self.P.exchange(ec.ECDH(), self.Q_C.public_key(default_backend()))
     K = long(hexlify(K), 16)
     # compute exchange hash
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init)
     hm.add_string(K_S)
     hm.add_string(Q_C_bytes)
     # SEC1: V2.0  2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion
     hm.add_string(self.Q_S.public_numbers().encode_point())
     hm.add_mpint(long(K))
     H = self.hash_algo(hm.asbytes()).digest()
     self.transport._set_K_H(K, H)
     sig = self.transport.get_server_key().sign_ssh_data(H)
     # construct reply
     m = Message()
     m.add_byte(c_MSG_KEXECDH_REPLY)
     m.add_string(K_S)
     m.add_string(self.Q_S.public_numbers().encode_point())
     m.add_string(sig)
     self.transport._send_message(m)
     self.transport._activate_outbound()
Exemple #21
0
    def set_environment_variable(self, name, value):
        """
        Set the value of an environment variable.

        .. warning::
            The server may reject this request depending on its ``AcceptEnv``
            setting; such rejections will fail silently (which is common client
            practice for this particular request type). Make sure you
            understand your server's configuration before using!

        :param str name: name of the environment variable
        :param str value: value of the environment variable

        :raises:
            `.SSHException` -- if the request was rejected or the channel was
            closed
        """
        m = Message()
        m.add_byte(cMSG_CHANNEL_REQUEST)
        m.add_int(self.remote_chanid)
        m.add_string("env")
        m.add_boolean(False)
        m.add_string(name)
        m.add_string(value)
        self.transport._send_user_message(m)
Exemple #22
0
 def _parse_kexdh_gex_request_old(self, m):
     # same as above, but without min_bits or max_bits (used by older
     # clients like putty)
     self.preferred_bits = m.get_int()
     # smoosh the user's preferred size into our own limits
     if self.preferred_bits > self.max_bits:
         self.preferred_bits = self.max_bits
     if self.preferred_bits < self.min_bits:
         self.preferred_bits = self.min_bits
     # generate prime
     pack = self.transport._get_modulus_pack()
     if pack is None:
         raise SSHException("Can't do server-side gex with no modulus pack")
     self.transport._log(
         DEBUG, "Picking p (~ {} bits)".format(self.preferred_bits)
     )
     self.g, self.p = pack.get_modulus(
         self.min_bits, self.preferred_bits, self.max_bits
     )
     m = Message()
     m.add_byte(c_MSG_KEXDH_GEX_GROUP)
     m.add_mpint(self.p)
     m.add_mpint(self.g)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_INIT)
     self.old_style = True
Exemple #23
0
    def send(self, s):
        """
        Send data to the channel.  Returns the number of bytes sent, or 0 if
        the channel stream is closed.  Applications are responsible for
        checking that all data has been sent: if only some of the data was
        transmitted, the application needs to attempt delivery of the remaining
        data.

        @param s: data to send
        @type s: str
        @return: number of bytes actually sent
        @rtype: int

        @raise socket.timeout: if no data could be sent before the timeout set
            by L{settimeout}.
        """
        size = len(s)
        self.lock.acquire()
        try:
            size = self._wait_for_send_window(size)
            if size == 0:
                # eof or similar
                return 0
            m = Message()
            m.add_byte(chr(MSG_CHANNEL_DATA))
            m.add_int(self.remote_chanid)
            m.add_string(s[:size])
        finally:
            self.lock.release()
        # Note: We release self.lock before calling _send_user_message.
        # Otherwise, we can deadlock during re-keying.
        self.transport._send_user_message(m)
        return size
Exemple #24
0
    def _parse_kexgss_group(self, m):
        """
        Parse the SSH2_MSG_KEXGSS_GROUP message (client mode).

        :param `Message` m: The content of the SSH2_MSG_KEXGSS_GROUP message
        """
        self.p = m.get_mpint()
        self.g = m.get_mpint()
        # reject if p's bit length < 1024 or > 8192
        bitlen = util.bit_length(self.p)
        if (bitlen < 1024) or (bitlen > 8192):
            raise SSHException(
                'Server-generated gex p (don\'t ask) is out of range '
                '({} bits)'.format(bitlen))
        self.transport._log(DEBUG, 'Got server p ({} bits)'.format(bitlen))  # noqa
        self._generate_x()
        # now compute e = g^x mod p
        self.e = pow(self.g, self.x, self.p)
        m = Message()
        m.add_byte(c_MSG_KEXGSS_INIT)
        m.add_string(self.kexgss.ssh_init_sec_context(target=self.gss_host))
        m.add_mpint(self.e)
        self.transport._send_message(m)
        self.transport._expect_packet(MSG_KEXGSS_HOSTKEY,
                                      MSG_KEXGSS_CONTINUE,
                                      MSG_KEXGSS_COMPLETE,
                                      MSG_KEXGSS_ERROR)
Exemple #25
0
    def get_pty(self, term='vt100', width=80, height=24):
        """
        Request a pseudo-terminal from the server.  This is usually used right
        after creating a client channel, to ask the server to provide some
        basic terminal semantics for a shell invoked with L{invoke_shell}.
        It isn't necessary (or desirable) to call this method if you're going
        to exectue a single command with L{exec_command}.

        @param term: the terminal type to emulate (for example, C{'vt100'})
        @type term: str
        @param width: width (in characters) of the terminal screen
        @type width: int
        @param height: height (in characters) of the terminal screen
        @type height: int
        
        @raise SSHException: if the request was rejected or the channel was
            closed
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('pty-req')
        m.add_boolean(True)
        m.add_string(term)
        m.add_int(width)
        m.add_int(height)
        # pixel height, width (usually useless)
        m.add_int(0).add_int(0)
        m.add_string('')
        self.event.clear()
        self.transport._send_user_message(m)
        self._wait_for_event()
Exemple #26
0
    def recv(self, nbytes):
        """
        Receive data from the channel.  The return value is a string
        representing the data received.  The maximum amount of data to be
        received at once is specified by ``nbytes``.  If a string of length zero
        is returned, the channel stream has closed.

        :param int nbytes: maximum number of bytes to read.
        :return: received data, as a `bytes`

        :raises socket.timeout:
            if no data is ready before the timeout set by `settimeout`.
        """
        try:
            out = self.in_buffer.read(nbytes, self.timeout)
        except PipeTimeout:
            raise socket.timeout()

        ack = self._check_add_window(len(out))
        # no need to hold the channel lock when sending this
        if ack > 0:
            m = Message()
            m.add_byte(cMSG_CHANNEL_WINDOW_ADJUST)
            m.add_int(self.remote_chanid)
            m.add_int(ack)
            self.transport._send_user_message(m)

        return out
Exemple #27
0
 def invoke_shell(self):
     """
     Request an interactive shell session on this channel.  If the server
     allows it, the channel will then be directly connected to the stdin,
     stdout, and stderr of the shell.
     
     Normally you would call L{get_pty} before this, in which case the
     shell will operate through the pty, and the channel will be connected
     to the stdin and stdout of the pty.
     
     When the shell exits, the channel will be closed and can't be reused.
     You must open a new channel if you wish to open another shell.
     
     @raise SSHException: if the request was rejected or the channel was
         closed
     """
     if self.closed or self.eof_received or self.eof_sent or not self.active:
         raise SSHException('Channel is not open')
     m = Message()
     m.add_byte(chr(MSG_CHANNEL_REQUEST))
     m.add_int(self.remote_chanid)
     m.add_string('shell')
     m.add_boolean(1)
     self.event.clear()
     self.transport._send_user_message(m)
     self._wait_for_event()
Exemple #28
0
 def _parse_kexdh_init(self, m):
     # server mode
     self.e = m.get_mpint()
     if (self.e < 1) or (self.e > P - 1):
         raise SSHException('Client kex "e" is out of range')
     K = pow(self.e, self.x, P)
     key = str(self.transport.get_server_key())
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K)
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init)
     hm.add_string(key)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     H = SHA.new(str(hm)).digest()
     self.transport._set_K_H(K, H)
     # sign it
     sig = self.transport.get_server_key().sign_ssh_data(self.transport.randpool, H)
     # send reply
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_REPLY))
     m.add_string(key)
     m.add_mpint(self.f)
     m.add_string(str(sig))
     self.transport._send_message(m)
     self.transport._activate_outbound()
Exemple #29
0
 def _parse_kexdh_gex_request(self, m):
     minbits = m.get_int()
     preferredbits = m.get_int()
     maxbits = m.get_int()
     # smoosh the user's preferred size into our own limits
     if preferredbits > self.max_bits:
         preferredbits = self.max_bits
     if preferredbits < self.min_bits:
         preferredbits = self.min_bits
     # fix min/max if they're inconsistent.  technically, we could just pout
     # and hang up, but there's no harm in giving them the benefit of the
     # doubt and just picking a bitsize for them.
     if minbits > preferredbits:
         minbits = preferredbits
     if maxbits < preferredbits:
         maxbits = preferredbits
     # now save a copy
     self.min_bits = minbits
     self.preferred_bits = preferredbits
     self.max_bits = maxbits
     # generate prime
     pack = self.transport._get_modulus_pack()
     if pack is None:
         raise SSHException('Can\'t do server-side gex with no modulus pack')
     self.transport._log(DEBUG, 'Picking p (%d <= %d <= %d bits)' % (minbits, preferredbits, maxbits))
     self.g, self.p = pack.get_modulus(minbits, preferredbits, maxbits)
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_GROUP))
     m.add_mpint(self.p)
     m.add_mpint(self.g)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_INIT)
Exemple #30
0
    def invoke_subsystem(self, subsystem):
        """
        Request a subsystem on the server (for example, C{sftp}).  If the
        server allows it, the channel will then be directly connected to the
        requested subsystem.
        
        When the subsystem finishes, the channel will be closed and can't be
        reused.

        @param subsystem: name of the subsystem being requested.
        @type subsystem: str

        @raise SSHException: if the request was rejected or the channel was
            closed
        """
        if self.closed or self.eof_received or self.eof_sent or not self.active:
            raise SSHException('Channel is not open')
        m = Message()
        m.add_byte(chr(MSG_CHANNEL_REQUEST))
        m.add_int(self.remote_chanid)
        m.add_string('subsystem')
        m.add_boolean(True)
        m.add_string(subsystem)
        self.event.clear()
        self.transport._send_user_message(m)
        self._wait_for_event()
Exemple #31
0
    def request_x11(
            self,
            screen_number=0,
            auth_protocol=None,
            auth_cookie=None,
            single_connection=False,
            handler=None
    ):
        """
        Request an x11 session on this channel.  If the server allows it,
        further x11 requests can be made from the server to the client,
        when an x11 application is run in a shell session.

        From :rfc:`4254`::

            It is RECOMMENDED that the 'x11 authentication cookie' that is
            sent be a fake, random cookie, and that the cookie be checked and
            replaced by the real cookie when a connection request is received.

        If you omit the auth_cookie, a new secure random 128-bit value will be
        generated, used, and returned.  You will need to use this value to
        verify incoming x11 requests and replace them with the actual local
        x11 cookie (which requires some knowledge of the x11 protocol).

        If a handler is passed in, the handler is called from another thread
        whenever a new x11 connection arrives.  The default handler queues up
        incoming x11 connections, which may be retrieved using
        `.Transport.accept`.  The handler's calling signature is::

            handler(channel: Channel, (address: str, port: int))

        :param int screen_number: the x11 screen number (0, 10, etc.)
        :param str auth_protocol:
            the name of the X11 authentication method used; if none is given,
            ``"MIT-MAGIC-COOKIE-1"`` is used
        :param str auth_cookie:
            hexadecimal string containing the x11 auth cookie; if none is
            given, a secure random 128-bit value is generated
        :param bool single_connection:
            if True, only a single x11 connection will be forwarded (by
            default, any number of x11 connections can arrive over this
            session)
        :param handler:
            an optional callable handler to use for incoming X11 connections
        :return: the auth_cookie used
        """
        if auth_protocol is None:
            auth_protocol = 'MIT-MAGIC-COOKIE-1'
        if auth_cookie is None:
            auth_cookie = binascii.hexlify(os.urandom(16))

        m = Message()
        m.add_byte(cMSG_CHANNEL_REQUEST)
        m.add_int(self.remote_chanid)
        m.add_string('x11-req')
        m.add_boolean(True)
        m.add_boolean(single_connection)
        m.add_string(auth_protocol)
        m.add_string(auth_cookie)
        m.add_int(screen_number)
        self._event_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
        self.transport._set_x11_handler(handler)
        return auth_cookie
Exemple #32
0
 def _handle_request(self, m):
     key = m.get_text()
     want_reply = m.get_boolean()
     server = self.transport.server_object
     ok = False
     if key == 'exit-status':
         self.exit_status = m.get_int()
         self.status_event.set()
         ok = True
     elif key == 'xon-xoff':
         # ignore
         ok = True
     elif key == 'pty-req':
         term = m.get_string()
         width = m.get_int()
         height = m.get_int()
         pixelwidth = m.get_int()
         pixelheight = m.get_int()
         modes = m.get_string()
         if server is None:
             ok = False
         else:
             ok = server.check_channel_pty_request(
                 self,
                 term,
                 width,
                 height,
                 pixelwidth,
                 pixelheight,
                 modes
             )
     elif key == 'shell':
         if server is None:
             ok = False
         else:
             ok = server.check_channel_shell_request(self)
     elif key == 'env':
         name = m.get_string()
         value = m.get_string()
         if server is None:
             ok = False
         else:
             ok = server.check_channel_env_request(self, name, value)
     elif key == 'exec':
         cmd = m.get_string()
         if server is None:
             ok = False
         else:
             ok = server.check_channel_exec_request(self, cmd)
     elif key == 'subsystem':
         name = m.get_text()
         if server is None:
             ok = False
         else:
             ok = server.check_channel_subsystem_request(self, name)
     elif key == 'window-change':
         width = m.get_int()
         height = m.get_int()
         pixelwidth = m.get_int()
         pixelheight = m.get_int()
         if server is None:
             ok = False
         else:
             ok = server.check_channel_window_change_request(
                 self, width, height, pixelwidth, pixelheight)
     elif key == 'x11-req':
         single_connection = m.get_boolean()
         auth_proto = m.get_text()
         auth_cookie = m.get_binary()
         screen_number = m.get_int()
         if server is None:
             ok = False
         else:
             ok = server.check_channel_x11_request(
                 self,
                 single_connection,
                 auth_proto,
                 auth_cookie,
                 screen_number
             )
     elif key == '*****@*****.**':
         if server is None:
             ok = False
         else:
             ok = server.check_channel_forward_agent_request(self)
     else:
         self._log(DEBUG, 'Unhandled channel request "{}"'.format(key))
         ok = False
     if want_reply:
         m = Message()
         if ok:
             m.add_byte(cMSG_CHANNEL_SUCCESS)
         else:
             m.add_byte(cMSG_CHANNEL_FAILURE)
         m.add_int(self.remote_chanid)
         self.transport._send_user_message(m)
Exemple #33
0
 def _request_auth(self):
     m = Message()
     m.add_byte(cMSG_SERVICE_REQUEST)
     m.add_string('ssh-userauth')
     self.transport._send_message(m)