コード例 #1
0
ファイル: userauth.py プロジェクト: PeterLUYP/2016YCProject
    def auth_publickey(self, packet):
        """
        Public key authentication.  Payload::
            byte has signature
            string algorithm name
            string key blob
            [string signature] (if has signature is True)

        Create a SSHPublicKey credential and verify it using our portal.
        """
        hasSig = ord(packet[0:1])
        algName, blob, rest = getNS(packet[1:], 2)
        pubKey = keys.Key.fromString(blob)
        signature = hasSig and getNS(rest)[0] or None
        if hasSig:
            b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
                 NS(self.user) + NS(self.nextService) + NS(b'publickey') +
                 chr(hasSig) + NS(pubKey.sshType()) + NS(blob))
            c = credentials.SSHPrivateKey(self.user, algName, blob, b,
                                          signature)
            return self.portal.login(c, None, interfaces.IConchUser)
        else:
            c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
            return self.portal.login(c, None,
                                     interfaces.IConchUser).addErrback(
                                         self._ebCheckKey, packet[1:])
コード例 #2
0
    def auth_publickey(self, packet):
        """
        Public key authentication.  Payload::
            byte has signature
            string algorithm name
            string key blob
            [string signature] (if has signature is True)

        Create a SSHPublicKey credential and verify it using our portal.
        """
        hasSig = ord(packet[0:1])
        algName, blob, rest = getNS(packet[1:], 2)
        pubKey = keys.Key.fromString(blob)
        signature = hasSig and getNS(rest)[0] or None
        if hasSig:
            b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
                NS(self.user) + NS(self.nextService) + NS(b'publickey') +
                chr(hasSig) +  NS(pubKey.sshType()) + NS(blob))
            c = credentials.SSHPrivateKey(self.user, algName, blob, b,
                    signature)
            return self.portal.login(c, None, interfaces.IConchUser)
        else:
            c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
            return self.portal.login(c, None,
                    interfaces.IConchUser).addErrback(self._ebCheckKey,
                            packet[1:])
コード例 #3
0
ファイル: userauth.py プロジェクト: JohnDoes95/project_parser
    def auth_publickey(self, packet):
        """
        Public key authentication.  Payload::
            byte has signature
            string algorithm name
            string key blob
            [string signature] (if has signature is True)

        Create a SSHPublicKey credential and verify it using our portal.
        """
        hasSig = ord(packet[0:1])
        algName, blob, rest = getNS(packet[1:], 2)

        try:
            pubKey = keys.Key.fromString(blob)
        except keys.BadKeyError:
            error = "Unsupported key type %s or bad key" % (
                algName.decode('ascii'),)
            log.msg(error)
            return defer.fail(UnauthorizedLogin(error))

        signature = hasSig and getNS(rest)[0] or None
        if hasSig:
            b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
                NS(self.user) + NS(self.nextService) + NS(b'publickey') +
                chr(hasSig) +  NS(pubKey.sshType()) + NS(blob))
            c = credentials.SSHPrivateKey(self.user, algName, blob, b,
                    signature)
            return self.portal.login(c, None, interfaces.IConchUser)
        else:
            c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
            return self.portal.login(c, None,
                    interfaces.IConchUser).addErrback(self._ebCheckKey,
                            packet[1:])
コード例 #4
0
    def auth_publickey(self, packet):
        """
        Public key authentication.  Payload::
            byte has signature
            string algorithm name
            string key blob
            [string signature] (if has signature is True)

        Create a SSHPublicKey credential and verify it using our portal.
        """
        hasSig = ord(packet[0:1])
        algName, blob, rest = getNS(packet[1:], 2)

        try:
            pubKey = keys.Key.fromString(blob)
        except keys.BadKeyError:
            error = "Unsupported key type %s or bad key" % (
                algName.decode('ascii'), )
            log.msg(error)
            return defer.fail(UnauthorizedLogin(error))

        signature = hasSig and getNS(rest)[0] or None
        if hasSig:
            b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
                 NS(self.user) + NS(self.nextService) + NS(b'publickey') +
                 chr(hasSig) + NS(pubKey.sshType()) + NS(blob))
            c = credentials.SSHPrivateKey(self.user, algName, blob, b,
                                          signature)
            return self.portal.login(c, None, interfaces.IConchUser)
        else:
            c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
            return self.portal.login(c, None,
                                     interfaces.IConchUser).addErrback(
                                         self._ebCheckKey, packet[1:])
コード例 #5
0
ファイル: banana.py プロジェクト: JohnDoes95/project_parser
def int2b128(integer, stream):
    if integer == 0:
        stream(chr(0))
        return
    assert integer > 0, "can only encode positive integers"
    while integer:
        stream(chr(integer & 0x7f))
        integer = integer >> 7
コード例 #6
0
ファイル: banana.py プロジェクト: 18636800170/videoWebsie
def int2b128(integer, stream):
    if integer == 0:
        stream(chr(0))
        return
    assert integer > 0, "can only encode positive integers"
    while integer:
        stream(chr(integer & 0x7f))
        integer = integer >> 7
コード例 #7
0
ファイル: window.py プロジェクト: JohnDoes95/project_parser
def rectangle(terminal, position, dimension):
    """
    Draw a rectangle

    @type position: L{tuple}
    @param position: A tuple of the (top, left) coordinates of the rectangle.
    @type dimension: L{tuple}
    @param dimension: A tuple of the (width, height) size of the rectangle.
    """
    (top, left) = position
    (width, height) = dimension
    terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)

    terminal.cursorPosition(top, left)
    terminal.write(chr(0o154))
    terminal.write(chr(0o161) * (width - 2))
    terminal.write(chr(0o153))
    for n in range(height - 2):
        terminal.cursorPosition(left, top + n + 1)
        terminal.write(chr(0o170))
        terminal.cursorForward(width - 2)
        terminal.write(chr(0o170))
    terminal.cursorPosition(0, top + height - 1)
    terminal.write(chr(0o155))
    terminal.write(chr(0o161) * (width - 2))
    terminal.write(chr(0o152))

    terminal.selectCharacterSet(insults.CS_US, insults.G0)
コード例 #8
0
def rectangle(terminal, position, dimension):
    """
    Draw a rectangle

    @type position: L{tuple}
    @param position: A tuple of the (top, left) coordinates of the rectangle.
    @type dimension: L{tuple}
    @param dimension: A tuple of the (width, height) size of the rectangle.
    """
    (top, left) = position
    (width, height) = dimension
    terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)

    terminal.cursorPosition(top, left)
    terminal.write(chr(0o154))
    terminal.write(chr(0o161) * (width - 2))
    terminal.write(chr(0o153))
    for n in range(height - 2):
        terminal.cursorPosition(left, top + n + 1)
        terminal.write(chr(0o170))
        terminal.cursorForward(width - 2)
        terminal.write(chr(0o170))
    terminal.cursorPosition(0, top + height - 1)
    terminal.write(chr(0o155))
    terminal.write(chr(0o161) * (width - 2))
    terminal.write(chr(0o152))

    terminal.selectCharacterSet(insults.CS_US, insults.G0)
コード例 #9
0
ファイル: session.py プロジェクト: JohnDoes95/project_parser
 def processEnded(self, reason=None):
     """
     When we are told the process ended, try to notify the other side about
     how the process ended using the exit-signal or exit-status requests.
     Also, close the channel.
     """
     if reason is not None:
         err = reason.value
         if err.signal is not None:
             signame = self._getSignalName(err.signal)
             if (getattr(os, 'WCOREDUMP', None) is not None and
                 os.WCOREDUMP(err.status)):
                 log.msg('exitSignal: %s (core dumped)' % (signame,))
                 coreDumped = 1
             else:
                 log.msg('exitSignal: %s' % (signame,))
                 coreDumped = 0
             self.session.conn.sendRequest(self.session, b'exit-signal',
                     common.NS(networkString(signame[3:])) +
                     chr(coreDumped) + common.NS(b'') + common.NS(b''))
         elif err.exitCode is not None:
             log.msg('exitCode: %r' % (err.exitCode,))
             self.session.conn.sendRequest(self.session, b'exit-status',
                     struct.pack('>L', err.exitCode))
     self.session.loseConnection()
コード例 #10
0
ファイル: transport.py プロジェクト: davegermiquet/cowrie
    def sendPacket(self, messageType, payload):
        """
        Override because OpenSSH pads with 0 on KEXINIT
        """
        if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
            if not self._allowedKeyExchangeMessageType(messageType):
                self._blockedByKeyExchange.append((messageType, payload))
                return

        payload = chr(messageType) + payload
        if self.outgoingCompression:
            payload = (self.outgoingCompression.compress(payload)
                       + self.outgoingCompression.flush(2))
        bs = self.currentEncryptions.encBlockSize
        # 4 for the packet length and 1 for the padding length
        totalSize = 5 + len(payload)
        lenPad = bs - (totalSize % bs)
        if lenPad < 4:
            lenPad = lenPad + bs
        if messageType == transport.MSG_KEXINIT:
            padding = b'\0' * lenPad
        else:
            padding = randbytes.secureRandom(lenPad)

        packet = (struct.pack(b'!LB',
                              totalSize + lenPad - 4, lenPad) +
                  payload + padding)
        encPacket = (
            self.currentEncryptions.encrypt(packet) +
            self.currentEncryptions.makeMAC(
                self.outgoingPacketSequence, packet))
        self.transport.write(encPacket)
        self.outgoingPacketSequence += 1
コード例 #11
0
ファイル: session.py プロジェクト: Arshdeep10/scrapy
 def processEnded(self, reason=None):
     """
     When we are told the process ended, try to notify the other side about
     how the process ended using the exit-signal or exit-status requests.
     Also, close the channel.
     """
     if reason is not None:
         err = reason.value
         if err.signal is not None:
             signame = self._getSignalName(err.signal)
             if (getattr(os, 'WCOREDUMP', None) is not None and
                 os.WCOREDUMP(err.status)):
                 log.msg('exitSignal: %s (core dumped)' % (signame,))
                 coreDumped = 1
             else:
                 log.msg('exitSignal: %s' % (signame,))
                 coreDumped = 0
             self.session.conn.sendRequest(
                 self.session, b'exit-signal',
                 common.NS(networkString(signame[3:])) + chr(coreDumped) +
                 common.NS(b'') + common.NS(b''))
         elif err.exitCode is not None:
             log.msg('exitCode: %r' % (err.exitCode,))
             self.session.conn.sendRequest(self.session, b'exit-status',
                     struct.pack('>L', err.exitCode))
     self.session.loseConnection()
コード例 #12
0
ファイル: transport.py プロジェクト: softkrates/cowrie
    def sendPacket(self, messageType, payload):
        """
        Override because OpenSSH pads with 0 on KEXINIT
        """
        if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
            if not self._allowedKeyExchangeMessageType(messageType):
                self._blockedByKeyExchange.append((messageType, payload))
                return

        payload = chr(messageType) + payload
        if self.outgoingCompression:
            payload = (self.outgoingCompression.compress(payload)
                       + self.outgoingCompression.flush(2))
        bs = self.currentEncryptions.encBlockSize
        # 4 for the packet length and 1 for the padding length
        totalSize = 5 + len(payload)
        lenPad = bs - (totalSize % bs)
        if lenPad < 4:
            lenPad = lenPad + bs
        if messageType == transport.MSG_KEXINIT:
            padding = b'\0' * lenPad
        else:
            padding = randbytes.secureRandom(lenPad)

        packet = (struct.pack(b'!LB',
                              totalSize + lenPad - 4, lenPad) +
                  payload + padding)
        encPacket = (
            self.currentEncryptions.encrypt(packet) +
            self.currentEncryptions.makeMAC(
                self.outgoingPacketSequence, packet))
        self.transport.write(encPacket)
        self.outgoingPacketSequence += 1
コード例 #13
0
def challenge():
    """I return some random data."""
    crap = b''
    for x in range(random.randrange(15, 25)):
        crap = crap + chr(random.randint(65, 90))
    crap = md5(crap).digest()
    return crap
コード例 #14
0
 def test_publickey(self):
     """
     Test that the client can authenticate with a public key.
     """
     self.authClient.ssh_USERAUTH_FAILURE(NS(b'publickey') + b'\x00')
     self.assertEqual(self.authClient.transport.packets[-1],
             (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
                 + NS(b'publickey') + b'\x00' + NS(b'ssh-dss')
                 + NS(keys.Key.fromString(
                     keydata.publicDSA_openssh).blob())))
    # that key isn't good
     self.authClient.ssh_USERAUTH_FAILURE(NS(b'publickey') + b'\x00')
     blob = NS(keys.Key.fromString(keydata.publicRSA_openssh).blob())
     self.assertEqual(self.authClient.transport.packets[-1],
             (userauth.MSG_USERAUTH_REQUEST, (NS(b'foo') + NS(b'nancy')
                 + NS(b'publickey') + b'\x00' + NS(b'ssh-rsa') + blob)))
     self.authClient.ssh_USERAUTH_PK_OK(NS(b'ssh-rsa')
         + NS(keys.Key.fromString(keydata.publicRSA_openssh).blob()))
     sigData = (NS(self.authClient.transport.sessionID)
             + chr(userauth.MSG_USERAUTH_REQUEST) + NS(b'foo')
             + NS(b'nancy') + NS(b'publickey') + b'\x01' + NS(b'ssh-rsa')
             + blob)
     obj = keys.Key.fromString(keydata.privateRSA_openssh)
     self.assertEqual(self.authClient.transport.packets[-1],
             (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy')
                 + NS(b'publickey') + b'\x01' + NS(b'ssh-rsa') + blob
                 + NS(obj.sign(sigData))))
コード例 #15
0
 def setModes(self):
     pty = self.pty
     attr = tty.tcgetattr(pty.fileno())
     for mode, modeValue in self.modes:
         if mode not in ttymodes.TTYMODES:
             continue
         ttyMode = ttymodes.TTYMODES[mode]
         if len(ttyMode) == 2:  # Flag.
             flag, ttyAttr = ttyMode
             if not hasattr(tty, ttyAttr):
                 continue
             ttyval = getattr(tty, ttyAttr)
             if modeValue:
                 attr[flag] = attr[flag] | ttyval
             else:
                 attr[flag] = attr[flag] & ~ttyval
         elif ttyMode == 'OSPEED':
             attr[tty.OSPEED] = getattr(tty, 'B%s' % (modeValue, ))
         elif ttyMode == 'ISPEED':
             attr[tty.ISPEED] = getattr(tty, 'B%s' % (modeValue, ))
         else:
             if not hasattr(tty, ttyMode):
                 continue
             ttyval = getattr(tty, ttyMode)
             attr[tty.CC][ttyval] = chr(modeValue)
     tty.tcsetattr(pty.fileno(), tty.TCSANOW, attr)
コード例 #16
0
ファイル: userauth.py プロジェクト: tgenov/cowrie
    def _pamConv(self, items):
        """
        Convert a list of PAM authentication questions into a
        MSG_USERAUTH_INFO_REQUEST.  Returns a Deferred that will be called
        back when the user has responses to the questions.

        @param items: a list of 2-tuples (message, kind).  We only care about
            kinds 1 (password) and 2 (text).
        @type items: C{list}
        @rtype: L{defer.Deferred}
        """
        resp = []
        for message, kind in items:
            if kind == 1:  # Password
                resp.append((message, 0))
            elif kind == 2:  # Text
                resp.append((message, 1))
            elif kind in (3, 4):
                return defer.fail(
                    error.ConchError('cannot handle PAM 3 or 4 messages'))
            else:
                return defer.fail(
                    error.ConchError('bad PAM auth kind %i' % (kind, )))
        packet = NS(b'') + NS(b'') + NS(b'')
        packet += struct.pack('>L', len(resp))
        for prompt, echo in resp:
            packet += NS(prompt)
            packet += chr(echo)
        self.transport.sendPacket(userauth.MSG_USERAUTH_INFO_REQUEST, packet)
        self._pamDeferred = defer.Deferred()
        return self._pamDeferred
コード例 #17
0
ファイル: userauth.py プロジェクト: micheloosterhof/cowrie
    def _pamConv(self, items):
        """
        Convert a list of PAM authentication questions into a
        MSG_USERAUTH_INFO_REQUEST.  Returns a Deferred that will be called
        back when the user has responses to the questions.

        @param items: a list of 2-tuples (message, kind).  We only care about
            kinds 1 (password) and 2 (text).
        @type items: C{list}
        @rtype: L{defer.Deferred}
        """
        resp = []
        for message, kind in items:
            if kind == 1:  # Password
                resp.append((message, 0))
            elif kind == 2:  # Text
                resp.append((message, 1))
            elif kind in (3, 4):
                return defer.fail(error.ConchError(
                    'cannot handle PAM 3 or 4 messages'))
            else:
                return defer.fail(error.ConchError(
                    'bad PAM auth kind %i' % (kind,)))
        packet = NS(b'') + NS(b'') + NS(b'')
        packet += struct.pack('>L', len(resp))
        for prompt, echo in resp:
            packet += NS(prompt)
            packet += chr(echo)
        self.transport.sendPacket(userauth.MSG_USERAUTH_INFO_REQUEST, packet)
        self._pamDeferred = defer.Deferred()
        return self._pamDeferred
コード例 #18
0
 def test_publickey(self):
     """
     Test that the client can authenticate with a public key.
     """
     self.authClient.ssh_USERAUTH_FAILURE(NS(b'publickey') + b'\x00')
     self.assertEqual(
         self.authClient.transport.packets[-1],
         (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') + NS(b'nancy') +
          NS(b'publickey') + b'\x00' + NS(b'ssh-dss') +
          NS(keys.Key.fromString(keydata.publicDSA_openssh).blob())))
     # that key isn't good
     self.authClient.ssh_USERAUTH_FAILURE(NS(b'publickey') + b'\x00')
     blob = NS(keys.Key.fromString(keydata.publicRSA_openssh).blob())
     self.assertEqual(self.authClient.transport.packets[-1],
                      (userauth.MSG_USERAUTH_REQUEST,
                       (NS(b'foo') + NS(b'nancy') + NS(b'publickey') +
                        b'\x00' + NS(b'ssh-rsa') + blob)))
     self.authClient.ssh_USERAUTH_PK_OK(
         NS(b'ssh-rsa') +
         NS(keys.Key.fromString(keydata.publicRSA_openssh).blob()))
     sigData = (NS(self.authClient.transport.sessionID) +
                chr(userauth.MSG_USERAUTH_REQUEST) + NS(b'foo') +
                NS(b'nancy') + NS(b'publickey') + b'\x01' + NS(b'ssh-rsa') +
                blob)
     obj = keys.Key.fromString(keydata.privateRSA_openssh)
     self.assertEqual(self.authClient.transport.packets[-1],
                      (userauth.MSG_USERAUTH_REQUEST, NS(b'foo') +
                       NS(b'nancy') + NS(b'publickey') + b'\x01' +
                       NS(b'ssh-rsa') + blob + NS(obj.sign(sigData))))
コード例 #19
0
    def sendGlobalRequest(self, request, data, wantReply=0):
        """
        Send a global request for this connection.  Current this is only used
        for remote->local TCP forwarding.

        @type request:      L{bytes}
        @type data:         L{bytes}
        @type wantReply:    L{bool}
        @rtype              C{Deferred}/L{None}
        """
        self.transport.sendPacket(
            MSG_GLOBAL_REQUEST,
            common.NS(request) + (wantReply and chr(255) or chr(0)) + data)
        if wantReply:
            d = defer.Deferred()
            self.deferreds['global'].append(d)
            return d
コード例 #20
0
 def test_failIfUnknownService(self):
     """
     If the user requests a service that we don't support, the
     authentication should fail.
     """
     packet = NS(b'foo') + NS(b'') + NS(b'password') + chr(0) + NS(b'foo')
     self.authServer.clock = task.Clock()
     d = self.authServer.ssh_USERAUTH_REQUEST(packet)
     return d.addCallback(self._checkFailed)
コード例 #21
0
 def test_failIfUnknownService(self):
     """
     If the user requests a service that we don't support, the
     authentication should fail.
     """
     packet = NS(b'foo') + NS(b'') + NS(b'password') + chr(0) + NS(b'foo')
     self.authServer.clock = task.Clock()
     d = self.authServer.ssh_USERAUTH_REQUEST(packet)
     return d.addCallback(self._checkFailed)
コード例 #22
0
class DialectTests(BananaTestBase):
    """
    Tests for Banana's handling of dialects.
    """
    vocab = b'remote'
    legalPbItem = chr(banana.Banana.outgoingVocabulary[vocab]) + banana.VOCAB
    illegalPbItem = chr(122) + banana.VOCAB

    def test_dialectNotSet(self):
        """
        If no dialect has been selected and a PB VOCAB item is received,
        L{NotImplementedError} is raised.
        """
        self.assertRaises(
            NotImplementedError,
            self.enc.dataReceived, self.legalPbItem)


    def test_receivePb(self):
        """
        If the PB dialect has been selected, a PB VOCAB item is accepted.
        """
        selectDialect(self.enc, b'pb')
        self.enc.dataReceived(self.legalPbItem)
        self.assertEqual(self.result, self.vocab)


    def test_receiveIllegalPb(self):
        """
        If the PB dialect has been selected and an unrecognized PB VOCAB item
        is received, L{banana.Banana.dataReceived} raises L{KeyError}.
        """
        selectDialect(self.enc, b'pb')
        self.assertRaises(KeyError, self.enc.dataReceived, self.illegalPbItem)


    def test_sendPb(self):
        """
        if pb dialect is selected, the sender must be able to send things in
        that dialect.
        """
        selectDialect(self.enc, b'pb')
        self.enc.sendEncoded(self.vocab)
        self.assertEqual(self.legalPbItem, self.io.getvalue())
コード例 #23
0
ファイル: telnet.py プロジェクト: Architektor/PySnip
 def enableRemote(self, opt):
     if opt == LINEMODE:
         self.transport.requestNegotiation(LINEMODE, MODE + chr(TRAPSIG))
         return True
     elif opt == NAWS:
         return True
     elif opt == SGA:
         return True
     else:
         return False
コード例 #24
0
 def enableRemote(self, opt):
     if opt == LINEMODE:
         self.transport.requestNegotiation(LINEMODE, MODE + chr(TRAPSIG))
         return True
     elif opt == NAWS:
         return True
     elif opt == SGA:
         return True
     else:
         return False
コード例 #25
0
 def test_loginTimeout(self):
     """
     Test that the login times out.
     """
     timeoutAuthServer = userauth.SSHUserAuthServer()
     timeoutAuthServer.clock = task.Clock()
     timeoutAuthServer.transport = FakeTransport(self.portal)
     timeoutAuthServer.serviceStarted()
     timeoutAuthServer.clock.advance(11 * 60 * 60)
     timeoutAuthServer.serviceStopped()
     self.assertEqual(timeoutAuthServer.transport.packets,
             [(transport.MSG_DISCONNECT,
             b'\x00' * 3 +
             chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
             NS(b"you took too long") + NS(b''))])
     self.assertTrue(timeoutAuthServer.transport.lostConnection)
コード例 #26
0
ファイル: userauth.py プロジェクト: PeterLUYP/2016YCProject
 def ssh_USERAUTH_PK_OK_publickey(self, packet):
     """
     This is MSG_USERAUTH_PK.  Our public key is valid, so we create a
     signature and try to authenticate with it.
     """
     publicKey = self.lastPublicKey
     b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
          NS(self.user) + NS(self.instance.name) + NS(b'publickey') +
          b'\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
     d = self.signData(publicKey, b)
     if not d:
         self.askForAuth(b'none', b'')
         # this will fail, we'll move on
         return
     d.addCallback(self._cbSignedData)
     d.addErrback(self._ebAuth)
コード例 #27
0
    def test_successfulPasswordAuthentication(self):
        """
        When provided with correct password authentication information, the
        server should respond by sending a MSG_USERAUTH_SUCCESS message with
        no other data.

        See RFC 4252, Section 5.1.
        """
        packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
                           NS(b'foo')])
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        def check(ignored):
            self.assertEqual(
                self.authServer.transport.packets,
                [(userauth.MSG_USERAUTH_SUCCESS, b'')])
        return d.addCallback(check)
コード例 #28
0
ファイル: test_userauth.py プロジェクト: gitPff/twisted
    def test_successfulPasswordAuthentication(self):
        """
        When provided with correct password authentication information, the
        server should respond by sending a MSG_USERAUTH_SUCCESS message with
        no other data.

        See RFC 4252, Section 5.1.
        """
        packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
                           NS(b'foo')])
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        def check(ignored):
            self.assertEqual(
                self.authServer.transport.packets,
                [(userauth.MSG_USERAUTH_SUCCESS, b'')])
        return d.addCallback(check)
コード例 #29
0
 def ssh_USERAUTH_PK_OK_publickey(self, packet):
     """
     This is MSG_USERAUTH_PK.  Our public key is valid, so we create a
     signature and try to authenticate with it.
     """
     publicKey = self.lastPublicKey
     b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
          NS(self.user) + NS(self.instance.name) + NS(b'publickey') +
          b'\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
     d  = self.signData(publicKey, b)
     if not d:
         self.askForAuth(b'none', b'')
         # this will fail, we'll move on
         return
     d.addCallback(self._cbSignedData)
     d.addErrback(self._ebAuth)
コード例 #30
0
 def test_loginTimeout(self):
     """
     Test that the login times out.
     """
     timeoutAuthServer = userauth.SSHUserAuthServer()
     timeoutAuthServer.clock = task.Clock()
     timeoutAuthServer.transport = FakeTransport(self.portal)
     timeoutAuthServer.serviceStarted()
     timeoutAuthServer.clock.advance(11 * 60 * 60)
     timeoutAuthServer.serviceStopped()
     self.assertEqual(
         timeoutAuthServer.transport.packets,
         [(transport.MSG_DISCONNECT, b'\x00' * 3 +
           chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
           NS(b"you took too long") + NS(b''))])
     self.assertTrue(timeoutAuthServer.transport.lostConnection)
コード例 #31
0
 def test_successfulPrivateKeyAuthentication(self):
     """
     Test that private key authentication completes successfully,
     """
     blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
     obj = keys.Key.fromString(keydata.privateRSA_openssh)
     packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\xff'
             + NS(obj.sshType()) + NS(blob))
     self.authServer.transport.sessionID = b'test'
     signature = obj.sign(NS(b'test') + chr(userauth.MSG_USERAUTH_REQUEST)
             + packet)
     packet += NS(signature)
     d = self.authServer.ssh_USERAUTH_REQUEST(packet)
     def check(ignored):
         self.assertEqual(self.authServer.transport.packets,
                 [(userauth.MSG_USERAUTH_SUCCESS, b'')])
     return d.addCallback(check)
コード例 #32
0
    def test_failedPasswordAuthentication(self):
        """
        When provided with invalid authentication details, the server should
        respond by sending a MSG_USERAUTH_FAILURE message which states whether
        the authentication was partially successful, and provides other, open
        options for authentication.

        See RFC 4252, Section 5.1.
        """
        # packet = username, next_service, authentication type, FALSE, password
        packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
                           NS(b'bar')])
        self.authServer.clock = task.Clock()
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        self.assertEqual(self.authServer.transport.packets, [])
        self.authServer.clock.advance(2)
        return d.addCallback(self._checkFailed)
コード例 #33
0
ファイル: test_userauth.py プロジェクト: gitPff/twisted
 def test_successfulPrivateKeyAuthentication(self):
     """
     Test that private key authentication completes successfully,
     """
     blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
     obj = keys.Key.fromString(keydata.privateRSA_openssh)
     packet = (NS(b'foo') + NS(b'none') + NS(b'publickey') + b'\xff'
             + NS(obj.sshType()) + NS(blob))
     self.authServer.transport.sessionID = b'test'
     signature = obj.sign(NS(b'test') + chr(userauth.MSG_USERAUTH_REQUEST)
             + packet)
     packet += NS(signature)
     d = self.authServer.ssh_USERAUTH_REQUEST(packet)
     def check(ignored):
         self.assertEqual(self.authServer.transport.packets,
                 [(userauth.MSG_USERAUTH_SUCCESS, b'')])
     return d.addCallback(check)
コード例 #34
0
ファイル: test_userauth.py プロジェクト: gitPff/twisted
    def test_failedPasswordAuthentication(self):
        """
        When provided with invalid authentication details, the server should
        respond by sending a MSG_USERAUTH_FAILURE message which states whether
        the authentication was partially successful, and provides other, open
        options for authentication.

        See RFC 4252, Section 5.1.
        """
        # packet = username, next_service, authentication type, FALSE, password
        packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
                           NS(b'bar')])
        self.authServer.clock = task.Clock()
        d = self.authServer.ssh_USERAUTH_REQUEST(packet)
        self.assertEqual(self.authServer.transport.packets, [])
        self.authServer.clock.advance(2)
        return d.addCallback(self._checkFailed)
コード例 #35
0
ファイル: test_userauth.py プロジェクト: gitPff/twisted
 def test_tooManyAttempts(self):
     """
     Test that the server disconnects if the client fails authentication
     too many times.
     """
     packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
                        NS(b'bar')])
     self.authServer.clock = task.Clock()
     for i in range(21):
         d = self.authServer.ssh_USERAUTH_REQUEST(packet)
         self.authServer.clock.advance(2)
     def check(ignored):
         self.assertEqual(self.authServer.transport.packets[-1],
             (transport.MSG_DISCONNECT,
             b'\x00' * 3 +
             chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
             NS(b"too many bad auths") + NS(b'')))
     return d.addCallback(check)
コード例 #36
0
 def test_tooManyAttempts(self):
     """
     Test that the server disconnects if the client fails authentication
     too many times.
     """
     packet = b''.join([NS(b'foo'), NS(b'none'), NS(b'password'), chr(0),
                        NS(b'bar')])
     self.authServer.clock = task.Clock()
     for i in range(21):
         d = self.authServer.ssh_USERAUTH_REQUEST(packet)
         self.authServer.clock.advance(2)
     def check(ignored):
         self.assertEqual(self.authServer.transport.packets[-1],
             (transport.MSG_DISCONNECT,
             b'\x00' * 3 +
             chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
             NS(b"too many bad auths") + NS(b'')))
     return d.addCallback(check)
コード例 #37
0
    def sendRequest(self, channel, requestType, data, wantReply=0):
        """
        Send a request to a channel.

        @type channel:      subclass of C{SSHChannel}
        @type requestType:  L{bytes}
        @type data:         L{bytes}
        @type wantReply:    L{bool}
        @rtype              C{Deferred}/L{None}
        """
        if channel.localClosed:
            return
        log.msg('sending request %r' % (requestType))
        self.transport.sendPacket(
            MSG_CHANNEL_REQUEST,
            struct.pack('>L', self.channelsToRemoteChannel[channel]) +
            common.NS(requestType) + chr(wantReply) + data)
        if wantReply:
            d = defer.Deferred()
            self.deferreds.setdefault(channel.id, []).append(d)
            return d
コード例 #38
0
    def sendRequest(self, channel, requestType, data, wantReply=0):
        """
        Send a request to a channel.

        @type channel:      subclass of C{SSHChannel}
        @type requestType:  L{bytes}
        @type data:         L{bytes}
        @type wantReply:    L{bool}
        @rtype              C{Deferred}/L{None}
        """
        if channel.localClosed:
            return
        log.msg('sending request %r' % (requestType))
        self.transport.sendPacket(MSG_CHANNEL_REQUEST, struct.pack('>L',
                                    self.channelsToRemoteChannel[channel])
                                  + common.NS(requestType)+chr(wantReply)
                                  + data)
        if wantReply:
            d = defer.Deferred()
            self.deferreds.setdefault(channel.id, []).append(d)
            return d
コード例 #39
0
ファイル: telnet.py プロジェクト: Architektor/PySnip
import warnings
warnings.warn(
    "As of Twisted 2.1, twisted.protocols.telnet is deprecated.  "
    "See twisted.conch.telnet for the current, supported API.",
    DeprecationWarning,
    stacklevel=2)

from io import BytesIO

from twisted import copyright
from twisted.internet import protocol
from twisted.python.compat import networkString, iterbytes, _bytesChr as chr

# Some utility chars.
ESC =            chr(27) # ESC for doing fanciness
BOLD_MODE_ON =   ESC + b"[1m" # turn bold on
BOLD_MODE_OFF=   ESC + b"[m"  # no char attributes


# Characters gleaned from the various (and conflicting) RFCs.  Not all of these are correct.

NULL =            chr(0)  # No operation.
LF   =           chr(10)  # Moves the printer to the
                          # next print line, keeping the
                          # same horizontal position.
CR =             chr(13)  # Moves the printer to the left
                          # margin of the current line.
BEL =             chr(7)  # Produces an audible or
                          # visible signal (which does
                          # NOT move the print head).
コード例 #40
0
ファイル: banana.py プロジェクト: 18636800170/videoWebsie
    @type st: L{bytes}

    @return: The integer value extracted from the byte string.
    @rtype: L{int} or L{long}
    """
    e = 1
    i = 0
    for char in iterbytes(st):
        n = ord(char)
        i += (n * e)
        e <<= 7
    return i


# delimiter characters.
LIST = chr(0x80)
INT = chr(0x81)
STRING = chr(0x82)
NEG = chr(0x83)
FLOAT = chr(0x84)
# "optional" -- these might be refused by a low-level implementation.
LONGINT = chr(0x85)
LONGNEG = chr(0x86)
# really optional; this is part of the 'pb' vocabulary
VOCAB = chr(0x87)

HIGH_BIT_SET = chr(0x80)


def setPrefixLimit(limit):
    """
コード例 #41
0
 def check(ignored):
     self.assertEqual(
         self.authServer.transport.packets[-1],
         (transport.MSG_DISCONNECT, b'\x00' * 3 +
          chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
          NS(b"too many bad auths") + NS(b'')))
コード例 #42
0
MSG_REQUEST_FAILURE = 82
MSG_CHANNEL_OPEN = 90
MSG_CHANNEL_OPEN_CONFIRMATION = 91
MSG_CHANNEL_OPEN_FAILURE = 92
MSG_CHANNEL_WINDOW_ADJUST = 93
MSG_CHANNEL_DATA = 94
MSG_CHANNEL_EXTENDED_DATA = 95
MSG_CHANNEL_EOF = 96
MSG_CHANNEL_CLOSE = 97
MSG_CHANNEL_REQUEST = 98
MSG_CHANNEL_SUCCESS = 99
MSG_CHANNEL_FAILURE = 100

OPEN_ADMINISTRATIVELY_PROHIBITED = 1
OPEN_CONNECT_FAILED = 2
OPEN_UNKNOWN_CHANNEL_TYPE = 3
OPEN_RESOURCE_SHORTAGE = 4

EXTENDED_DATA_STDERR = 1

messages = {}
for name, value in locals().copy().items():
    if name[:4] == 'MSG_':
        messages[value] = name # doesn't handle doubles

import string
alphanums = networkString(string.ascii_letters + string.digits)
TRANSLATE_TABLE = b''.join([chr(i) in alphanums and chr(i) or b'_'
    for i in range(256)])
SSHConnection.protocolMessages = messages
コード例 #43
0
def horizontalLine(terminal, y, left, right):
    terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
    terminal.cursorPosition(left, y)
    terminal.write(chr(0o161) * (right - left))
    terminal.selectCharacterSet(insults.CS_US, insults.G0)
コード例 #44
0
def verticalLine(terminal, x, top, bottom):
    terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
    for n in range(top, bottom):
        terminal.cursorPosition(x, n)
        terminal.write(chr(0o170))
    terminal.selectCharacterSet(insults.CS_US, insults.G0)
コード例 #45
0
ファイル: telnet.py プロジェクト: Architektor/PySnip
Telnet protocol implementation.

@author: Jean-Paul Calderone
"""

from __future__ import absolute_import, division

import struct

from zope.interface import implementer

from twisted.internet import protocol, interfaces as iinternet, defer
from twisted.python import log
from twisted.python.compat import _bytesChr as chr, iterbytes

MODE = chr(1)
EDIT = 1
TRAPSIG = 2
MODE_ACK = 4
SOFT_TAB = 8
LIT_ECHO = 16

# Characters gleaned from the various (and conflicting) RFCs.  Not all of these are correct.

NULL =           chr(0)   # No operation.
BEL =            chr(7)   # Produces an audible or
                          # visible signal (which does
                          # NOT move the print head).
BS =             chr(8)   # Moves the print head one
                          # character position towards
                          # the left margin.
コード例 #46
0
import warnings

warnings.warn(
    "As of Twisted 2.1, twisted.protocols.telnet is deprecated.  "
    "See twisted.conch.telnet for the current, supported API.",
    DeprecationWarning,
    stacklevel=2)

from io import BytesIO

from twisted import copyright
from twisted.internet import protocol
from twisted.python.compat import networkString, iterbytes, _bytesChr as chr

# Some utility chars.
ESC = chr(27)  # ESC for doing fanciness
BOLD_MODE_ON = ESC + b"[1m"  # turn bold on
BOLD_MODE_OFF = ESC + b"[m"  # no char attributes

# Characters gleaned from the various (and conflicting) RFCs.  Not all of these are correct.

NULL = chr(0)  # No operation.
LF = chr(10)  # Moves the printer to the
# next print line, keeping the
# same horizontal position.
CR = chr(13)  # Moves the printer to the left
# margin of the current line.
BEL = chr(7)  # Produces an audible or
# visible signal (which does
# NOT move the print head).
BS = chr(8)  # Moves the print head one
コード例 #47
0
MSG_REQUEST_FAILURE = 82
MSG_CHANNEL_OPEN = 90
MSG_CHANNEL_OPEN_CONFIRMATION = 91
MSG_CHANNEL_OPEN_FAILURE = 92
MSG_CHANNEL_WINDOW_ADJUST = 93
MSG_CHANNEL_DATA = 94
MSG_CHANNEL_EXTENDED_DATA = 95
MSG_CHANNEL_EOF = 96
MSG_CHANNEL_CLOSE = 97
MSG_CHANNEL_REQUEST = 98
MSG_CHANNEL_SUCCESS = 99
MSG_CHANNEL_FAILURE = 100

OPEN_ADMINISTRATIVELY_PROHIBITED = 1
OPEN_CONNECT_FAILED = 2
OPEN_UNKNOWN_CHANNEL_TYPE = 3
OPEN_RESOURCE_SHORTAGE = 4

EXTENDED_DATA_STDERR = 1

messages = {}
for name, value in locals().copy().items():
    if name[:4] == 'MSG_':
        messages[value] = name  # doesn't handle doubles

import string
alphanums = networkString(string.ascii_letters + string.digits)
TRANSLATE_TABLE = b''.join(
    [chr(i) in alphanums and chr(i) or b'_' for i in range(256)])
SSHConnection.protocolMessages = messages
コード例 #48
0
ファイル: telnet.py プロジェクト: yuu6/twisted
# See LICENSE for details.
"""
Telnet protocol implementation.

@author: Jean-Paul Calderone
"""

import struct

from zope.interface import implementer

from twisted.internet import protocol, interfaces as iinternet, defer
from twisted.python import log
from twisted.python.compat import _bytesChr as chr, iterbytes

MODE = chr(1)
EDIT = 1
TRAPSIG = 2
MODE_ACK = 4
SOFT_TAB = 8
LIT_ECHO = 16

# Characters gleaned from the various (and conflicting) RFCs. Not all of these
# are correct.

NULL = chr(0)  # No operation.
BEL = chr(7)  # Produces an audible or visible signal (which does NOT move the
# print head).
BS = chr(8)  # Moves the print head one character position towards the left
# margin.
HT = chr(9)  # Moves the printer to the next horizontal tab stop. It remains
コード例 #49
0
ファイル: window.py プロジェクト: JohnDoes95/project_parser
def verticalLine(terminal, x, top, bottom):
    terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
    for n in range(top, bottom):
        terminal.cursorPosition(x, n)
        terminal.write(chr(0o170))
    terminal.selectCharacterSet(insults.CS_US, insults.G0)
コード例 #50
0
ファイル: banana.py プロジェクト: JohnDoes95/project_parser
    @type st: L{bytes}

    @return: The integer value extracted from the byte string.
    @rtype: L{int} or L{long}
    """
    e = 1
    i = 0
    for char in iterbytes(st):
        n = ord(char)
        i += (n * e)
        e <<= 7
    return i


# delimiter characters.
LIST     = chr(0x80)
INT      = chr(0x81)
STRING   = chr(0x82)
NEG      = chr(0x83)
FLOAT    = chr(0x84)
# "optional" -- these might be refused by a low-level implementation.
LONGINT  = chr(0x85)
LONGNEG  = chr(0x86)
# really optional; this is part of the 'pb' vocabulary
VOCAB    = chr(0x87)

HIGH_BIT_SET = chr(0x80)

def setPrefixLimit(limit):
    """
    Set the limit on the prefix length for all Banana connections
コード例 #51
0
 def check(ignored):
     self.assertEqual(self.authServer.transport.packets[-1],
         (transport.MSG_DISCONNECT,
         b'\x00' * 3 +
         chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
         NS(b"too many bad auths") + NS(b'')))
コード例 #52
0
# See LICENSE for details.
"""
Telnet protocol implementation.

@author: Jean-Paul Calderone
"""

import struct

from zope.interface import implementer

from twisted.internet import protocol, interfaces as iinternet, defer
from twisted.python import log
from twisted.python.compat import _bytesChr as chr, iterbytes

MODE = chr(1)
EDIT = 1
TRAPSIG = 2
MODE_ACK = 4
SOFT_TAB = 8
LIT_ECHO = 16

# Characters gleaned from the various (and conflicting) RFCs.  Not all of these are correct.

NULL = chr(0)  # No operation.
BEL = chr(7)  # Produces an audible or
# visible signal (which does
# NOT move the print head).
BS = chr(8)  # Moves the print head one
# character position towards
# the left margin.
コード例 #53
0
ファイル: window.py プロジェクト: JohnDoes95/project_parser
def horizontalLine(terminal, y, left, right):
    terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
    terminal.cursorPosition(left, y)
    terminal.write(chr(0o161) * (right - left))
    terminal.selectCharacterSet(insults.CS_US, insults.G0)