o bK@sFdZddlZddlZddlZddlmZddlmZmZm Z zddl Z Wn e y/dZ Ynwe Z zddl ZWn e yCdZ YnweZ ddlmZmZmZddlmZddlmZddlmZdd lmZdd lmZmZdd lmZm Z dd l!m"Z"dd l#m$Z$ddl%m&Z&ddl'm(Z(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/e$Z0ddZ1ddZ2eeGdddZ3eeGdddZ4eeGdddZ5e+eddddde6dGd d!d!eZ7ej8j9fd"ed#ee:gej8fd$e ej8fd%d&Z;d'd(ZeeGd-d.d.Z?dS)/zO Provide L{ICredentialsChecker} implementations to be used in Conch protocols. N) decodebytes)BinaryIOCallableIterator) Interface implementer providedBy)Versionerror)keys)ICredentialsChecker)ISSHPrivateKeyIUsernamePassword)UnauthorizedLoginUnhandledCredentials)defer)Logger)verifyCryptedPassword)failurereflect)deprecatedModuleAttribute)FilePath)runAsEffectiveUsercCstdurdSt|S)a 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} N)pwdgetpwnam)usernamer8/usr/lib/python3/dist-packages/twisted/conch/checkers.py _pwdGetByName2s  rcCs"tdurtj}ndStdd||S)z 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} Nr)spwdgetspnamr)rfrrr_shadowGetByName@s r#c@s(eZdZdZefZdddZddZdS)UNIXPasswordDatabaseab 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. NcCs|durttg}||_dSN)rr#_getByNameFunctions)selfgetByNameFunctionsrrr__init__]s zUNIXPasswordDatabase.__init__c Cs|jt}|jt}|jD]5}z||}Wnty-tt dYSw|durH|d}|dkr;qt ||rHt |jSqtt dS)Nzinvalid usernamezunable to verify password) rdecodesysgetfilesystemencodingpasswordr&KeyErrorrfailrrsucceed)r' credentialsrr/funcpwnamcryptedrrrrequestAvatarIdbs     z$UNIXPasswordDatabase.requestAvatarIdr%)__name__ __module__ __qualname____doc__rcredentialInterfacesr)r7rrrrr$Ps   r$c@sBeZdZdZefZeZddZddZ ddZ dd Z d d Z d S) SSHPublicKeyDatabasez Checker that authenticates SSH public keys, based on public keys listed in authorized_keys and authorized_keys2 files in user .ssh/ directories. cCs,t|j|}||j|||j|Sr%)r maybeDeferredcheckKey addCallback_cbRequestAvatarId addErrback_ebRequestAvatarIdr'r3drrrr7s z$SSHPublicKeyDatabase.requestAvatarIdcCs|s ttdS|jsttSztj|j }| |j|j r'|j WSWnt y=tdttdYSwttdS)aC 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. z invalid keyError while verifying keyzerror while verifying keyzunable to verify key)rFailurer signaturer ValidPublicKeyr Key fromStringblobverifysigDatar Exception_log)r'validKeyr3pubKeyrrrrAs  z'SSHPublicKeyDatabase._cbRequestAvatarIdcs8|j|j}t|jdddg}fdd|DS)a 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}. I{$HOME/.ssh/authorized_keys2} is also returned, though it has been U{deprecated by OpenSSH since 2001}. @return: A list of L{FilePath} instances to files with the authorized keys. .sshauthorized_keysauthorized_keys2csg|]}|qSrchild.0r"rootrr sz?SSHPublicKeyDatabase.getAuthorizedKeysFiles..)_userdbrrrpw_dirrW)r'r3pwentfilesrrZrgetAuthorizedKeysFilessz+SSHPublicKeyDatabase.getAuthorizedKeysFilesc Cs |j|jdd\}}||D]q}|sqz|}Wn!ty@}z|jtjkr5t |||j}nWYd}~nd}~ww|8|D]-}| }t |dkrSqFzt |d|j krhWWddSWqFtjysYqFwWdn1s~wYqdS)zg Retrieve files containing authorized keys and check against user credentials. Nr*TF)r]rrraexistsopenOSErrorerrnoEACCESrsplitlenrrLbinasciiError) r'r3ouidogidfilepathlinesell2rrrr?s<     zSSHPublicKeyDatabase.checkKeycCs,|tstjd|jdttdS|S)Nz1Unauthorized login due to internal error: {error}r zunable to get avatar id)checkrrPr valuerrG)r'r"rrrrCs z'SSHPublicKeyDatabase._ebRequestAvatarIdN) r8r9r:r;rr<rr]r7rArar?rCrrrrr=ys# r=c@sDeZdZdZddZeddZddZdd Zd d Z d d Z dS)SSHProtocolCheckera 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. cCsi|_i|_dSr%)checkerssuccessfulCredentialsr'rrrr)s zSSHProtocolChecker.__init__cCst|jSr%)listrwr ryrrrr<sz'SSHProtocolChecker.credentialInterfacescGs"|s|j}|D]}||j|<qdSr%)r<rw)r'checkerr<credentialInterfacerrrregisterCheckers  z"SSHProtocolChecker.registerCheckerc Csft|}|D]}|j|}|dur"t|j|}||j|Sqtt dd t t j |S)a 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 NzNo checker for %sz, )rrwgetrr>r7r@_cbGoodAuthenticationr1rjoinmaprqual)r'r3ifacicrErrrr7s  z"SSHProtocolChecker.requestAvatarIdcCsB||jvr g|j|<|j||||r|j|=|St)a 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. )rxappendareDoner NotEnoughAuthentication)r'avatarIdr3rrrrs   z(SSHProtocolChecker._cbGoodAuthenticationcCdS)a 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. Tr)r'rrrrr)s zSSHProtocolChecker.areDoneN) r8r9r:r;r)propertyr<r}r7rrrrrrrvs   rvTwistedzPlease use twisted.conch.checkers.SSHPublicKeyChecker, initialized with an instance of twisted.conch.checkers.UNIXAuthorizedKeysFiles instead.c@seZdZdZddZdS)IAuthorizedKeysDBzb An object that provides valid authorized ssh keys mapped to usernames. @since: 15.0 cCr)aL 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} Nr)rrrrgetAuthorizedKeysHsz#IAuthorizedKeysDB.getAuthorizedKeysN)r8r9r:r;rrrrrrAs rfileobjparseKeyreturnc csl|D]0}|}|r3|ds3z||VWqtjy2}ztjd||dWYd}~qd}~wwqdS)a 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 #z1Unable to parse line {line!r} as a key: {error!s})liner N)strip startswithr BadKeyErrorrPr )rrrrqrrrreadAuthorizedKeyFileUs rc cs|D]@}|rCz|}t||EdHWdn1s!wYWqtyB}ztjd|j|dWYd}~qd}~wwqdS)a 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 Nz"Unable to read {path!r}: {error!s})pathr )rdrerrfrPr r) filepathsrfpr"rqrrr_keysFromFilepathsrs rc@s eZdZdZddZddZdS)InMemorySSHKeyDBz Object that provides SSH public keys based on a dictionary of usernames mapped to L{twisted.conch.ssh.keys.Key}s. @since: 15.0 cC ||_dS)z Initializes a new L{InMemorySSHKeyDB}. @param mapping: mapping of usernames to iterables of L{twisted.conch.ssh.keys.Key}s @type mapping: L{dict} N)_mapping)r'mappingrrrr)s zInMemorySSHKeyDB.__init__cCs|j|gSr%)rr~)r'rrrrrsz"InMemorySSHKeyDB.getAuthorizedKeysN)r8r9r:r;r)rrrrrrs rc@s*eZdZdZdejjfddZddZdS)UNIXAuthorizedKeysFilesa 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 NcCs"||_||_|durt|_dSdS)a 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} N)r] _parseKeyr)r'userdbrrrrr)s   z UNIXAuthorizedKeysFiles.__init__csXz|j|}Wn tyYdSwt|jdddg}tfdd|D|jS)NrrSrTrUc3s|]}|VqdSr%rVrXrZrr sz.)r]rr0rr^rWrr)r'rpasswdr`rrZrrs z)UNIXAuthorizedKeysFiles.getAuthorizedKeys) r8r9r:r;r rJrKr)rrrrrrs rc@s>eZdZdZefZddZddZddZdd Z d d Z d S) SSHPublicKeyCheckera? 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 cCr)z Initializes a L{SSHPublicKeyChecker}. @param keydb: a provider of L{IAuthorizedKeysDB} @type keydb: L{IAuthorizedKeysDB} provider N)_keydb)r'keydbrrrr)s zSSHPublicKeyChecker.__init__cCs.t|j|}||j|||j||Sr%)rr>_sanityCheckKeyr@ _checkKey _verifyKeyrDrrrr7sz#SSHPublicKeyChecker.requestAvatarIdcCs|jsttj|jS)aW 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} )rHr rIr rJrKrL)r'r3rrrrsz#SSHPublicKeyChecker._sanityCheckKeycs,tfdd|j|jDrStd)ab 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} c3s|]}|kVqdSr%r)rYkeyrRrrrs z0SSHPublicKeyChecker._checkKey..zKey not authorized)anyrrrr)r'rRr3rrrrs  zSSHPublicKeyChecker._checkKeyc CsFz||j|jr |jWSWtdty"}ztd|d}~ww)a~ 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} rFNzKey signature invalid.)rMrHrNrrOr)r'rRr3rqrrrrs zSSHPublicKeyChecker._verifyKeyN) r8r9r:r;rr<r)r7rrrrrrrrs   r)@r;rkrgr-base64rtypingrrrr_pwd ImportErrorr _spwdzope.interfacerrr incrementalr twisted.conchr twisted.conch.sshr twisted.cred.checkersr twisted.cred.credentialsrrtwisted.cred.errorrrtwisted.internetrtwisted.loggerrtwisted.plugins.cred_unixrtwisted.pythonrrtwisted.python.deprecatertwisted.python.filepathrtwisted.python.utilrrPrr#r$r=rvr8rrJrKbytesrrrrrrrrrs~               (mM   '