Esempio n. 1
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)
Esempio n. 2
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 6
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.rng, 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()
Esempio n. 7
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.rng, 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()
Esempio n. 8
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)
Esempio n. 9
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 10
0
 def _auth_message(self):
     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)
     return m
Esempio n. 11
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_pending()
     self.transport._send_user_message(m)
     self._wait_for_event()
Esempio n. 12
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 13
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 14
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 15
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_pending()
     self.transport._send_user_message(m)
     self._wait_for_event()
Esempio n. 16
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)
Esempio n. 17
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 18
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_pending()
        self.transport._send_user_message(m)
        self._wait_for_event()
Esempio n. 19
0
 def _parse_service_accept(self, m):
     service = m.get_string()
     if service == b'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, str):
                 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(bytes(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(b'')
             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)
Esempio n. 20
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
Esempio n. 21
0
 def _disconnect_service_not_available(self):
     m = Message()
     m.add_byte(chr(MSG_DISCONNECT))
     m.add_int(DISCONNECT_SERVICE_NOT_AVAILABLE)
     m.add_string('Service not available')
     m.add_string('en')
     self.transport._send_message(m)
     self.transport.close()
Esempio n. 22
0
 def _disconnect_no_more_auth(self):
     m = Message()
     m.add_byte(chr(MSG_DISCONNECT))
     m.add_int(DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE)
     m.add_string('No more auth methods available')
     m.add_string('en')
     self.transport._send_message(m)
     self.transport.close()
Esempio n. 23
0
 def _disconnect_no_more_auth(self):
     m = Message()
     m.add_byte(chr(MSG_DISCONNECT))
     m.add_int(DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE)
     m.add_string('No more auth methods available')
     m.add_string('en')
     self.transport._send_message(m)
     self.transport.close()
Esempio n. 24
0
 def _disconnect_service_not_available(self):
     m = Message()
     m.add_byte(chr(MSG_DISCONNECT))
     m.add_int(DISCONNECT_SERVICE_NOT_AVAILABLE)
     m.add_string('Service not available')
     m.add_string('en')
     self.transport._send_message(m)
     self.transport.close()
Esempio n. 25
0
    def _parse_userauth_request(self, m):
        if not self.transport.server_mode:
            # er, uh... what?
            m = Message()
            m.add_byte(chr(MSG_USERAUTH_FAILURE))
            m.add_string('none')
            m.add_boolean(0)
            self.transport._send_message(m)
            return
        if self.authenticated:
            # ignore
            return
        username = m.get_string()
        service = m.get_string()
        method = m.get_string()
        self.transport._log(DEBUG, 'Auth request (type=%s) service=%s, username=%s' % (method, service, username))
        if service != 'ssh-connection':
            self._disconnect_service_not_available()
            return
        if (self.auth_username is not None) and (self.auth_username != username):
            self.transport._log(WARNING, 'Auth rejected because the client attempted to change username in mid-flight')
            self._disconnect_no_more_auth()
            return
        self.auth_username = username

        if method == 'none':
            result = self.transport.server_object.check_auth_none(username)
        elif method == 'password':
            changereq = m.get_boolean()
            password = m.get_string()
            try:
                password = password.decode('UTF-8')
            except UnicodeError:
                # some clients/servers expect non-utf-8 passwords!
                # in this case, just return the raw byte string.
                pass
            if changereq:
                # always treated as failure, since we don't support changing passwords, but collect
                # the list of valid auth types from the callback anyway
                self.transport._log(DEBUG, 'Auth request to change passwords (rejected)')
                newpassword = m.get_string()
                try:
                    newpassword = newpassword.decode('UTF-8', 'replace')
                except UnicodeError:
                    pass
                result = AUTH_FAILED
            else:
                result = self.transport.server_object.check_auth_password(username, password)
        elif method == 'publickey':
            sig_attached = m.get_boolean()
            keytype = m.get_string()
            keyblob = m.get_string()
            try:
                key = self.transport._key_info[keytype](Message(keyblob))
            except SSHException, e:
                self.transport._log(INFO, 'Auth rejected: public key: %s' % str(e))
                key = None
            except:
Esempio n. 26
0
 def _negotiate_keys_wrapper(self, m):
     if self.local_kex_init is None: # Remote side sent KEXINIT
         # Simulate in-transit MSG_CHANNEL_WINDOW_ADJUST by sending it
         # before responding to the incoming MSG_KEXINIT.
         m2 = Message()
         m2.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST))
         m2.add_int(chan.remote_chanid)
         m2.add_int(1)    # bytes to add
         self._send_message(m2)
     return _negotiate_keys(self, m)
Esempio n. 27
0
File: agent.py Progetto: goosemo/ssh
 def sign_ssh_data(self, rng, data):
     msg = Message()
     msg.add_byte(chr(SSH2_AGENTC_SIGN_REQUEST))
     msg.add_string(self.blob)
     msg.add_string(data)
     msg.add_int(0)
     ptype, result = self.agent._send_message(msg)
     if ptype != SSH2_AGENT_SIGN_RESPONSE:
         raise SSHException('key cannot be used for signing')
     return result.get_string()
Esempio n. 28
0
 def _send_eof(self):
     # you are holding the lock.
     if self.eof_sent:
         return None
     m = Message()
     m.add_byte(chr(MSG_CHANNEL_EOF))
     m.add_int(self.remote_chanid)
     self.eof_sent = True
     self._log(DEBUG, 'EOF sent (%s)', self._name)
     return m
Esempio n. 29
0
 def sign_ssh_data(self, rng, data):
     msg = Message()
     msg.add_byte(chr(SSH2_AGENTC_SIGN_REQUEST))
     msg.add_string(self.blob)
     msg.add_string(data)
     msg.add_int(0)
     ptype, result = self.agent._send_message(msg)
     if ptype != SSH2_AGENT_SIGN_RESPONSE:
         raise SSHException('key cannot be used for signing')
     return result.get_string()
Esempio n. 30
0
 def _negotiate_keys_wrapper(self, m):
     if self.local_kex_init is None:  # Remote side sent KEXINIT
         # Simulate in-transit MSG_CHANNEL_WINDOW_ADJUST by sending it
         # before responding to the incoming MSG_KEXINIT.
         m2 = Message()
         m2.add_byte(chr(MSG_CHANNEL_WINDOW_ADJUST))
         m2.add_int(chan.remote_chanid)
         m2.add_int(1)  # bytes to add
         self._send_message(m2)
     return _negotiate_keys(self, m)
Esempio n. 31
0
 def _send_eof(self):
     # you are holding the lock.
     if self.eof_sent:
         return None
     m = Message()
     m.add_byte(chr(MSG_CHANNEL_EOF))
     m.add_int(self.remote_chanid)
     self.eof_sent = True
     self._log(DEBUG, 'EOF sent (%s)', self._name)
     return m
Esempio n. 32
0
 def _get_session_blob(self, key, service, username):
     m = Message()
     m.add_string(self.transport.session_id)
     m.add_byte(chr(MSG_USERAUTH_REQUEST))
     m.add_string(username)
     m.add_string(service)
     m.add_string('publickey')
     m.add_boolean(1)
     m.add_string(key.get_name())
     m.add_string(str(key))
     return str(m)
Esempio n. 33
0
 def _parse_service_request(self, m):
     service = m.get_string()
     if self.transport.server_mode and (service == 'ssh-userauth'):
         # accepted
         m = Message()
         m.add_byte(chr(MSG_SERVICE_ACCEPT))
         m.add_string(service)
         self.transport._send_message(m)
         return
     # dunno this one
     self._disconnect_service_not_available()
Esempio n. 34
0
 def _get_session_blob(self, key, service, username):
     m = Message()
     m.add_string(self.transport.session_id)
     m.add_byte(chr(MSG_USERAUTH_REQUEST))
     m.add_string(username)
     m.add_string(service)
     m.add_string(b'publickey')
     m.add_boolean(1)
     m.add_string(key.get_name())
     m.add_string(bytes(key))
     return bytes(m)
Esempio n. 35
0
 def _parse_service_request(self, m):
     service = m.get_string()
     if self.transport.server_mode and (service == 'ssh-userauth'):
         # accepted
         m = Message()
         m.add_byte(chr(MSG_SERVICE_ACCEPT))
         m.add_string(service)
         self.transport._send_message(m)
         return
     # dunno this one
     self._disconnect_service_not_available()
Esempio n. 36
0
 def _interactive_query(self, q):
     # make interactive query instead of response
     m = Message()
     m.add_byte(chr(MSG_USERAUTH_INFO_REQUEST))
     m.add_string(q.name)
     m.add_string(q.instructions)
     m.add_string('')
     m.add_int(len(q.prompts))
     for p in q.prompts:
         m.add_string(p[0])
         m.add_boolean(p[1])
     self.transport._send_message(m)
Esempio n. 37
0
 def _close_internal(self):
     # you are holding the lock.
     if not self.active or self.closed:
         return None, None
     m1 = self._send_eof()
     m2 = Message()
     m2.add_byte(chr(MSG_CHANNEL_CLOSE))
     m2.add_int(self.remote_chanid)
     self._set_closed()
     # can't unlink from the Transport yet -- the remote side may still
     # try to send meta-data (exit-status, etc)
     return m1, m2
Esempio n. 38
0
 def _close_internal(self):
     # you are holding the lock.
     if not self.active or self.closed:
         return None, None
     m1 = self._send_eof()
     m2 = Message()
     m2.add_byte(chr(MSG_CHANNEL_CLOSE))
     m2.add_int(self.remote_chanid)
     self._set_closed()
     # can't unlink from the Transport yet -- the remote side may still
     # try to send meta-data (exit-status, etc)
     return m1, m2
Esempio n. 39
0
 def _interactive_query(self, q):
     # make interactive query instead of response
     m = Message()
     m.add_byte(chr(MSG_USERAUTH_INFO_REQUEST))
     m.add_string(q.name)
     m.add_string(q.instructions)
     m.add_string('')
     m.add_int(len(q.prompts))
     for p in q.prompts:
         m.add_string(p[0])
         m.add_boolean(p[1])
     self.transport._send_message(m)
Esempio n. 40
0
 def start_kex(self):
     self._generate_x()
     if self.transport.server_mode:
         # compute f = g^x mod p, but don't send it yet
         self.f = pow(G, self.x, P)
         self.transport._expect_packet(_MSG_KEXDH_INIT)
         return
     # compute e = g^x mod p (where g=2), and send it
     self.e = pow(G, self.x, P)
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_INIT))
     m.add_mpint(self.e)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_REPLY)
Esempio n. 41
0
 def _parse_kexdh_gex_group(self, m):
     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 (%d bits)' % bitlen)
     self.transport._log(DEBUG, 'Got server p (%d bits)' % bitlen)
     self._generate_x()
     # now compute e = g^x mod p
     self.e = pow(self.g, self.x, self.p)
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_INIT))
     m.add_mpint(self.e)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_REPLY)
Esempio n. 42
0
 def _parse_userauth_info_request(self, m):
     if self.auth_method != 'keyboard-interactive':
         raise SSHException('Illegal info request from server')
     title = m.get_string()
     instructions = m.get_string()
     m.get_string()  # lang
     prompts = m.get_int()
     prompt_list = []
     for i in range(prompts):
         prompt_list.append((m.get_string(), m.get_boolean()))
     response_list = self.interactive_handler(title, instructions, prompt_list)
     
     m = Message()
     m.add_byte(chr(MSG_USERAUTH_INFO_RESPONSE))
     m.add_int(len(response_list))
     for r in response_list:
         m.add_string(r)
     self.transport._send_message(m)
Esempio n. 43
0
 def _parse_kexdh_gex_group(self, m):
     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 (%d bits)'
             % bitlen)
     self.transport._log(DEBUG, 'Got server p (%d bits)' % bitlen)
     self._generate_x()
     # now compute e = g^x mod p
     self.e = pow(self.g, self.x, self.p)
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_INIT))
     m.add_mpint(self.e)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_REPLY)
Esempio n. 44
0
    def _parse_userauth_info_request(self, m):
        if self.auth_method != 'keyboard-interactive':
            raise SSHException('Illegal info request from server')
        title = m.get_string()
        instructions = m.get_string()
        m.get_string()  # lang
        prompts = m.get_int()
        prompt_list = []
        for i in range(prompts):
            prompt_list.append((m.get_string(), m.get_boolean()))
        response_list = self.interactive_handler(title, instructions,
                                                 prompt_list)

        m = Message()
        m.add_byte(chr(MSG_USERAUTH_INFO_RESPONSE))
        m.add_int(len(response_list))
        for r in response_list:
            m.add_string(r)
        self.transport._send_message(m)
Esempio n. 45
0
 def start_kex(self, _test_old_style=False):
     if self.transport.server_mode:
         self.transport._expect_packet(_MSG_KEXDH_GEX_REQUEST, _MSG_KEXDH_GEX_REQUEST_OLD)
         return
     # request a bit range: we accept (min_bits) to (max_bits), but prefer
     # (preferred_bits).  according to the spec, we shouldn't pull the
     # minimum up above 1024.
     m = Message()
     if _test_old_style:
         # only used for unit tests: we shouldn't ever send this
         m.add_byte(chr(_MSG_KEXDH_GEX_REQUEST_OLD))
         m.add_int(self.preferred_bits)
         self.old_style = True
     else:
         m.add_byte(chr(_MSG_KEXDH_GEX_REQUEST))
         m.add_int(self.min_bits)
         m.add_int(self.preferred_bits)
         m.add_int(self.max_bits)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_GROUP)
Esempio n. 46
0
 def send_exit_status(self, status):
     """
     Send the exit status of an executed command to the client.  (This
     really only makes sense in server mode.)  Many clients expect to
     get some sort of status code back from an executed command after
     it completes.
     
     @param status: the exit code of the process
     @type status: int
     
     @since: 1.2
     """
     # in many cases, the channel will not still be open here.
     # that's fine.
     m = Message()
     m.add_byte(chr(MSG_CHANNEL_REQUEST))
     m.add_int(self.remote_chanid)
     m.add_string('exit-status')
     m.add_boolean(False)
     m.add_int(status)
     self.transport._send_user_message(m)
Esempio n. 47
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 (~ %d bits)' % (self.preferred_bits,))
     self.g, self.p = pack.get_modulus(self.min_bits, self.preferred_bits, self.max_bits)
     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)
     self.old_style = True
Esempio n. 48
0
 def send_exit_status(self, status):
     """
     Send the exit status of an executed command to the client.  (This
     really only makes sense in server mode.)  Many clients expect to
     get some sort of status code back from an executed command after
     it completes.
     
     @param status: the exit code of the process
     @type status: int
     
     @since: 1.2
     """
     # in many cases, the channel will not still be open here.
     # that's fine.
     m = Message()
     m.add_byte(chr(MSG_CHANNEL_REQUEST))
     m.add_int(self.remote_chanid)
     m.add_string('exit-status')
     m.add_boolean(False)
     m.add_int(status)
     self.transport._send_user_message(m)
Esempio n. 49
0
 def _send_auth_result(self, username, method, result):
     # okay, send result
     m = Message()
     if result == AUTH_SUCCESSFUL:
         self.transport._log(INFO, 'Auth granted (%s).' % method)
         m.add_byte(chr(MSG_USERAUTH_SUCCESS))
         self.authenticated = True
     else:
         self.transport._log(INFO, 'Auth rejected (%s).' % method)
         m.add_byte(chr(MSG_USERAUTH_FAILURE))
         m.add_string(self.transport.server_object.get_allowed_auths(username))
         if result == AUTH_PARTIALLY_SUCCESSFUL:
             m.add_boolean(1)
         else:
             m.add_boolean(0)
             self.auth_fail_count += 1
     self.transport._send_message(m)
     if self.auth_fail_count >= 10:
         self._disconnect_no_more_auth()
     if result == AUTH_SUCCESSFUL:
         self.transport._auth_trigger()
Esempio n. 50
0
 def start_kex(self, _test_old_style=False):
     if self.transport.server_mode:
         self.transport._expect_packet(_MSG_KEXDH_GEX_REQUEST,
                                       _MSG_KEXDH_GEX_REQUEST_OLD)
         return
     # request a bit range: we accept (min_bits) to (max_bits), but prefer
     # (preferred_bits).  according to the spec, we shouldn't pull the
     # minimum up above 1024.
     m = Message()
     if _test_old_style:
         # only used for unit tests: we shouldn't ever send this
         m.add_byte(chr(_MSG_KEXDH_GEX_REQUEST_OLD))
         m.add_int(self.preferred_bits)
         self.old_style = True
     else:
         m.add_byte(chr(_MSG_KEXDH_GEX_REQUEST))
         m.add_int(self.min_bits)
         m.add_int(self.preferred_bits)
         m.add_int(self.max_bits)
     self.transport._send_message(m)
     self.transport._expect_packet(_MSG_KEXDH_GEX_GROUP)
Esempio n. 51
0
 def _send_auth_result(self, username, method, result):
     # okay, send result
     m = Message()
     if result == AUTH_SUCCESSFUL:
         self.transport._log(INFO, 'Auth granted (%s).' % method)
         m.add_byte(chr(MSG_USERAUTH_SUCCESS))
         self.authenticated = True
     else:
         self.transport._log(INFO, 'Auth rejected (%s).' % method)
         m.add_byte(chr(MSG_USERAUTH_FAILURE))
         m.add_string(
             self.transport.server_object.get_allowed_auths(username))
         if result == AUTH_PARTIALLY_SUCCESSFUL:
             m.add_boolean(1)
         else:
             m.add_boolean(0)
             self.auth_fail_count += 1
     self.transport._send_message(m)
     if self.auth_fail_count >= 10:
         self._disconnect_no_more_auth()
     if result == AUTH_SUCCESSFUL:
         self.transport._auth_trigger()
Esempio n. 52
0
    def request_forward_agent(self, handler):
        """
        Request for a forward SSH Agent on this channel.
        This is only valid for an ssh-agent from openssh !!!

        @param handler: a required handler to use for incoming SSH Agent connections
        @type handler: function

        @return: if we are ok or not (at that time we always return ok)
        @rtype: boolean

        @raise: SSHException in case of channel problem.
        """
        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('*****@*****.**')
        m.add_boolean(False)
        self.transport._send_user_message(m)
        self.transport._set_forward_agent_handler(handler)
        return True
Esempio n. 53
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.rng, 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()
Esempio n. 54
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 (~ %d bits)' % (self.preferred_bits, ))
     self.g, self.p = pack.get_modulus(self.min_bits, self.preferred_bits,
                                       self.max_bits)
     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)
     self.old_style = True
Esempio n. 55
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.assertEquals(str(msg), self.__a)

        msg = Message()
        msg.add_boolean(True)
        msg.add_boolean(False)
        msg.add_byte('\xf3')
        msg.add_bytes('\x00\x3f')
        msg.add_list(['huey', 'dewey', 'louie'])
        self.assertEquals(str(msg), self.__b)

        msg = Message()
        msg.add_int64(5)
        msg.add_int64(0xf5e4d3c2b109L)
        msg.add_mpint(17)
        msg.add_mpint(0xf5e4d3c2b109L)
        msg.add_mpint(-0x65e4d3c2b109L)
        self.assertEquals(str(msg), self.__c)
Esempio n. 56
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
        L{Transport.accept}.  The handler's calling signature is::
        
            handler(channel: Channel, (address: str, port: int))
        
        @param screen_number: the x11 screen number (0, 10, etc)
        @type screen_number: int
        @param auth_protocol: the name of the X11 authentication method used;
            if none is given, C{"MIT-MAGIC-COOKIE-1"} is used
        @type auth_protocol: str
        @param auth_cookie: hexadecimal string containing the x11 auth cookie;
            if none is given, a secure random 128-bit value is generated
        @type auth_cookie: str
        @param single_connection: if True, only a single x11 connection will be
            forwarded (by default, any number of x11 connections can arrive
            over this session)
        @type single_connection: bool
        @param handler: an optional handler to use for incoming X11 connections
        @type handler: function
        @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(self.transport.rng.read(16))

        m = Message()
        m.add_byte(chr(MSG_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
Esempio n. 57
0
 def _handle_request(self, m):
     key = m.get_string()
     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 == '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_string()
         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_string()
         auth_cookie = m.get_string()
         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 "%s"' % key)
         ok = False
     if want_reply:
         m = Message()
         if ok:
             m.add_byte(chr(MSG_CHANNEL_SUCCESS))
         else:
             m.add_byte(chr(MSG_CHANNEL_FAILURE))
         m.add_int(self.remote_chanid)
         self.transport._send_user_message(m)