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:])
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:])
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:])
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:])
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
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)
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()
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
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()
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
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))))
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)
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
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
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))))
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
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)
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())
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
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)
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)
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)
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)
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)
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)
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)
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
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
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).
@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): """
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'')))
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
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)
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)
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.
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
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
# 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
@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
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'')))
# 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.