twisted.conch.error.ConchError

Here are the examples of the python api twisted.conch.error.ConchError taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

41 Examples 7

3 Source : avatar.py
with MIT License
from autofelix

    def lookupChannel(self, channelType, windowSize, maxPacket, data):
        klass = self.channelLookup.get(channelType, None)
        if not klass:
            raise ConchError(OPEN_UNKNOWN_CHANNEL_TYPE, "unknown channel")
        else:
            return klass(remoteWindow=windowSize,
                         remoteMaxPacket=maxPacket,
                         data=data, avatar=self)


    def lookupSubsystem(self, subsystem, data):

3 Source : default.py
with MIT License
from autofelix

    def _getPassword(self, prompt):
        """
        Prompt for a password using L{getpass.getpass}.

        @param prompt: Written on tty to ask for the input.
        @type prompt: L{str}
        @return: The input.
        @rtype: L{str}
        """
        with self._replaceStdoutStdin():
            try:
                p = getpass.getpass(prompt)
                return p
            except (KeyboardInterrupt, IOError):
                print()
                raise ConchError('PEBKAC')


    def getPassword(self, prompt = None):

3 Source : direct.py
with MIT License
from autofelix

    def receiveError(self, code, desc):
        if self.factory.d is None:
            return
        d, self.factory.d = self.factory.d, None
        d.errback(error.ConchError(desc, code))


    def sendDisconnect(self, code, reason):

3 Source : direct.py
with MIT License
from autofelix

    def sendDisconnect(self, code, reason):
        if self.factory.d is None:
            return
        d, self.factory.d = self.factory.d, None
        transport.SSHClientTransport.sendDisconnect(self, code, reason)
        d.errback(error.ConchError(reason, code))


    def receiveDebug(self, alwaysDisplay, message, lang):

3 Source : conch.py
with MIT License
from autofelix

    def channel_forwarded_tcpip(self, windowSize, maxPacket, data):
        log.msg('FTCP {!r}'.format(data))
        remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
        log.msg(self.remoteForwards)
        log.msg(remoteHP)
        if remoteHP[1] in self.remoteForwards:
            connectHP = self.remoteForwards[remoteHP[1]]
            log.msg('connect forwarding {}'.format(connectHP))
            return SSHConnectForwardingChannel(connectHP,
                                               remoteWindow=windowSize,
                                               remoteMaxPacket=maxPacket,
                                               conn=self)
        else:
            raise ConchError(connection.OPEN_CONNECT_FAILED,
                             "don't know about that port")


    def channelClosed(self, channel):

3 Source : tkconch.py
with MIT License
from autofelix

    def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):
        if ans.lower() not in ('yes', 'no'):
            return deferredAskFrame("Please type  'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
        if ans.lower() == 'no':
            frame.write('Host key verification failed.\r\n')
            raise error.ConchError('bad host key')
        try:
            frame.write(
                "Warning: Permanently added '%s' (%s) to the list of "
                "known hosts.\r\n" %
                (khHost, {b'ssh-dss':'DSA', b'ssh-rsa':'RSA'}[keyType]))
            with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as known_hosts:
                encodedKey = base64.encodestring(pubKey).replace(b'\n', b'')
                known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey))
        except:
            log.deferr()
            raise error.ConchError

    def connectionSecure(self):

3 Source : agent.py
with MIT License
from autofelix

    def _cbRequestIdentities(self, data):
        """
        Unpack a collection of identities into a list of tuples comprised of
        public key blobs and comments.
        """
        if ord(data[0:1]) != AGENT_IDENTITIES_ANSWER:
            raise ConchError('unexpected response: %i' % ord(data[0:1]))
        numKeys = struct.unpack('!L', data[1:5])[0]
        result = []
        data = data[5:]
        for i in range(numKeys):
            blob, data = getNS(data)
            comment, data = getNS(data)
            result.append((blob, comment))
        return result


    def addIdentity(self, blob, comment = b''):

3 Source : agent.py
with MIT License
from autofelix

    def _cbSignData(self, data):
        if ord(data[0:1]) != AGENT_SIGN_RESPONSE:
            raise ConchError('unexpected data: %i' % ord(data[0:1]))
        signature = getNS(data[1:])[0]
        return signature


    def removeIdentity(self, blob):

3 Source : connection.py
with MIT License
from autofelix

    def _cleanupGlobalDeferreds(self):
        """
        All pending requests that have returned a deferred must be errbacked
        when this service is stopped, otherwise they might be left uncalled and
        uncallable.
        """
        for d in self.deferreds["global"]:
            d.errback(error.ConchError("Connection stopped."))
        del self.deferreds["global"][:]


    # packet methods
    def ssh_GLOBAL_REQUEST(self, packet):

3 Source : connection.py
with MIT License
from autofelix

    def ssh_REQUEST_FAILURE(self, packet):
        """
        Our global request failed.  Get the appropriate Deferred and errback
        it with the packet we received.
        """
        log.msg('RF')
        self.deferreds['global'].pop(0).errback(
            error.ConchError('global request failed', packet))

    def ssh_CHANNEL_OPEN(self, packet):

3 Source : connection.py
with MIT License
from autofelix

    def ssh_CHANNEL_OPEN_FAILURE(self, packet):
        """
        The other side did not accept our MSG_CHANNEL_OPEN request.  Payload::
            uint32  local channel number
            uint32  reason code
            string  reason description

        Find the channel using the local channel number and notify it by
        calling its openFailed() method.
        """
        localChannel, reasonCode = struct.unpack('>2L', packet[:8])
        reasonDesc = common.getNS(packet[8:])[0]
        channel = self.channels[localChannel]
        del self.channels[localChannel]
        channel.conn = self
        reason = error.ConchError(reasonDesc, reasonCode)
        log.callWithLogger(channel, channel.openFailed, reason)

    def ssh_CHANNEL_WINDOW_ADJUST(self, packet):

3 Source : connection.py
with MIT License
from autofelix

    def ssh_CHANNEL_FAILURE(self, packet):
        """
        Our channel request to the other side failed.  Payload::
            uint32  local channel number

        Get the C{Deferred} out of self.deferreds and errback it with a
        C{error.ConchError}.
        """
        localChannel = struct.unpack('>L', packet[:4])[0]
        if self.deferreds.get(localChannel):
            d = self.deferreds[localChannel].pop(0)
            log.callWithLogger(self.channels[localChannel],
                               d.errback,
                               error.ConchError('channel request failed'))

    # methods for users of the connection to call

    def sendGlobalRequest(self, request, data, wantReply=0):

3 Source : factory.py
with MIT License
from autofelix

    def startFactory(self):
        """
        Check for public and private keys.
        """
        if not hasattr(self,'publicKeys'):
            self.publicKeys = self.getPublicKeys()
        if not hasattr(self,'privateKeys'):
            self.privateKeys = self.getPrivateKeys()
        if not self.publicKeys or not self.privateKeys:
            raise error.ConchError('no host keys, failing')
        if not hasattr(self,'primes'):
            self.primes = self.getPrimes()


    def buildProtocol(self, addr):

3 Source : test_conch.py
with MIT License
from autofelix

    def processEnded(self, reason):
        """
        Called when the process has ended.

        @param reason: a Failure giving the reason for the process' end.
        """
        if reason.value.exitCode != 0:
            self._getDeferred().errback(
                ConchError("exit code was not 0: {}".format(
                                 reason.value.exitCode)))
        else:
            buf = self.buf.replace(b'\r\n', b'\n')
            self._getDeferred().callback(buf)



class ConchTestForwardingProcess(protocol.ProcessProtocol):

3 Source : test_connection.py
with MIT License
from autofelix

    def lookupChannel(self, channelType, windowSize, maxPacket, data):
        """
        The server wants us to return a channel.  If the requested channel is
        our TestChannel, return it, otherwise return None.
        """
        if channelType == TestChannel.name:
            return TestChannel(remoteWindow=windowSize,
                    remoteMaxPacket=maxPacket,
                    data=data, avatar=self)
        elif channelType == b"conch-error-args":
            # Raise a ConchError with backwards arguments to make sure the
            # connection fixes it for us.  This case should be deprecated and
            # deleted eventually, but only after all of Conch gets the argument
            # order right.
            raise error.ConchError(
                self._ARGS_ERROR_CODE, "error args in wrong order")


    def gotGlobalRequest(self, requestType, data):

3 Source : test_connection.py
with MIT License
from autofelix

    def test_getChannelWithAvatar(self):
        """
        Test that getChannel dispatches to the avatar when an avatar is
        present. Correct functioning without the avatar is verified in
        test_CHANNEL_OPEN.
        """
        channel = self.conn.getChannel(b'TestChannel', 50, 30, b'data')
        self.assertEqual(channel.data, b'data')
        self.assertEqual(channel.remoteWindowLeft, 50)
        self.assertEqual(channel.remoteMaxPacket, 30)
        self.assertRaises(error.ConchError, self.conn.getChannel,
                b'BadChannel', 50, 30, b'data')

    def test_gotGlobalRequestWithoutAvatar(self):

3 Source : test_connection.py
with MIT License
from autofelix

    def test_channelClosedCausesLeftoverChannelDeferredsToErrback(self):
        """
        Whenever an SSH channel gets closed any Deferred that was returned by a
        sendRequest() on its parent connection must be errbacked.
        """
        channel = TestChannel()
        self._openChannel(channel)

        d = self.conn.sendRequest(
            channel, b"dummyrequest", b"dummydata", wantReply=1)
        d = self.assertFailure(d, error.ConchError)
        self.conn.channelClosed(channel)
        return d



class CleanConnectionShutdownTests(unittest.TestCase):

3 Source : test_connection.py
with MIT License
from autofelix

    def test_serviceStoppedCausesLeftoverGlobalDeferredsToErrback(self):
        """
        Once the service is stopped any leftover global deferred returned by
        a sendGlobalRequest() call must be errbacked.
        """
        self.conn.serviceStarted()

        d = self.conn.sendGlobalRequest(
            b"dummyrequest", b"dummydata", wantReply=1)
        d = self.assertFailure(d, error.ConchError)
        self.conn.serviceStopped()
        return d

3 Source : test_ssh.py
with MIT License
from autofelix

    def test_unknownChannel(self):
        """
        When an attempt is made to open an unknown channel type, the L{Deferred}
        returned by L{SSHChannel.sendRequest} fires its errback.
        """
        d = self.assertFailure(
            self._ourServerOurClientTest(b'crazy-unknown-channel'), Exception)
        def cbFailed(ignored):
            errors = self.flushLoggedErrors(error.ConchError)
            self.assertEqual(errors[0].value.args, (3, 'unknown channel'))
            self.assertEqual(len(errors), 1)
        d.addCallback(cbFailed)
        return d


    def test_maxPacket(self):

3 Source : avatar.py
with MIT License
from fbla-competitive-events

    def lookupChannel(self, channelType, windowSize, maxPacket, data):
        klass = self.channelLookup.get(channelType, None)
        if not klass:
            raise ConchError(OPEN_UNKNOWN_CHANNEL_TYPE, "unknown channel")
        else:
            return klass(remoteWindow=windowSize,
                         remoteMaxPacket=maxPacket,
                         data=data, avatar=self)

    def lookupSubsystem(self, subsystem, data):

3 Source : tkconch.py
with MIT License
from fbla-competitive-events

    def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):
        if ans.lower() not in ('yes', 'no'):
            return deferredAskFrame("Please type  'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
        if ans.lower() == 'no':
            frame.write('Host key verification failed.\r\n')
            raise error.ConchError('bad host key')
        try:
            frame.write("Warning: Permanently added '%s' (%s) to the list of known hosts.\r\n" % (khHost, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType]))
            with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as known_hosts:
                encodedKey = base64.encodestring(pubKey).replace('\n', '')
                known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey))
        except:
            log.deferr()
            raise error.ConchError

    def connectionSecure(self):

3 Source : test_conch.py
with MIT License
from fbla-competitive-events

    def processEnded(self, reason):
        """
        Called when the process has ended.

        @param reason: a Failure giving the reason for the process' end.
        """
        if reason.value.exitCode != 0:
            self._getDeferred().errback(
                ConchError("exit code was not 0: %s" %
                                 reason.value.exitCode))
        else:
            buf = self.buf.replace('\r\n', '\n')
            self._getDeferred().callback(buf)



class ConchTestForwardingProcess(protocol.ProcessProtocol):

0 Source : default.py
with MIT License
from autofelix

    def getPrivateKey(self):
        """
        Try to load the private key from the last used file identified by
        C{getPublicKey}, potentially asking for the passphrase if the key is
        encrypted.
        """
        file = os.path.expanduser(self.usedFiles[-1])
        if not os.path.exists(file):
            return None
        try:
            return defer.succeed(keys.Key.fromFile(file))
        except keys.EncryptedKeyError:
            for i in range(3):
                prompt = "Enter passphrase for key '%s': " % self.usedFiles[-1]
                try:
                    p = self._getPassword(prompt).encode(
                        sys.getfilesystemencoding())
                    return defer.succeed(keys.Key.fromFile(file, passphrase=p))
                except (keys.BadKeyError, ConchError):
                    pass
                return defer.fail(ConchError('bad password'))
            raise
        except KeyboardInterrupt:
            print()
            reactor.stop()


    def getGenericAnswers(self, name, instruction, prompts):

0 Source : tkconch.py
with MIT License
from autofelix

    def verifyHostKey(self, pubKey, fingerprint):
        #d = defer.Deferred()
        #d.addCallback(lambda x:defer.succeed(1))
        #d.callback(2)
        #return d
        goodKey = isInKnownHosts(options['host'], pubKey, {'known-hosts': None})
        if goodKey == 1: # good key
            return defer.succeed(1)
        elif goodKey == 2: # AAHHHHH changed
            return defer.fail(error.ConchError('bad host key'))
        else:
            if options['host'] == self.transport.getPeer().host:
                host = options['host']
                khHost = options['host']
            else:
                host = '%s (%s)' % (options['host'],
                                    self.transport.getPeer().host)
                khHost = '%s,%s' % (options['host'],
                                    self.transport.getPeer().host)
            keyType = common.getNS(pubKey)[0]
            ques = """The authenticity of host '%s' can't be established.\r
%s key fingerprint is %s.""" % (host,
                                {b'ssh-dss':'DSA', b'ssh-rsa':'RSA'}[keyType],
                                fingerprint)
            ques+='\r\nAre you sure you want to continue connecting (yes/no)? '
            return deferredAskFrame(ques, 1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)

    def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):

0 Source : agent.py
with MIT License
from autofelix

    def dataReceived(self, data):
        self.buf += data
        while 1:
            if len(self.buf)   <  = 4:
                return
            packLen = struct.unpack('!L', self.buf[:4])[0]
            if len(self.buf)  <  4 + packLen:
                return
            packet, self.buf = self.buf[4:4 + packLen], self.buf[4 + packLen:]
            reqType = ord(packet[0:1])
            d = self.deferreds.pop(0)
            if reqType == AGENT_FAILURE:
                d.errback(ConchError('agent failure'))
            elif reqType == AGENT_SUCCESS:
                d.callback(b'')
            else:
                d.callback(packet)


    def sendRequest(self, reqType, data):

0 Source : connection.py
with MIT License
from autofelix

    def ssh_CHANNEL_OPEN(self, packet):
        """
        The other side wants to get a channel.  Payload::
            string  channel name
            uint32  remote channel number
            uint32  remote window size
            uint32  remote maximum packet size
              <  channel specific data>

        We get a channel from self.getChannel(), give it a local channel number
        and notify the other side.  Then notify the channel by calling its
        channelOpen method.
        """
        channelType, rest = common.getNS(packet)
        senderChannel, windowSize, maxPacket = struct.unpack('>3L', rest[:12])
        packet = rest[12:]
        try:
            channel = self.getChannel(channelType, windowSize, maxPacket,
                            packet)
            localChannel = self.localChannelID
            self.localChannelID += 1
            channel.id = localChannel
            self.channels[localChannel] = channel
            self.channelsToRemoteChannel[channel] = senderChannel
            self.localToRemoteChannel[localChannel] = senderChannel
            self.transport.sendPacket(MSG_CHANNEL_OPEN_CONFIRMATION,
                struct.pack('>4L', senderChannel, localChannel,
                    channel.localWindowSize,
                    channel.localMaxPacket)+channel.specificData)
            log.callWithLogger(channel, channel.channelOpen, packet)
        except Exception as e:
            log.err(e, 'channel open failed')
            if isinstance(e, error.ConchError):
                textualInfo, reason = e.args
                if isinstance(textualInfo, (int, long)):
                    # See #3657 and #3071
                    textualInfo, reason = reason, textualInfo
            else:
                reason = OPEN_CONNECT_FAILED
                textualInfo = "unknown failure"
            self.transport.sendPacket(
                MSG_CHANNEL_OPEN_FAILURE,
                struct.pack('>2L', senderChannel, reason) +
                common.NS(networkString(textualInfo)) + common.NS(b''))

    def ssh_CHANNEL_OPEN_CONFIRMATION(self, packet):

0 Source : connection.py
with MIT License
from autofelix

    def _cbChannelRequest(self, result, localChannel):
        """
        Called back if the other side wanted a reply to a channel request.  If
        the result is true, send a MSG_CHANNEL_SUCCESS.  Otherwise, raise
        a C{error.ConchError}

        @param result: the value returned from the channel's requestReceived()
            method.  If it's False, the request failed.
        @type result: L{bool}
        @param localChannel: the local channel ID of the channel to which the
            request was made.
        @type localChannel: L{int}
        @raises ConchError: if the result is False.
        """
        if not result:
            raise error.ConchError('failed request')
        self.transport.sendPacket(MSG_CHANNEL_SUCCESS, struct.pack('>L',
                                self.localToRemoteChannel[localChannel]))

    def _ebChannelRequest(self, result, localChannel):

0 Source : connection.py
with MIT License
from autofelix

    def getChannel(self, channelType, windowSize, maxPacket, data):
        """
        The other side requested a channel of some sort.
        channelType is the type of channel being requested,
        windowSize is the initial size of the remote window,
        maxPacket is the largest packet we should send,
        data is any other packet data (often nothing).

        We return a subclass of L{SSHChannel}.

        By default, this dispatches to a method 'channel_channelType' with any
        non-alphanumerics in the channelType replace with _'s.  If it cannot
        find a suitable method, it returns an OPEN_UNKNOWN_CHANNEL_TYPE error.
        The method is called with arguments of windowSize, maxPacket, data.

        @type channelType:  L{bytes}
        @type windowSize:   L{int}
        @type maxPacket:    L{int}
        @type data:         L{bytes}
        @rtype:             subclass of L{SSHChannel}/L{tuple}
        """
        log.msg('got channel %r request' % (channelType))
        if hasattr(self.transport, "avatar"): # this is a server!
            chan = self.transport.avatar.lookupChannel(channelType,
                                                       windowSize,
                                                       maxPacket,
                                                       data)
        else:
            channelType = channelType.translate(TRANSLATE_TABLE)
            attr = 'channel_%s' % nativeString(channelType)
            f = getattr(self, attr, None)
            if f is not None:
                chan = f(windowSize, maxPacket, data)
            else:
                chan = None
        if chan is None:
            raise error.ConchError('unknown channel',
                    OPEN_UNKNOWN_CHANNEL_TYPE)
        else:
            chan.conn = self
            return chan

    def gotGlobalRequest(self, requestType, data):

0 Source : connection.py
with MIT License
from autofelix

    def channelClosed(self, channel):
        """
        Called when a channel is closed.
        It clears the local state related to the channel, and calls
        channel.closed().
        MAKE SURE YOU CALL THIS METHOD, even if you subclass L{SSHConnection}.
        If you don't, things will break mysteriously.

        @type channel: L{SSHChannel}
        """
        if channel in self.channelsToRemoteChannel: # actually open
            channel.localClosed = channel.remoteClosed = True
            del self.localToRemoteChannel[channel.id]
            del self.channels[channel.id]
            del self.channelsToRemoteChannel[channel]
            for d in self.deferreds.pop(channel.id, []):
                d.errback(error.ConchError("Channel closed."))
            log.callWithLogger(channel, channel.closed)



MSG_GLOBAL_REQUEST = 80

0 Source : userauth.py
with MIT License
from autofelix

    def tryAuth(self, kind, user, data):
        """
        Try to authenticate the user with the given method.  Dispatches to a
        auth_* method.

        @param kind: the authentication method to try.
        @type kind: L{bytes}
        @param user: the username the client is authenticating with.
        @type user: L{bytes}
        @param data: authentication specific data sent by the client.
        @type data: L{bytes}
        @return: A Deferred called back if the method succeeded, or erred back
            if it failed.
        @rtype: C{defer.Deferred}
        """
        log.msg('%r trying auth %r' % (user, kind))
        if kind not in self.supportedAuthentications:
            return defer.fail(
                    error.ConchError('unsupported authentication, failing'))
        kind = nativeString(kind.replace(b'-', b'_'))
        f = getattr(self, 'auth_%s' % (kind,), None)
        if f:
            ret = f(data)
            if not ret:
                return defer.fail(
                        error.ConchError(
                            '%s return None instead of a Deferred'
                            % (kind, )))
            else:
                return ret
        return defer.fail(error.ConchError('bad auth type: %s' % (kind,)))


    def ssh_USERAUTH_REQUEST(self, packet):

0 Source : userauth.py
with MIT License
from autofelix

    def ssh_USERAUTH_REQUEST(self, packet):
        """
        The client has requested authentication.  Payload::
            string user
            string next service
            string method
              <  authentication specific data>

        @type packet: L{bytes}
        """
        user, nextService, method, rest = getNS(packet, 3)
        if user != self.user or nextService != self.nextService:
            self.authenticatedWith = [] # clear auth state
        self.user = user
        self.nextService = nextService
        self.method = method
        d = self.tryAuth(method, user, rest)
        if not d:
            self._ebBadAuth(
                failure.Failure(error.ConchError('auth returned none')))
            return
        d.addCallback(self._cbFinishedAuth)
        d.addErrback(self._ebMaybeBadAuth)
        d.addErrback(self._ebBadAuth)
        return d


    def _cbFinishedAuth(self, result):

0 Source : userauth.py
with MIT License
from autofelix

    def _cbFinishedAuth(self, result):
        """
        The callback when user has successfully been authenticated.  For a
        description of the arguments, see L{twisted.cred.portal.Portal.login}.
        We start the service requested by the user.
        """
        (interface, avatar, logout) = result
        self.transport.avatar = avatar
        self.transport.logoutFunction = logout
        service = self.transport.factory.getService(self.transport,
                self.nextService)
        if not service:
            raise error.ConchError('could not get next service: %s'
                                  % self.nextService)
        log.msg('%r authenticated with %r' % (self.user, self.method))
        self.transport.sendPacket(MSG_USERAUTH_SUCCESS, b'')
        self.transport.setService(service())


    def _ebMaybeBadAuth(self, reason):

0 Source : _kex.py
with MIT License
from autofelix

def getKex(kexAlgorithm):
    """
    Get a description of a named key exchange algorithm.

    @param kexAlgorithm: The key exchange algorithm name.
    @type kexAlgorithm: L{bytes}

    @return: A description of the key exchange algorithm named by
        C{kexAlgorithm}.
    @rtype: L{_IKexAlgorithm}

    @raises ConchError: if the key exchange algorithm is not found.
    """
    if kexAlgorithm not in _kexAlgorithms:
        raise error.ConchError(
            "Unsupported key exchange algorithm: %s" % (kexAlgorithm,))
    return _kexAlgorithms[kexAlgorithm]



def isEllipticCurve(kexAlgorithm):

0 Source : test_connection.py
with MIT License
from autofelix

    def _lookupChannelErrorTest(self, code):
        """
        Deliver a request for a channel open which will result in an exception
        being raised during channel lookup.  Assert that an error response is
        delivered as a result.
        """
        self.transport.avatar._ARGS_ERROR_CODE = code
        self.conn.ssh_CHANNEL_OPEN(
            common.NS(b'conch-error-args') + b'\x00\x00\x00\x01' * 4)
        errors = self.flushLoggedErrors(error.ConchError)
        self.assertEqual(
            len(errors), 1, "Expected one error, got: %r" % (errors,))
        self.assertEqual(errors[0].value.args, (long(123), "error args in wrong order"))
        self.assertEqual(
            self.transport.packets,
            [(connection.MSG_CHANNEL_OPEN_FAILURE,
              # The response includes some bytes which identifying the
              # associated request, as well as the error code (7b in hex) and
              # the error message.
              b'\x00\x00\x00\x01\x00\x00\x00\x7b' + common.NS(
                        b'error args in wrong order') + common.NS(b''))])


    def test_lookupChannelError(self):

0 Source : test_ssh.py
with MIT License
from autofelix

    def execCommand(self, proto, cmd):
        self.cmd = cmd
        self.proto = proto
        f = cmd.split()[0]
        if f == b'false':
            t = FalseTransport(proto)
            # Avoid disconnecting this immediately.  If the channel is closed
            # before execCommand even returns the caller gets confused.
            reactor.callLater(0, t.loseConnection)
        elif f == b'echo':
            t = EchoTransport(proto)
            t.write(cmd[5:])
            t.loseConnection()
        elif f == b'secho':
            t = SuperEchoTransport(proto)
            t.write(cmd[6:])
            t.loseConnection()
        elif f == b'eecho':
            t = ErrEchoTransport(proto)
            t.write(cmd[6:])
            t.loseConnection()
        else:
            raise error.ConchError('bad exec')
        self.avatar.conn.transport.expectedLoseConnection = 1


    def eofReceived(self):

0 Source : test_ssh.py
with MIT License
from autofelix

    def test_failedExec(self):
        """
        If L{SSHChannel.sendRequest} issues an exec which the server responds to
        with an error, the L{Deferred} it returns fires its errback.
        """
        channel = self._ourServerOurClientTest()

        def cbChannel(channel):
            self.channel = channel
            return self.assertFailure(
                channel.conn.sendRequest(
                    channel, b'exec', common.NS(b'jumboliah'), 1),
                Exception)
        channel.addCallback(cbChannel)

        def cbFailed(ignored):
            # The server logs this exception when it cannot perform the
            # requested exec.
            errors = self.flushLoggedErrors(error.ConchError)
            self.assertEqual(errors[0].value.args, ('bad exec', None))
        channel.addCallback(cbFailed)
        return channel


    def test_falseChannel(self):

0 Source : unix.py
with MIT License
from autofelix

    def openShell(self, proto):
        if not self.ptyTuple:  # We didn't get a pty-req.
            log.msg('tried to get shell without pty, failing')
            raise ConchError("no pty")
        uid, gid = self.avatar.getUserGroupId()
        homeDir = self.avatar.getHomeDir()
        shell = self.avatar.getShell()
        self.environ['USER'] = self.avatar.username
        self.environ['HOME'] = homeDir
        self.environ['SHELL'] = shell
        shellExec = os.path.basename(shell)
        peer = self.avatar.conn.transport.transport.getPeer()
        host = self.avatar.conn.transport.transport.getHost()
        self.environ['SSH_CLIENT'] = '%s %s %s' % (
            peer.host, peer.port, host.port)
        self.getPtyOwnership()
        self.pty = self._reactor.spawnProcess(
            proto, shell, ['-%s' % (shellExec,)], self.environ, homeDir, uid,
            gid, usePTY=self.ptyTuple)
        self.addUTMPEntry()
        fcntl.ioctl(self.pty.fileno(), tty.TIOCSWINSZ,
                    struct.pack('4H', *self.winSize))
        if self.modes:
            self.setModes()
        self.oldWrite = proto.transport.write
        proto.transport.write = self._writeHack
        self.avatar.conn.transport.transport.setTcpNoDelay(1)


    def execCommand(self, proto, cmd):

0 Source : connection.py
with The Unlicense
from dspray95

    def channelClosed(self, channel):
        """
        Called when a channel is closed.
        It clears the local state related to the channel, and calls
        channel.closed().
        MAKE SURE YOU CALL THIS METHOD, even if you subclass L{SSHConnection}.
        If you don't, things will break mysteriously.

        @type channel: L{SSHChannel}
        """
        if channel in self.channelsToRemoteChannel: # actually open
            channel.localClosed = channel.remoteClosed = True
            del self.localToRemoteChannel[channel.id]
            del self.channels[channel.id]
            del self.channelsToRemoteChannel[channel]
            for d in self.deferreds.setdefault(channel.id, []):
                d.errback(error.ConchError("Channel closed."))
            del self.deferreds[channel.id][:]
            log.callWithLogger(channel, channel.closed)

MSG_GLOBAL_REQUEST = 80

0 Source : conch.py
with MIT License
from fbla-competitive-events

    def channel_forwarded_tcpip(self, windowSize, maxPacket, data):
        log.msg('%s %s' % ('FTCP', repr(data)))
        remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
        log.msg(self.remoteForwards)
        log.msg(remoteHP)
        if remoteHP[1] in self.remoteForwards:
            connectHP = self.remoteForwards[remoteHP[1]]
            log.msg('connect forwarding %s' % (connectHP,))
            return SSHConnectForwardingChannel(connectHP,
                                            remoteWindow = windowSize,
                                            remoteMaxPacket = maxPacket,
                                            conn = self)
        else:
            raise ConchError(connection.OPEN_CONNECT_FAILED, "don't know about that port")

#    def channel_auth_agent_openssh_com(self, windowSize, maxPacket, data):
#        if options['agent'] and keyAgent:
#            return agent.SSHAgentForwardingChannel(remoteWindow = windowSize,
#                                             remoteMaxPacket = maxPacket,
#                                             conn = self)
#        else:
#            return connection.OPEN_CONNECT_FAILED, "don't have an agent"

    def channelClosed(self, channel):

0 Source : tkconch.py
with MIT License
from fbla-competitive-events

    def verifyHostKey(self, pubKey, fingerprint):
        #d = defer.Deferred()
        #d.addCallback(lambda x:defer.succeed(1))
        #d.callback(2)
        #return d
        goodKey = isInKnownHosts(options['host'], pubKey, {'known-hosts': None})
        if goodKey == 1: # good key
            return defer.succeed(1)
        elif goodKey == 2: # AAHHHHH changed
            return defer.fail(error.ConchError('bad host key'))
        else:
            if options['host'] == self.transport.getPeer()[1]:
                host = options['host']
                khHost = options['host']
            else:
                host = '%s (%s)' % (options['host'],
                                    self.transport.getPeer()[1])
                khHost = '%s,%s' % (options['host'],
                                    self.transport.getPeer()[1])
            keyType = common.getNS(pubKey)[0]
            ques = """The authenticity of host '%s' can't be established.\r
%s key fingerprint is %s.""" % (host,
                                {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType],
                                fingerprint)
            ques+='\r\nAre you sure you want to continue connecting (yes/no)? '
            return deferredAskFrame(ques, 1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)

    def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):

0 Source : _kex.py
with MIT License
from fbla-competitive-events

def getKex(kexAlgorithm):
    """
    Get a description of a named key exchange algorithm.

    @param kexAlgorithm: The key exchange algorithm name.
    @type kexAlgorithm: L{bytes}

    @return: A description of the key exchange algorithm named by
        C{kexAlgorithm}.
    @rtype: L{_IKexAlgorithm}

    @raises ConchError: if the key exchange algorithm is not found.
    """
    if kexAlgorithm not in _kexAlgorithms:
        raise error.ConchError(
            "Unsupported key exchange algorithm: %s" % (kexAlgorithm,))
    return _kexAlgorithms[kexAlgorithm]



def isFixedGroup(kexAlgorithm):