File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/conch.tar
Back
checkers.py 0000644 00000045736 15027667726 0006746 0 ustar 00 # -*- test-case-name: twisted.conch.test.test_checkers -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Provide L{ICredentialsChecker} implementations to be used in Conch protocols. """ import binascii import errno import sys from base64 import decodebytes from typing import BinaryIO, Callable, Iterator try: import pwd as _pwd except ImportError: pwd = None else: pwd = _pwd try: import spwd as _spwd except ImportError: spwd = None else: spwd = _spwd from zope.interface import Interface, implementer, providedBy from incremental import Version from twisted.conch import error from twisted.conch.ssh import keys from twisted.cred.checkers import ICredentialsChecker from twisted.cred.credentials import ISSHPrivateKey, IUsernamePassword from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials from twisted.internet import defer from twisted.logger import Logger from twisted.plugins.cred_unix import verifyCryptedPassword from twisted.python import failure, reflect from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.filepath import FilePath from twisted.python.util import runAsEffectiveUser _log = Logger() def _pwdGetByName(username): """ Look up a user in the /etc/passwd database using the pwd module. If the pwd module is not available, return None. @param username: the username of the user to return the passwd database information for. @type username: L{str} """ if pwd is None: return None return pwd.getpwnam(username) def _shadowGetByName(username): """ Look up a user in the /etc/shadow database using the spwd module. If it is not available, return L{None}. @param username: the username of the user to return the shadow database information for. @type username: L{str} """ if spwd is not None: f = spwd.getspnam else: return None return runAsEffectiveUser(0, 0, f, username) @implementer(ICredentialsChecker) class UNIXPasswordDatabase: """ A checker which validates users out of the UNIX password databases, or databases of a compatible format. @ivar _getByNameFunctions: a C{list} of functions which are called in order to valid a user. The default value is such that the C{/etc/passwd} database will be tried first, followed by the C{/etc/shadow} database. """ credentialInterfaces = (IUsernamePassword,) def __init__(self, getByNameFunctions=None): if getByNameFunctions is None: getByNameFunctions = [_pwdGetByName, _shadowGetByName] self._getByNameFunctions = getByNameFunctions def requestAvatarId(self, credentials): # We get bytes, but the Py3 pwd module uses str. So attempt to decode # it using the same method that CPython does for the file on disk. username = credentials.username.decode(sys.getfilesystemencoding()) password = credentials.password.decode(sys.getfilesystemencoding()) for func in self._getByNameFunctions: try: pwnam = func(username) except KeyError: return defer.fail(UnauthorizedLogin("invalid username")) else: if pwnam is not None: crypted = pwnam[1] if crypted == "": continue if verifyCryptedPassword(crypted, password): return defer.succeed(credentials.username) # fallback return defer.fail(UnauthorizedLogin("unable to verify password")) @implementer(ICredentialsChecker) class SSHPublicKeyDatabase: """ Checker that authenticates SSH public keys, based on public keys listed in authorized_keys and authorized_keys2 files in user .ssh/ directories. """ credentialInterfaces = (ISSHPrivateKey,) _userdb = pwd def requestAvatarId(self, credentials): d = defer.maybeDeferred(self.checkKey, credentials) d.addCallback(self._cbRequestAvatarId, credentials) d.addErrback(self._ebRequestAvatarId) return d def _cbRequestAvatarId(self, validKey, credentials): """ Check whether the credentials themselves are valid, now that we know if the key matches the user. @param validKey: A boolean indicating whether or not the public key matches a key in the user's authorized_keys file. @param credentials: The credentials offered by the user. @type credentials: L{ISSHPrivateKey} provider @raise UnauthorizedLogin: (as a failure) if the key does not match the user in C{credentials}. Also raised if the user provides an invalid signature. @raise ValidPublicKey: (as a failure) if the key matches the user but the credentials do not include a signature. See L{error.ValidPublicKey} for more information. @return: The user's username, if authentication was successful. """ if not validKey: return failure.Failure(UnauthorizedLogin("invalid key")) if not credentials.signature: return failure.Failure(error.ValidPublicKey()) else: try: pubKey = keys.Key.fromString(credentials.blob) if pubKey.verify(credentials.signature, credentials.sigData): return credentials.username except Exception: # any error should be treated as a failed login _log.failure("Error while verifying key") return failure.Failure(UnauthorizedLogin("error while verifying key")) return failure.Failure(UnauthorizedLogin("unable to verify key")) def getAuthorizedKeysFiles(self, credentials): """ Return a list of L{FilePath} instances for I{authorized_keys} files which might contain information about authorized keys for the given credentials. On OpenSSH servers, the default location of the file containing the list of authorized public keys is U{$HOME/.ssh/authorized_keys<http://www.openbsd.org/cgi-bin/man.cgi?query=sshd_config>}. I{$HOME/.ssh/authorized_keys2} is also returned, though it has been U{deprecated by OpenSSH since 2001<http://marc.info/?m=100508718416162>}. @return: A list of L{FilePath} instances to files with the authorized keys. """ pwent = self._userdb.getpwnam(credentials.username) root = FilePath(pwent.pw_dir).child(".ssh") files = ["authorized_keys", "authorized_keys2"] return [root.child(f) for f in files] def checkKey(self, credentials): """ Retrieve files containing authorized keys and check against user credentials. """ ouid, ogid = self._userdb.getpwnam(credentials.username)[2:4] for filepath in self.getAuthorizedKeysFiles(credentials): if not filepath.exists(): continue try: lines = filepath.open() except OSError as e: if e.errno == errno.EACCES: lines = runAsEffectiveUser(ouid, ogid, filepath.open) else: raise with lines: for l in lines: l2 = l.split() if len(l2) < 2: continue try: if decodebytes(l2[1]) == credentials.blob: return True except binascii.Error: continue return False def _ebRequestAvatarId(self, f): if not f.check(UnauthorizedLogin): _log.error( "Unauthorized login due to internal error: {error}", error=f.value ) return failure.Failure(UnauthorizedLogin("unable to get avatar id")) return f @implementer(ICredentialsChecker) class SSHProtocolChecker: """ SSHProtocolChecker is a checker that requires multiple authentications to succeed. To add a checker, call my registerChecker method with the checker and the interface. After each successful authenticate, I call my areDone method with the avatar id. To get a list of the successful credentials for an avatar id, use C{SSHProcotolChecker.successfulCredentials[avatarId]}. If L{areDone} returns True, the authentication has succeeded. """ def __init__(self): self.checkers = {} self.successfulCredentials = {} @property def credentialInterfaces(self): return list(self.checkers.keys()) def registerChecker(self, checker, *credentialInterfaces): if not credentialInterfaces: credentialInterfaces = checker.credentialInterfaces for credentialInterface in credentialInterfaces: self.checkers[credentialInterface] = checker def requestAvatarId(self, credentials): """ Part of the L{ICredentialsChecker} interface. Called by a portal with some credentials to check if they'll authenticate a user. We check the interfaces that the credentials provide against our list of acceptable checkers. If one of them matches, we ask that checker to verify the credentials. If they're valid, we call our L{_cbGoodAuthentication} method to continue. @param credentials: the credentials the L{Portal} wants us to verify """ ifac = providedBy(credentials) for i in ifac: c = self.checkers.get(i) if c is not None: d = defer.maybeDeferred(c.requestAvatarId, credentials) return d.addCallback(self._cbGoodAuthentication, credentials) return defer.fail( UnhandledCredentials( "No checker for %s" % ", ".join(map(reflect.qual, ifac)) ) ) def _cbGoodAuthentication(self, avatarId, credentials): """ Called if a checker has verified the credentials. We call our L{areDone} method to see if the whole of the successful authentications are enough. If they are, we return the avatar ID returned by the first checker. """ if avatarId not in self.successfulCredentials: self.successfulCredentials[avatarId] = [] self.successfulCredentials[avatarId].append(credentials) if self.areDone(avatarId): del self.successfulCredentials[avatarId] return avatarId else: raise error.NotEnoughAuthentication() def areDone(self, avatarId): """ Override to determine if the authentication is finished for a given avatarId. @param avatarId: the avatar returned by the first checker. For this checker to function correctly, all the checkers must return the same avatar ID. """ return True deprecatedModuleAttribute( Version("Twisted", 15, 0, 0), ( "Please use twisted.conch.checkers.SSHPublicKeyChecker, " "initialized with an instance of " "twisted.conch.checkers.UNIXAuthorizedKeysFiles instead." ), __name__, "SSHPublicKeyDatabase", ) class IAuthorizedKeysDB(Interface): """ An object that provides valid authorized ssh keys mapped to usernames. @since: 15.0 """ def getAuthorizedKeys(avatarId): """ Gets an iterable of authorized keys that are valid for the given C{avatarId}. @param avatarId: the ID of the avatar @type avatarId: valid return value of L{twisted.cred.checkers.ICredentialsChecker.requestAvatarId} @return: an iterable of L{twisted.conch.ssh.keys.Key} """ def readAuthorizedKeyFile( fileobj: BinaryIO, parseKey: Callable[[bytes], keys.Key] = keys.Key.fromString ) -> Iterator[keys.Key]: """ Reads keys from an authorized keys file. Any non-comment line that cannot be parsed as a key will be ignored, although that particular line will be logged. @param fileobj: something from which to read lines which can be parsed as keys @param parseKey: a callable that takes bytes and returns a L{twisted.conch.ssh.keys.Key}, mainly to be used for testing. The default is L{twisted.conch.ssh.keys.Key.fromString}. @return: an iterable of L{twisted.conch.ssh.keys.Key} @since: 15.0 """ for line in fileobj: line = line.strip() if line and not line.startswith(b"#"): # for comments try: yield parseKey(line) except keys.BadKeyError as e: _log.error( "Unable to parse line {line!r} as a key: {error!s}", line=line, error=e, ) def _keysFromFilepaths(filepaths, parseKey): """ Helper function that turns an iterable of filepaths into a generator of keys. If any file cannot be read, a message is logged but it is otherwise ignored. @param filepaths: iterable of L{twisted.python.filepath.FilePath}. @type filepaths: iterable @param parseKey: a callable that takes a string and returns a L{twisted.conch.ssh.keys.Key} @type parseKey: L{callable} @return: generator of L{twisted.conch.ssh.keys.Key} @rtype: generator @since: 15.0 """ for fp in filepaths: if fp.exists(): try: with fp.open() as f: yield from readAuthorizedKeyFile(f, parseKey) except OSError as e: _log.error("Unable to read {path!r}: {error!s}", path=fp.path, error=e) @implementer(IAuthorizedKeysDB) class InMemorySSHKeyDB: """ Object that provides SSH public keys based on a dictionary of usernames mapped to L{twisted.conch.ssh.keys.Key}s. @since: 15.0 """ def __init__(self, mapping): """ Initializes a new L{InMemorySSHKeyDB}. @param mapping: mapping of usernames to iterables of L{twisted.conch.ssh.keys.Key}s @type mapping: L{dict} """ self._mapping = mapping def getAuthorizedKeys(self, username): return self._mapping.get(username, []) @implementer(IAuthorizedKeysDB) class UNIXAuthorizedKeysFiles: """ Object that provides SSH public keys based on public keys listed in authorized_keys and authorized_keys2 files in UNIX user .ssh/ directories. If any of the files cannot be read, a message is logged but that file is otherwise ignored. @since: 15.0 """ def __init__(self, userdb=None, parseKey=keys.Key.fromString): """ Initializes a new L{UNIXAuthorizedKeysFiles}. @param userdb: access to the Unix user account and password database (default is the Python module L{pwd}) @type userdb: L{pwd}-like object @param parseKey: a callable that takes a string and returns a L{twisted.conch.ssh.keys.Key}, mainly to be used for testing. The default is L{twisted.conch.ssh.keys.Key.fromString}. @type parseKey: L{callable} """ self._userdb = userdb self._parseKey = parseKey if userdb is None: self._userdb = pwd def getAuthorizedKeys(self, username): try: passwd = self._userdb.getpwnam(username) except KeyError: return () root = FilePath(passwd.pw_dir).child(".ssh") files = ["authorized_keys", "authorized_keys2"] return _keysFromFilepaths((root.child(f) for f in files), self._parseKey) @implementer(ICredentialsChecker) class SSHPublicKeyChecker: """ Checker that authenticates SSH public keys, based on public keys listed in authorized_keys and authorized_keys2 files in user .ssh/ directories. Initializing this checker with a L{UNIXAuthorizedKeysFiles} should be used instead of L{twisted.conch.checkers.SSHPublicKeyDatabase}. @since: 15.0 """ credentialInterfaces = (ISSHPrivateKey,) def __init__(self, keydb): """ Initializes a L{SSHPublicKeyChecker}. @param keydb: a provider of L{IAuthorizedKeysDB} @type keydb: L{IAuthorizedKeysDB} provider """ self._keydb = keydb def requestAvatarId(self, credentials): d = defer.maybeDeferred(self._sanityCheckKey, credentials) d.addCallback(self._checkKey, credentials) d.addCallback(self._verifyKey, credentials) return d def _sanityCheckKey(self, credentials): """ Checks whether the provided credentials are a valid SSH key with a signature (does not actually verify the signature). @param credentials: the credentials offered by the user @type credentials: L{ISSHPrivateKey} provider @raise ValidPublicKey: the credentials do not include a signature. See L{error.ValidPublicKey} for more information. @raise BadKeyError: The key included with the credentials is not recognized as a key. @return: the key in the credentials @rtype: L{twisted.conch.ssh.keys.Key} """ if not credentials.signature: raise error.ValidPublicKey() return keys.Key.fromString(credentials.blob) def _checkKey(self, pubKey, credentials): """ Checks the public key against all authorized keys (if any) for the user. @param pubKey: the key in the credentials (just to prevent it from having to be calculated again) @type pubKey: @param credentials: the credentials offered by the user @type credentials: L{ISSHPrivateKey} provider @raise UnauthorizedLogin: If the key is not authorized, or if there was any error obtaining a list of authorized keys for the user. @return: C{pubKey} if the key is authorized @rtype: L{twisted.conch.ssh.keys.Key} """ if any( key == pubKey for key in self._keydb.getAuthorizedKeys(credentials.username) ): return pubKey raise UnauthorizedLogin("Key not authorized") def _verifyKey(self, pubKey, credentials): """ Checks whether the credentials themselves are valid, now that we know if the key matches the user. @param pubKey: the key in the credentials (just to prevent it from having to be calculated again) @type pubKey: L{twisted.conch.ssh.keys.Key} @param credentials: the credentials offered by the user @type credentials: L{ISSHPrivateKey} provider @raise UnauthorizedLogin: If the key signature is invalid or there was any error verifying the signature. @return: The user's username, if authentication was successful @rtype: L{bytes} """ try: if pubKey.verify(credentials.signature, credentials.sigData): return credentials.username except Exception as e: # Any error should be treated as a failed login raise UnauthorizedLogin("Error while verifying key") from e raise UnauthorizedLogin("Key signature invalid.") telnet.py 0000644 00000112246 15027667726 0006441 0 ustar 00 # -*- test-case-name: twisted.conch.test.test_telnet -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Telnet protocol implementation. @author: Jean-Paul Calderone """ import struct from zope.interface import implementer from twisted.internet import defer, interfaces as iinternet, protocol from twisted.logger import Logger from twisted.python.compat import iterbytes def _chr(i: int) -> bytes: """Create a byte sequence of length 1. U{RFC 854<https://tools.ietf.org/html/rfc854>} specifies codes in decimal, but Python can only handle L{bytes} literals in octal or hexadecimal. This helper function bridges that gap. @param i: The value of the only byte in the sequence. """ return bytes((i,)) 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 # unspecified how either party determines or establishes where such tab stops # are located. LF = _chr(10) # Moves the printer to the next print line, keeping the same # horizontal position. VT = _chr(11) # Moves the printer to the next vertical tab stop. It remains # unspecified how either party determines or establishes where such tab stops # are located. FF = _chr(12) # Moves the printer to the top of the next page, keeping the same # horizontal position. CR = _chr(13) # Moves the printer to the left margin of the current line. ECHO = _chr(1) # User-to-Server: Asks the server to send Echos of the # transmitted data. SGA = _chr(3) # Suppress Go Ahead. Go Ahead is silly and most modern servers # should suppress it. NAWS = _chr(31) # Negotiate About Window Size. Indicate that information about # the size of the terminal can be communicated. LINEMODE = _chr(34) # Allow line buffering to be negotiated about. EOR = _chr(239) # End of Record (RFC 885) SE = _chr(240) # End of subnegotiation parameters. NOP = _chr(241) # No operation. DM = _chr(242) # "Data Mark": The data stream portion of a Synch. This should # always be accompanied by a TCP Urgent notification. BRK = _chr(243) # NVT character Break. IP = _chr(244) # The function Interrupt Process. AO = _chr(245) # The function Abort Output AYT = _chr(246) # The function Are You There. EC = _chr(247) # The function Erase Character. EL = _chr(248) # The function Erase Line GA = _chr(249) # The Go Ahead signal. SB = _chr(250) # Indicates that what follows is subnegotiation of the indicated # option. WILL = _chr(251) # Indicates the desire to begin performing, or confirmation # that you are now performing, the indicated option. WONT = _chr(252) # Indicates the refusal to perform, or continue performing, # the indicated option. DO = _chr(253) # Indicates the request that the other party perform, or # confirmation that you are expecting the other party to perform, the indicated # option. DONT = _chr(254) # Indicates the demand that the other party stop performing, # or confirmation that you are no longer expecting the other party to perform, # the indicated option. IAC = _chr(255) # Data Byte 255. Introduces a telnet command. LINEMODE_MODE = _chr(1) LINEMODE_EDIT = _chr(1) LINEMODE_TRAPSIG = _chr(2) LINEMODE_MODE_ACK = _chr(4) LINEMODE_SOFT_TAB = _chr(8) LINEMODE_LIT_ECHO = _chr(16) LINEMODE_FORWARDMASK = _chr(2) LINEMODE_SLC = _chr(3) LINEMODE_SLC_SYNCH = _chr(1) LINEMODE_SLC_BRK = _chr(2) LINEMODE_SLC_IP = _chr(3) LINEMODE_SLC_AO = _chr(4) LINEMODE_SLC_AYT = _chr(5) LINEMODE_SLC_EOR = _chr(6) LINEMODE_SLC_ABORT = _chr(7) LINEMODE_SLC_EOF = _chr(8) LINEMODE_SLC_SUSP = _chr(9) LINEMODE_SLC_EC = _chr(10) LINEMODE_SLC_EL = _chr(11) LINEMODE_SLC_EW = _chr(12) LINEMODE_SLC_RP = _chr(13) LINEMODE_SLC_LNEXT = _chr(14) LINEMODE_SLC_XON = _chr(15) LINEMODE_SLC_XOFF = _chr(16) LINEMODE_SLC_FORW1 = _chr(17) LINEMODE_SLC_FORW2 = _chr(18) LINEMODE_SLC_MCL = _chr(19) LINEMODE_SLC_MCR = _chr(20) LINEMODE_SLC_MCWL = _chr(21) LINEMODE_SLC_MCWR = _chr(22) LINEMODE_SLC_MCBOL = _chr(23) LINEMODE_SLC_MCEOL = _chr(24) LINEMODE_SLC_INSRT = _chr(25) LINEMODE_SLC_OVER = _chr(26) LINEMODE_SLC_ECR = _chr(27) LINEMODE_SLC_EWR = _chr(28) LINEMODE_SLC_EBOL = _chr(29) LINEMODE_SLC_EEOL = _chr(30) LINEMODE_SLC_DEFAULT = _chr(3) LINEMODE_SLC_VALUE = _chr(2) LINEMODE_SLC_CANTCHANGE = _chr(1) LINEMODE_SLC_NOSUPPORT = _chr(0) LINEMODE_SLC_LEVELBITS = _chr(3) LINEMODE_SLC_ACK = _chr(128) LINEMODE_SLC_FLUSHIN = _chr(64) LINEMODE_SLC_FLUSHOUT = _chr(32) LINEMODE_EOF = _chr(236) LINEMODE_SUSP = _chr(237) LINEMODE_ABORT = _chr(238) class ITelnetProtocol(iinternet.IProtocol): def unhandledCommand(command, argument): """ A command was received but not understood. @param command: the command received. @type command: L{str}, a single character. @param argument: the argument to the received command. @type argument: L{str}, a single character, or None if the command that was unhandled does not provide an argument. """ def unhandledSubnegotiation(command, data): """ A subnegotiation command was received but not understood. @param command: the command being subnegotiated. That is, the first byte after the SB command. @type command: L{str}, a single character. @param data: all other bytes of the subneogation. That is, all but the first bytes between SB and SE, with IAC un-escaping applied. @type data: L{bytes}, each a single character """ def enableLocal(option): """ Enable the given option locally. This should enable the given option on this side of the telnet connection and return True. If False is returned, the option will be treated as still disabled and the peer will be notified. @param option: the option to be enabled. @type option: L{bytes}, a single character. """ def enableRemote(option): """ Indicate whether the peer should be allowed to enable this option. Returns True if the peer should be allowed to enable this option, False otherwise. @param option: the option to be enabled. @type option: L{bytes}, a single character. """ def disableLocal(option): """ Disable the given option locally. Unlike enableLocal, this method cannot fail. The option must be disabled. @param option: the option to be disabled. @type option: L{bytes}, a single character. """ def disableRemote(option): """ Indicate that the peer has disabled this option. @param option: the option to be disabled. @type option: L{bytes}, a single character. """ class ITelnetTransport(iinternet.ITransport): def do(option): """ Indicate a desire for the peer to begin performing the given option. Returns a Deferred that fires with True when the peer begins performing the option, or fails with L{OptionRefused} when the peer refuses to perform it. If the peer is already performing the given option, the Deferred will fail with L{AlreadyEnabled}. If a negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be enabled. """ def dont(option): """ Indicate a desire for the peer to cease performing the given option. Returns a Deferred that fires with True when the peer ceases performing the option. If the peer is not performing the given option, the Deferred will fail with L{AlreadyDisabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be disabled. """ def will(option): """ Indicate our willingness to begin performing this option locally. Returns a Deferred that fires with True when the peer agrees to allow us to begin performing this option, or fails with L{OptionRefused} if the peer refuses to allow us to begin performing it. If the option is already enabled locally, the Deferred will fail with L{AlreadyEnabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be enabled. """ def wont(option): """ Indicate that we will stop performing the given option. Returns a Deferred that fires with True when the peer acknowledges we have stopped performing this option. If the option is already disabled locally, the Deferred will fail with L{AlreadyDisabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be disabled. """ def requestNegotiation(about, data): """ Send a subnegotiation request. @param about: A byte indicating the feature being negotiated. @param data: Any number of L{bytes} containing specific information about the negotiation being requested. No values in this string need to be escaped, as this function will escape any value which requires it. """ class TelnetError(Exception): pass class NegotiationError(TelnetError): def __str__(self) -> str: return ( self.__class__.__module__ + "." + self.__class__.__name__ + ":" + repr(self.args[0]) ) class OptionRefused(NegotiationError): pass class AlreadyEnabled(NegotiationError): pass class AlreadyDisabled(NegotiationError): pass class AlreadyNegotiating(NegotiationError): pass @implementer(ITelnetProtocol) class TelnetProtocol(protocol.Protocol): _log = Logger() def unhandledCommand(self, command, argument): pass def unhandledSubnegotiation(self, command, data): pass def enableLocal(self, option): pass def enableRemote(self, option): pass def disableLocal(self, option): pass def disableRemote(self, option): pass class Telnet(protocol.Protocol): """ @ivar commandMap: A mapping of bytes to callables. When a telnet command is received, the command byte (the first byte after IAC) is looked up in this dictionary. If a callable is found, it is invoked with the argument of the command, or None if the command takes no argument. Values should be added to this dictionary if commands wish to be handled. By default, only WILL, WONT, DO, and DONT are handled. These should not be overridden, as this class handles them correctly and provides an API for interacting with them. @ivar negotiationMap: A mapping of bytes to callables. When a subnegotiation command is received, the command byte (the first byte after SB) is looked up in this dictionary. If a callable is found, it is invoked with the argument of the subnegotiation. Values should be added to this dictionary if subnegotiations are to be handled. By default, no values are handled. @ivar options: A mapping of option bytes to their current state. This state is likely of little use to user code. Changes should not be made to it. @ivar state: A string indicating the current parse state. It can take on the values "data", "escaped", "command", "newline", "subnegotiation", and "subnegotiation-escaped". Changes should not be made to it. @ivar transport: This protocol's transport object. """ # One of a lot of things state = "data" def __init__(self): self.options = {} self.negotiationMap = {} self.commandMap = { WILL: self.telnet_WILL, WONT: self.telnet_WONT, DO: self.telnet_DO, DONT: self.telnet_DONT, } def _write(self, data): self.transport.write(data) class _OptionState: """ Represents the state of an option on both sides of a telnet connection. @ivar us: The state of the option on this side of the connection. @ivar him: The state of the option on the other side of the connection. """ class _Perspective: """ Represents the state of an option on side of the telnet connection. Some options can be enabled on a particular side of the connection (RFC 1073 for example: only the client can have NAWS enabled). Other options can be enabled on either or both sides (such as RFC 1372: each side can have its own flow control state). @ivar state: C{'yes'} or C{'no'} indicating whether or not this option is enabled on one side of the connection. @ivar negotiating: A boolean tracking whether negotiation about this option is in progress. @ivar onResult: When negotiation about this option has been initiated by this side of the connection, a L{Deferred} which will fire with the result of the negotiation. L{None} at other times. """ state = "no" negotiating = False onResult = None def __str__(self) -> str: return self.state + ("*" * self.negotiating) def __init__(self): self.us = self._Perspective() self.him = self._Perspective() def __repr__(self) -> str: return f"<_OptionState us={self.us} him={self.him}>" def getOptionState(self, opt): return self.options.setdefault(opt, self._OptionState()) def _do(self, option): self._write(IAC + DO + option) def _dont(self, option): self._write(IAC + DONT + option) def _will(self, option): self._write(IAC + WILL + option) def _wont(self, option): self._write(IAC + WONT + option) def will(self, option): """ Indicate our willingness to enable an option. """ s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.us.state == "yes": return defer.fail(AlreadyEnabled(option)) else: s.us.negotiating = True s.us.onResult = d = defer.Deferred() self._will(option) return d def wont(self, option): """ Indicate we are not willing to enable an option. """ s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.us.state == "no": return defer.fail(AlreadyDisabled(option)) else: s.us.negotiating = True s.us.onResult = d = defer.Deferred() self._wont(option) return d def do(self, option): s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.him.state == "yes": return defer.fail(AlreadyEnabled(option)) else: s.him.negotiating = True s.him.onResult = d = defer.Deferred() self._do(option) return d def dont(self, option): s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.him.state == "no": return defer.fail(AlreadyDisabled(option)) else: s.him.negotiating = True s.him.onResult = d = defer.Deferred() self._dont(option) return d def requestNegotiation(self, about, data): """ Send a negotiation message for the option C{about} with C{data} as the payload. @param data: the payload @type data: L{bytes} @see: L{ITelnetTransport.requestNegotiation} """ data = data.replace(IAC, IAC * 2) self._write(IAC + SB + about + data + IAC + SE) def dataReceived(self, data): appDataBuffer = [] for b in iterbytes(data): if self.state == "data": if b == IAC: self.state = "escaped" elif b == b"\r": self.state = "newline" else: appDataBuffer.append(b) elif self.state == "escaped": if b == IAC: appDataBuffer.append(b) self.state = "data" elif b == SB: self.state = "subnegotiation" self.commands = [] elif b in (EOR, NOP, DM, BRK, IP, AO, AYT, EC, EL, GA): self.state = "data" if appDataBuffer: self.applicationDataReceived(b"".join(appDataBuffer)) del appDataBuffer[:] self.commandReceived(b, None) elif b in (WILL, WONT, DO, DONT): self.state = "command" self.command = b else: raise ValueError("Stumped", b) elif self.state == "command": self.state = "data" command = self.command del self.command if appDataBuffer: self.applicationDataReceived(b"".join(appDataBuffer)) del appDataBuffer[:] self.commandReceived(command, b) elif self.state == "newline": self.state = "data" if b == b"\n": appDataBuffer.append(b"\n") elif b == b"\0": appDataBuffer.append(b"\r") elif b == IAC: # IAC isn't really allowed after \r, according to the # RFC, but handling it this way is less surprising than # delivering the IAC to the app as application data. # The purpose of the restriction is to allow terminals # to unambiguously interpret the behavior of the CR # after reading only one more byte. CR LF is supposed # to mean one thing (cursor to next line, first column), # CR NUL another (cursor to first column). Absent the # NUL, it still makes sense to interpret this as CR and # then apply all the usual interpretation to the IAC. appDataBuffer.append(b"\r") self.state = "escaped" else: appDataBuffer.append(b"\r" + b) elif self.state == "subnegotiation": if b == IAC: self.state = "subnegotiation-escaped" else: self.commands.append(b) elif self.state == "subnegotiation-escaped": if b == SE: self.state = "data" commands = self.commands del self.commands if appDataBuffer: self.applicationDataReceived(b"".join(appDataBuffer)) del appDataBuffer[:] self.negotiate(commands) else: self.state = "subnegotiation" self.commands.append(b) else: raise ValueError("How'd you do this?") if appDataBuffer: self.applicationDataReceived(b"".join(appDataBuffer)) def connectionLost(self, reason): for state in self.options.values(): if state.us.onResult is not None: d = state.us.onResult state.us.onResult = None d.errback(reason) if state.him.onResult is not None: d = state.him.onResult state.him.onResult = None d.errback(reason) def applicationDataReceived(self, data): """ Called with application-level data. """ def unhandledCommand(self, command, argument): """ Called for commands for which no handler is installed. """ def commandReceived(self, command, argument): cmdFunc = self.commandMap.get(command) if cmdFunc is None: self.unhandledCommand(command, argument) else: cmdFunc(argument) def unhandledSubnegotiation(self, command, data): """ Called for subnegotiations for which no handler is installed. """ def negotiate(self, data): command, data = data[0], data[1:] cmdFunc = self.negotiationMap.get(command) if cmdFunc is None: self.unhandledSubnegotiation(command, data) else: cmdFunc(data) def telnet_WILL(self, option): s = self.getOptionState(option) self.willMap[s.him.state, s.him.negotiating](self, s, option) def will_no_false(self, state, option): # He is unilaterally offering to enable an option. if self.enableRemote(option): state.him.state = "yes" self._do(option) else: self._dont(option) def will_no_true(self, state, option): # Peer agreed to enable an option in response to our request. state.him.state = "yes" state.him.negotiating = False d = state.him.onResult state.him.onResult = None d.callback(True) assert self.enableRemote( option ), "enableRemote must return True in this context (for option {!r})".format( option ) def will_yes_false(self, state, option): # He is unilaterally offering to enable an already-enabled option. # Ignore this. pass def will_yes_true(self, state, option): # This is a bogus state. It is here for completeness. It will # never be entered. assert ( False ), "will_yes_true can never be entered, but was called with {!r}, {!r}".format( state, option, ) willMap = { ("no", False): will_no_false, ("no", True): will_no_true, ("yes", False): will_yes_false, ("yes", True): will_yes_true, } def telnet_WONT(self, option): s = self.getOptionState(option) self.wontMap[s.him.state, s.him.negotiating](self, s, option) def wont_no_false(self, state, option): # He is unilaterally demanding that an already-disabled option be/remain disabled. # Ignore this (although we could record it and refuse subsequent enable attempts # from our side - he can always refuse them again though, so we won't) pass def wont_no_true(self, state, option): # Peer refused to enable an option in response to our request. state.him.negotiating = False d = state.him.onResult state.him.onResult = None d.errback(OptionRefused(option)) def wont_yes_false(self, state, option): # Peer is unilaterally demanding that an option be disabled. state.him.state = "no" self.disableRemote(option) self._dont(option) def wont_yes_true(self, state, option): # Peer agreed to disable an option at our request. state.him.state = "no" state.him.negotiating = False d = state.him.onResult state.him.onResult = None d.callback(True) self.disableRemote(option) wontMap = { ("no", False): wont_no_false, ("no", True): wont_no_true, ("yes", False): wont_yes_false, ("yes", True): wont_yes_true, } def telnet_DO(self, option): s = self.getOptionState(option) self.doMap[s.us.state, s.us.negotiating](self, s, option) def do_no_false(self, state, option): # Peer is unilaterally requesting that we enable an option. if self.enableLocal(option): state.us.state = "yes" self._will(option) else: self._wont(option) def do_no_true(self, state, option): # Peer agreed to allow us to enable an option at our request. state.us.state = "yes" state.us.negotiating = False d = state.us.onResult state.us.onResult = None d.callback(True) self.enableLocal(option) def do_yes_false(self, state, option): # Peer is unilaterally requesting us to enable an already-enabled option. # Ignore this. pass def do_yes_true(self, state, option): # This is a bogus state. It is here for completeness. It will never be # entered. assert ( False ), "do_yes_true can never be entered, but was called with {!r}, {!r}".format( state, option, ) doMap = { ("no", False): do_no_false, ("no", True): do_no_true, ("yes", False): do_yes_false, ("yes", True): do_yes_true, } def telnet_DONT(self, option): s = self.getOptionState(option) self.dontMap[s.us.state, s.us.negotiating](self, s, option) def dont_no_false(self, state, option): # Peer is unilaterally demanding us to disable an already-disabled option. # Ignore this. pass def dont_no_true(self, state, option): # Offered option was refused. Fail the Deferred returned by the # previous will() call. state.us.negotiating = False d = state.us.onResult state.us.onResult = None d.errback(OptionRefused(option)) def dont_yes_false(self, state, option): # Peer is unilaterally demanding we disable an option. state.us.state = "no" self.disableLocal(option) self._wont(option) def dont_yes_true(self, state, option): # Peer acknowledged our notice that we will disable an option. state.us.state = "no" state.us.negotiating = False d = state.us.onResult state.us.onResult = None d.callback(True) self.disableLocal(option) dontMap = { ("no", False): dont_no_false, ("no", True): dont_no_true, ("yes", False): dont_yes_false, ("yes", True): dont_yes_true, } def enableLocal(self, option): """ Reject all attempts to enable options. """ return False def enableRemote(self, option): """ Reject all attempts to enable options. """ return False def disableLocal(self, option): """ Signal a programming error by raising an exception. L{enableLocal} must return true for the given value of C{option} in order for this method to be called. If a subclass of L{Telnet} overrides enableLocal to allow certain options to be enabled, it must also override disableLocal to disable those options. @raise NotImplementedError: Always raised. """ raise NotImplementedError( f"Don't know how to disable local telnet option {option!r}" ) def disableRemote(self, option): """ Signal a programming error by raising an exception. L{enableRemote} must return true for the given value of C{option} in order for this method to be called. If a subclass of L{Telnet} overrides enableRemote to allow certain options to be enabled, it must also override disableRemote tto disable those options. @raise NotImplementedError: Always raised. """ raise NotImplementedError( f"Don't know how to disable remote telnet option {option!r}" ) class ProtocolTransportMixin: def write(self, data): self.transport.write(data.replace(b"\n", b"\r\n")) def writeSequence(self, seq): self.transport.writeSequence(seq) def loseConnection(self): self.transport.loseConnection() def getHost(self): return self.transport.getHost() def getPeer(self): return self.transport.getPeer() class TelnetTransport(Telnet, ProtocolTransportMixin): """ @ivar protocol: An instance of the protocol to which this transport is connected, or None before the connection is established and after it is lost. @ivar protocolFactory: A callable which returns protocol instances which provide L{ITelnetProtocol}. This will be invoked when a connection is established. It is passed *protocolArgs and **protocolKwArgs. @ivar protocolArgs: A tuple of additional arguments to pass to protocolFactory. @ivar protocolKwArgs: A dictionary of additional arguments to pass to protocolFactory. """ disconnecting = False protocolFactory = None protocol = None def __init__(self, protocolFactory=None, *a, **kw): Telnet.__init__(self) if protocolFactory is not None: self.protocolFactory = protocolFactory self.protocolArgs = a self.protocolKwArgs = kw def connectionMade(self): if self.protocolFactory is not None: self.protocol = self.protocolFactory( *self.protocolArgs, **self.protocolKwArgs ) assert ITelnetProtocol.providedBy(self.protocol) try: factory = self.factory except AttributeError: pass else: self.protocol.factory = factory self.protocol.makeConnection(self) def connectionLost(self, reason): Telnet.connectionLost(self, reason) if self.protocol is not None: try: self.protocol.connectionLost(reason) finally: del self.protocol def enableLocal(self, option): return self.protocol.enableLocal(option) def enableRemote(self, option): return self.protocol.enableRemote(option) def disableLocal(self, option): return self.protocol.disableLocal(option) def disableRemote(self, option): return self.protocol.disableRemote(option) def unhandledSubnegotiation(self, command, data): self.protocol.unhandledSubnegotiation(command, data) def unhandledCommand(self, command, argument): self.protocol.unhandledCommand(command, argument) def applicationDataReceived(self, data): self.protocol.dataReceived(data) def write(self, data): ProtocolTransportMixin.write(self, data.replace(b"\xff", b"\xff\xff")) class TelnetBootstrapProtocol(TelnetProtocol, ProtocolTransportMixin): protocol = None def __init__(self, protocolFactory, *args, **kw): self.protocolFactory = protocolFactory self.protocolArgs = args self.protocolKwArgs = kw def connectionMade(self): self.transport.negotiationMap[NAWS] = self.telnet_NAWS self.transport.negotiationMap[LINEMODE] = self.telnet_LINEMODE for opt in (LINEMODE, NAWS, SGA): self.transport.do(opt).addErrback( lambda f: self._log.failure("Error do {opt!r}", f, opt=opt) ) for opt in (ECHO,): self.transport.will(opt).addErrback( lambda f: self._log.failure("Error setting will {opt!r}", f, opt=opt) ) self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs) try: factory = self.factory except AttributeError: pass else: self.protocol.factory = factory self.protocol.makeConnection(self) def connectionLost(self, reason): if self.protocol is not None: try: self.protocol.connectionLost(reason) finally: del self.protocol def dataReceived(self, data): self.protocol.dataReceived(data) def enableLocal(self, opt): if opt == ECHO: return True elif opt == SGA: return True else: return False def enableRemote(self, opt): if opt == LINEMODE: self.transport.requestNegotiation(LINEMODE, MODE + LINEMODE_TRAPSIG) return True elif opt == NAWS: return True elif opt == SGA: return True else: return False def telnet_NAWS(self, data): # NAWS is client -> server *only*. self.protocol will # therefore be an ITerminalTransport, the `.protocol' # attribute of which will be an ITerminalProtocol. Maybe. # You know what, XXX TODO clean this up. if len(data) == 4: width, height = struct.unpack("!HH", b"".join(data)) self.protocol.terminalProtocol.terminalSize(width, height) else: self._log.error("Wrong number of NAWS bytes: {nbytes}", nbytes=len(data)) linemodeSubcommands = {LINEMODE_SLC: "SLC"} def telnet_LINEMODE(self, data): # linemodeSubcommand = data[0] # # XXX TODO: This should be enabled to parse linemode subnegotiation. # getattr(self, "linemode_" + self.linemodeSubcommands[linemodeSubcommand])( # data[1:] # ) pass def linemode_SLC(self, data): chunks = zip(*[iter(data)] * 3) for slcFunction, slcValue, slcWhat in chunks: # Later, we should parse stuff. "SLC", ord(slcFunction), ord(slcValue), ord(slcWhat) from twisted.protocols import basic class StatefulTelnetProtocol(basic.LineReceiver, TelnetProtocol): delimiter = b"\n" state = "Discard" def connectionLost(self, reason): basic.LineReceiver.connectionLost(self, reason) TelnetProtocol.connectionLost(self, reason) def lineReceived(self, line): oldState = self.state newState = getattr(self, "telnet_" + oldState)(line) if newState is not None: if self.state == oldState: self.state = newState else: self._log.warn("state changed and new state returned") def telnet_Discard(self, line): pass from twisted.cred import credentials class AuthenticatingTelnetProtocol(StatefulTelnetProtocol): """ A protocol which prompts for credentials and attempts to authenticate them. Username and password prompts are given (the password is obscured). When the information is collected, it is passed to a portal and an avatar implementing L{ITelnetProtocol} is requested. If an avatar is returned, it connected to this protocol's transport, and this protocol's transport is connected to it. Otherwise, the user is re-prompted for credentials. """ state = "User" protocol = None def __init__(self, portal): self.portal = portal def connectionMade(self): self.transport.write(b"Username: ") def connectionLost(self, reason): StatefulTelnetProtocol.connectionLost(self, reason) if self.protocol is not None: try: self.protocol.connectionLost(reason) self.logout() finally: del self.protocol, self.logout def telnet_User(self, line): self.username = line self.transport.will(ECHO) self.transport.write(b"Password: ") return "Password" def telnet_Password(self, line): username, password = self.username, line del self.username def login(ignored): creds = credentials.UsernamePassword(username, password) d = self.portal.login(creds, None, ITelnetProtocol) d.addCallback(self._cbLogin) d.addErrback(self._ebLogin) self.transport.wont(ECHO).addCallback(login) return "Discard" def _cbLogin(self, ial): interface, protocol, logout = ial assert interface is ITelnetProtocol self.protocol = protocol self.logout = logout self.state = "Command" protocol.makeConnection(self.transport) self.transport.protocol = protocol def _ebLogin(self, failure): self.transport.write(b"\nAuthentication failed\n") self.transport.write(b"Username: ") self.state = "User" __all__ = [ # Exceptions "TelnetError", "NegotiationError", "OptionRefused", "AlreadyNegotiating", "AlreadyEnabled", "AlreadyDisabled", # Interfaces "ITelnetProtocol", "ITelnetTransport", # Other stuff, protocols, etc. "Telnet", "TelnetProtocol", "TelnetTransport", "TelnetBootstrapProtocol", ] ssh/agent.py 0000644 00000022454 15027667726 0007042 0 ustar 00 # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Implements the SSH v2 key agent protocol. This protocol is documented in the SSH source code, in the file U{PROTOCOL.agent<http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/PROTOCOL.agent>}. Maintainer: Paul Swartz """ import struct from twisted.conch.error import ConchError, MissingKeyStoreError from twisted.conch.ssh import keys from twisted.conch.ssh.common import NS, getMP, getNS from twisted.internet import defer, protocol class SSHAgentClient(protocol.Protocol): """ The client side of the SSH agent protocol. This is equivalent to ssh-add(1) and can be used with either ssh-agent(1) or the SSHAgentServer protocol, also in this package. """ def __init__(self): self.buf = b"" self.deferreds = [] 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): pack = struct.pack("!LB", len(data) + 1, reqType) + data self.transport.write(pack) d = defer.Deferred() self.deferreds.append(d) return d def requestIdentities(self): """ @return: A L{Deferred} which will fire with a list of all keys found in the SSH agent. The list of keys is comprised of (public key blob, comment) tuples. """ d = self.sendRequest(AGENTC_REQUEST_IDENTITIES, b"") d.addCallback(self._cbRequestIdentities) return d 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""): """ Add a private key blob to the agent's collection of keys. """ req = blob req += NS(comment) return self.sendRequest(AGENTC_ADD_IDENTITY, req) def signData(self, blob, data): """ Request that the agent sign the given C{data} with the private key which corresponds to the public key given by C{blob}. The private key should have been added to the agent already. @type blob: L{bytes} @type data: L{bytes} @return: A L{Deferred} which fires with a signature for given data created with the given key. """ req = NS(blob) req += NS(data) req += b"\000\000\000\000" # flags return self.sendRequest(AGENTC_SIGN_REQUEST, req).addCallback(self._cbSignData) 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): """ Remove the private key corresponding to the public key in blob from the running agent. """ req = NS(blob) return self.sendRequest(AGENTC_REMOVE_IDENTITY, req) def removeAllIdentities(self): """ Remove all keys from the running agent. """ return self.sendRequest(AGENTC_REMOVE_ALL_IDENTITIES, b"") class SSHAgentServer(protocol.Protocol): """ The server side of the SSH agent protocol. This is equivalent to ssh-agent(1) and can be used with either ssh-add(1) or the SSHAgentClient protocol, also in this package. """ def __init__(self): self.buf = b"" 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]) reqName = messages.get(reqType, None) if not reqName: self.sendResponse(AGENT_FAILURE, b"") else: f = getattr(self, "agentc_%s" % reqName) if getattr(self.factory, "keys", None) is None: self.sendResponse(AGENT_FAILURE, b"") raise MissingKeyStoreError() f(packet[1:]) def sendResponse(self, reqType, data): pack = struct.pack("!LB", len(data) + 1, reqType) + data self.transport.write(pack) def agentc_REQUEST_IDENTITIES(self, data): """ Return all of the identities that have been added to the server """ assert data == b"" numKeys = len(self.factory.keys) resp = [] resp.append(struct.pack("!L", numKeys)) for key, comment in self.factory.keys.values(): resp.append(NS(key.blob())) # yes, wrapped in an NS resp.append(NS(comment)) self.sendResponse(AGENT_IDENTITIES_ANSWER, b"".join(resp)) def agentc_SIGN_REQUEST(self, data): """ Data is a structure with a reference to an already added key object and some data that the clients wants signed with that key. If the key object wasn't loaded, return AGENT_FAILURE, else return the signature. """ blob, data = getNS(data) if blob not in self.factory.keys: return self.sendResponse(AGENT_FAILURE, b"") signData, data = getNS(data) assert data == b"\000\000\000\000" self.sendResponse( AGENT_SIGN_RESPONSE, NS(self.factory.keys[blob][0].sign(signData)) ) def agentc_ADD_IDENTITY(self, data): """ Adds a private key to the agent's collection of identities. On subsequent interactions, the private key can be accessed using only the corresponding public key. """ # need to pre-read the key data so we can get past it to the comment string keyType, rest = getNS(data) if keyType == b"ssh-rsa": nmp = 6 elif keyType == b"ssh-dss": nmp = 5 else: raise keys.BadKeyError("unknown blob type: %s" % keyType) rest = getMP(rest, nmp)[ -1 ] # ignore the key data for now, we just want the comment comment, rest = getNS(rest) # the comment, tacked onto the end of the key blob k = keys.Key.fromString(data, type="private_blob") # not wrapped in NS here self.factory.keys[k.blob()] = (k, comment) self.sendResponse(AGENT_SUCCESS, b"") def agentc_REMOVE_IDENTITY(self, data): """ Remove a specific key from the agent's collection of identities. """ blob, _ = getNS(data) k = keys.Key.fromString(blob, type="blob") del self.factory.keys[k.blob()] self.sendResponse(AGENT_SUCCESS, b"") def agentc_REMOVE_ALL_IDENTITIES(self, data): """ Remove all keys from the agent's collection of identities. """ assert data == b"" self.factory.keys = {} self.sendResponse(AGENT_SUCCESS, b"") # v1 messages that we ignore because we don't keep v1 keys # open-ssh sends both v1 and v2 commands, so we have to # do no-ops for v1 commands or we'll get "bad request" errors def agentc_REQUEST_RSA_IDENTITIES(self, data): """ v1 message for listing RSA1 keys; superseded by agentc_REQUEST_IDENTITIES, which handles different key types. """ self.sendResponse(AGENT_RSA_IDENTITIES_ANSWER, struct.pack("!L", 0)) def agentc_REMOVE_RSA_IDENTITY(self, data): """ v1 message for removing RSA1 keys; superseded by agentc_REMOVE_IDENTITY, which handles different key types. """ self.sendResponse(AGENT_SUCCESS, b"") def agentc_REMOVE_ALL_RSA_IDENTITIES(self, data): """ v1 message for removing all RSA1 keys; superseded by agentc_REMOVE_ALL_IDENTITIES, which handles different key types. """ self.sendResponse(AGENT_SUCCESS, b"") AGENTC_REQUEST_RSA_IDENTITIES = 1 AGENT_RSA_IDENTITIES_ANSWER = 2 AGENT_FAILURE = 5 AGENT_SUCCESS = 6 AGENTC_REMOVE_RSA_IDENTITY = 8 AGENTC_REMOVE_ALL_RSA_IDENTITIES = 9 AGENTC_REQUEST_IDENTITIES = 11 AGENT_IDENTITIES_ANSWER = 12 AGENTC_SIGN_REQUEST = 13 AGENT_SIGN_RESPONSE = 14 AGENTC_ADD_IDENTITY = 17 AGENTC_REMOVE_IDENTITY = 18 AGENTC_REMOVE_ALL_IDENTITIES = 19 messages = {} for name, value in locals().copy().items(): if name[:7] == "AGENTC_": messages[value] = name[7:] # doesn't handle doubles ssh/channel.py 0000644 00000023360 15027667726 0007351 0 ustar 00 # -*- test-case-name: twisted.conch.test.test_channel -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ The parent class for all the SSH Channels. Currently implemented channels are session, direct-tcp, and forwarded-tcp. Maintainer: Paul Swartz """ from zope.interface import implementer from twisted.internet import interfaces from twisted.logger import Logger from twisted.python import log @implementer(interfaces.ITransport) class SSHChannel(log.Logger): """ A class that represents a multiplexed channel over an SSH connection. The channel has a local window which is the maximum amount of data it will receive, and a remote which is the maximum amount of data the remote side will accept. There is also a maximum packet size for any individual data packet going each way. @ivar name: the name of the channel. @type name: L{bytes} @ivar localWindowSize: the maximum size of the local window in bytes. @type localWindowSize: L{int} @ivar localWindowLeft: how many bytes are left in the local window. @type localWindowLeft: L{int} @ivar localMaxPacket: the maximum size of packet we will accept in bytes. @type localMaxPacket: L{int} @ivar remoteWindowLeft: how many bytes are left in the remote window. @type remoteWindowLeft: L{int} @ivar remoteMaxPacket: the maximum size of a packet the remote side will accept in bytes. @type remoteMaxPacket: L{int} @ivar conn: the connection this channel is multiplexed through. @type conn: L{SSHConnection} @ivar data: any data to send to the other side when the channel is requested. @type data: L{bytes} @ivar avatar: an avatar for the logged-in user (if a server channel) @ivar localClosed: True if we aren't accepting more data. @type localClosed: L{bool} @ivar remoteClosed: True if the other side isn't accepting more data. @type remoteClosed: L{bool} """ _log = Logger() name: bytes = None # type: ignore[assignment] # only needed for client channels def __init__( self, localWindow=0, localMaxPacket=0, remoteWindow=0, remoteMaxPacket=0, conn=None, data=None, avatar=None, ): self.localWindowSize = localWindow or 131072 self.localWindowLeft = self.localWindowSize self.localMaxPacket = localMaxPacket or 32768 self.remoteWindowLeft = remoteWindow self.remoteMaxPacket = remoteMaxPacket self.areWriting = 1 self.conn = conn self.data = data self.avatar = avatar self.specificData = b"" self.buf = b"" self.extBuf = [] self.closing = 0 self.localClosed = 0 self.remoteClosed = 0 self.id = None # gets set later by SSHConnection def __str__(self) -> str: return self.__bytes__().decode("ascii") def __bytes__(self) -> bytes: """ Return a byte string representation of the channel """ name = self.name if not name: name = b"None" return b"<SSHChannel %b (lw %d rw %d)>" % ( name, self.localWindowLeft, self.remoteWindowLeft, ) def logPrefix(self): id = (self.id is not None and str(self.id)) or "unknown" if self.name: name = self.name.decode("ascii") else: name = "None" return f"SSHChannel {name} ({id}) on {self.conn.logPrefix()}" def channelOpen(self, specificData): """ Called when the channel is opened. specificData is any data that the other side sent us when opening the channel. @type specificData: L{bytes} """ self._log.info("channel open") def openFailed(self, reason): """ Called when the open failed for some reason. reason.desc is a string descrption, reason.code the SSH error code. @type reason: L{error.ConchError} """ self._log.error("other side refused open\nreason: {reason}", reason=reason) def addWindowBytes(self, data): """ Called when bytes are added to the remote window. By default it clears the data buffers. @type data: L{bytes} """ self.remoteWindowLeft = self.remoteWindowLeft + data if not self.areWriting and not self.closing: self.areWriting = True self.startWriting() if self.buf: b = self.buf self.buf = b"" self.write(b) if self.extBuf: b = self.extBuf self.extBuf = [] for (type, data) in b: self.writeExtended(type, data) def requestReceived(self, requestType, data): """ Called when a request is sent to this channel. By default it delegates to self.request_<requestType>. If this function returns true, the request succeeded, otherwise it failed. @type requestType: L{bytes} @type data: L{bytes} @rtype: L{bool} """ foo = requestType.replace(b"-", b"_").decode("ascii") f = getattr(self, "request_" + foo, None) if f: return f(data) self._log.info("unhandled request for {requestType}", requestType=requestType) return 0 def dataReceived(self, data): """ Called when we receive data. @type data: L{bytes} """ self._log.debug("got data {data}", data=data) def extReceived(self, dataType, data): """ Called when we receive extended data (usually standard error). @type dataType: L{int} @type data: L{str} """ self._log.debug( "got extended data {dataType} {data!r}", dataType=dataType, data=data ) def eofReceived(self): """ Called when the other side will send no more data. """ self._log.info("remote eof") def closeReceived(self): """ Called when the other side has closed the channel. """ self._log.info("remote close") self.loseConnection() def closed(self): """ Called when the channel is closed. This means that both our side and the remote side have closed the channel. """ self._log.info("closed") def write(self, data): """ Write some data to the channel. If there is not enough remote window available, buffer until it is. Otherwise, split the data into packets of length remoteMaxPacket and send them. @type data: L{bytes} """ if self.buf: self.buf += data return top = len(data) if top > self.remoteWindowLeft: data, self.buf = ( data[: self.remoteWindowLeft], data[self.remoteWindowLeft :], ) self.areWriting = 0 self.stopWriting() top = self.remoteWindowLeft rmp = self.remoteMaxPacket write = self.conn.sendData r = range(0, top, rmp) for offset in r: write(self, data[offset : offset + rmp]) self.remoteWindowLeft -= top if self.closing and not self.buf: self.loseConnection() # try again def writeExtended(self, dataType, data): """ Send extended data to this channel. If there is not enough remote window available, buffer until there is. Otherwise, split the data into packets of length remoteMaxPacket and send them. @type dataType: L{int} @type data: L{bytes} """ if self.extBuf: if self.extBuf[-1][0] == dataType: self.extBuf[-1][1] += data else: self.extBuf.append([dataType, data]) return if len(data) > self.remoteWindowLeft: data, self.extBuf = ( data[: self.remoteWindowLeft], [[dataType, data[self.remoteWindowLeft :]]], ) self.areWriting = 0 self.stopWriting() while len(data) > self.remoteMaxPacket: self.conn.sendExtendedData(self, dataType, data[: self.remoteMaxPacket]) data = data[self.remoteMaxPacket :] self.remoteWindowLeft -= self.remoteMaxPacket if data: self.conn.sendExtendedData(self, dataType, data) self.remoteWindowLeft -= len(data) if self.closing: self.loseConnection() # try again def writeSequence(self, data): """ Part of the Transport interface. Write a list of strings to the channel. @type data: C{list} of L{str} """ self.write(b"".join(data)) def loseConnection(self): """ Close the channel if there is no buferred data. Otherwise, note the request and return. """ self.closing = 1 if not self.buf and not self.extBuf: self.conn.sendClose(self) def getPeer(self): """ See: L{ITransport.getPeer} @return: The remote address of this connection. @rtype: L{SSHTransportAddress}. """ return self.conn.transport.getPeer() def getHost(self): """ See: L{ITransport.getHost} @return: An address describing this side of the connection. @rtype: L{SSHTransportAddress}. """ return self.conn.transport.getHost() def stopWriting(self): """ Called when the remote buffer is full, as a hint to stop writing. This can be ignored, but it can be helpful. """ def startWriting(self): """ Called when the remote buffer has more room, as a hint to continue writing. """ ssh/factory.py 0000644 00000007372 15027667726 0007415 0 ustar 00 # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ A Factory for SSH servers. See also L{twisted.conch.openssh_compat.factory} for OpenSSH compatibility. Maintainer: Paul Swartz """ import random from twisted.conch import error from twisted.conch.ssh import _kex, connection, transport, userauth from twisted.internet import protocol from twisted.logger import Logger class SSHFactory(protocol.Factory): """ A Factory for SSH servers. """ _log = Logger() protocol = transport.SSHServerTransport services = { b"ssh-userauth": userauth.SSHUserAuthServer, b"ssh-connection": connection.SSHConnection, } 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): """ Create an instance of the server side of the SSH protocol. @type addr: L{twisted.internet.interfaces.IAddress} provider @param addr: The address at which the server will listen. @rtype: L{twisted.conch.ssh.transport.SSHServerTransport} @return: The built transport. """ t = protocol.Factory.buildProtocol(self, addr) t.supportedPublicKeys = self.privateKeys.keys() if not self.primes: self._log.info( "disabling non-fixed-group key exchange algorithms " "because we cannot find moduli file" ) t.supportedKeyExchanges = [ kexAlgorithm for kexAlgorithm in t.supportedKeyExchanges if _kex.isFixedGroup(kexAlgorithm) or _kex.isEllipticCurve(kexAlgorithm) ] return t def getPublicKeys(self): """ Called when the factory is started to get the public portions of the servers host keys. Returns a dictionary mapping SSH key types to public key strings. @rtype: L{dict} """ raise NotImplementedError("getPublicKeys unimplemented") def getPrivateKeys(self): """ Called when the factory is started to get the private portions of the servers host keys. Returns a dictionary mapping SSH key types to L{twisted.conch.ssh.keys.Key} objects. @rtype: L{dict} """ raise NotImplementedError("getPrivateKeys unimplemented") def getPrimes(self): """ Called when the factory is started to get Diffie-Hellman generators and primes to use. Returns a dictionary mapping number of bits to lists of tuple of (generator, prime). @rtype: L{dict} """ def getDHPrime(self, bits): """ Return a tuple of (g, p) for a Diffe-Hellman process, with p being as close to bits bits as possible. @type bits: L{int} @rtype: L{tuple} """ primesKeys = sorted(self.primes.keys(), key=lambda i: abs(i - bits)) realBits = primesKeys[0] return random.choice(self.primes[realBits]) def getService(self, transport, service): """ Return a class to use as a service for the given transport. @type transport: L{transport.SSHServerTransport} @type service: L{bytes} @rtype: subclass of L{service.SSHService} """ if service == b"ssh-userauth" or hasattr(transport, "avatar"): return self.services[service] ssh/service.py 0000644 00000003024 15027667726 0007374 0 ustar 00 # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ The parent class for all the SSH services. Currently implemented services are ssh-userauth and ssh-connection. Maintainer: Paul Swartz """ from typing import Dict from twisted.logger import Logger class SSHService: # this is the ssh name for the service: name: bytes = None # type:ignore[assignment] protocolMessages: Dict[int, str] = {} # map #'s -> protocol names transport = None # gets set later _log = Logger() def serviceStarted(self): """ called when the service is active on the transport. """ def serviceStopped(self): """ called when the service is stopped, either by the connection ending or by another service being started """ def logPrefix(self): return "SSHService {!r} on {}".format( self.name, self.transport.transport.logPrefix() ) def packetReceived(self, messageNum, packet): """ called when we receive a packet on the transport """ # print self.protocolMessages if messageNum in self.protocolMessages: messageType = self.protocolMessages[messageNum] f = getattr(self, "ssh_%s" % messageType[4:], None) if f is not None: return f(packet) self._log.info( "couldn't handle {messageNum} {packet!r}", messageNum=messageNum, packet=packet, ) self.transport.sendUnimplemented() ssh/__pycache__/forwarding.cpython-310.pyc 0000644 00000020714 15027667726 0014442 0 ustar 00 o �b! � @ s� d Z ddlZddlmZmZ ddlmZmZ ddlm Z m Z G dd� dej�ZG dd � d ej �ZG d d� de�ZG dd � d e�ZG dd� dej �Zdd� ZG dd� dej�Zdd� ZeZdd� ZeZdd� Zdd� ZdS )z� This module contains the implementation of the TCP forwarding, which allows clients and servers to forward arbitrary TCP data across the connection. Maintainer: Paul Swartz � N)�channel�common)�protocol�reactor)�HostnameEndpoint�connectProtocolc @ s e Zd Zdd� Zdd� ZdS )�SSHListenForwardingFactoryc C s || _ || _|| _d S �N)�conn�hostport�klass)�self� connectionr r � r �>/usr/lib/python3/dist-packages/twisted/conch/ssh/forwarding.py�__init__ s z#SSHListenForwardingFactory.__init__c C sF | j | jd�}t|�}||_|j|jf}t| j|�}| j�||� |S )N)r ) r r �SSHForwardingClient�client�host�port�packOpen_direct_tcpipr �openChannel)r �addrr r � addrTuple�channelOpenDatar r r � buildProtocol s z(SSHListenForwardingFactory.buildProtocolN)�__name__� __module__�__qualname__r r r r r r r s r c @ s4 e Zd Zdd� Zdd� Zdd� Zdd� Zd d � ZdS )�SSHListenForwardingChannelc C sH | j jd| jd� t| jj�dkr| jjdd � }| �|� d| j_d S )Nzopened forwarding channel {id}��id� � )�_log�infor! �lenr �buf�write)r �specificData�br r r �channelOpen$ s z&SSHListenForwardingChannel.channelOpenc C s | � � d S r )�closed�r �reasonr r r � openFailed+ s z%SSHListenForwardingChannel.openFailedc C s | j j�|� d S r )r � transportr( �r �datar r r �dataReceived. s z'SSHListenForwardingChannel.dataReceivedc C s | j j�� d S r )r r0 �loseConnection�r r r r �eofReceived1 s z&SSHListenForwardingChannel.eofReceivedc C s4 t | d�r| jjd| jd� | jj�� | `d S d S )Nr z%closing local forwarding channel {id}r )�hasattrr$ r% r! r r0 r4 r5 r r r r, 4 s �z!SSHListenForwardingChannel.closedN)r r r r+ r/ r3 r6 r, r r r r r # s r c @ � e Zd ZdZdS )� SSHListenClientForwardingChannels direct-tcpipN�r r r �namer r r r r9 ; � r9 c @ r8 )� SSHListenServerForwardingChannels forwarded-tcpipNr: r r r r r= @ r<