ϪfU PUdZddlZddlZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZddlmZmZmZddlmZddlmZmZddlmZdd lmZdd lmZdd lmZm Z dd l!m"Z"m#Z#dd l$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+m,Z,ddl-m.Z.ddl/m0Z0ddl1m2Z2e'Z3Gddee4e4e5e5e4e4e4fZ6GddeZ7e e7e8d< ddl9Z:ee7e:Z9 ddlde7de?de6fdZ@de4de e>fdZAde4de e>fd ZBeeGd!d"ZCeeGd#d$ZDeeGd%d&ZEe.ed'd(ddd)eFd$Gd*d+eZGejjfd,ee?d-e e?gejfde ejfd.ZJd/e e0ed-e e?gejfde ejfd0ZKeeGGd1d2ZLeeGGd3d4ZMeeGd5d6ZNy#e;$rdZ9YGwxYw#e;$rdZs r+ __getitem__z!CryptedPasswordRecord.__getitem__Yr:r-N)r.r/r0r1rr3rAr(r-r+r=r=Rs    r-r=userdbr6r%cf|j|jtjS)a+ Lookup a user by name in a L{pwd}-style database. @param userdb: The user database. @param username: Identifying name in bytes. This will be decoded according to the filesystem encoding, as the L{pwd} module does internally. @raises KeyError: when the user doesn't exist )r9decodesysgetfilesystemencoding)rBr6s r+ _lookupUserrG_s% ??8??3+D+D+FG HHr-cVtytttj|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. @returns: A L{pwd.struct_passwd}, where field 1 may contain a crypted password, or L{None} when the L{pwd} database is unavailable. @raises KeyError: when no such user exists N)r;r r=r9)r6s r+ _pwdGetByNamerIms# { %s||H'= >>r-c jttj}nyttt dd||S)a 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} @returns: A L{spwd.struct_spwd}, where field 1 may contain a crypted password, or L{None} when the L{spwd} database is unavailable. @raises KeyError: when no such user exists Nr)spwdgetspnamr r=r")r6fs r+_shadowGetByNamerNs0  MM %'9!Q8'L MMr-c$eZdZdZefZddZdZy)UNIXPasswordDatabaseae 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 validate a user. The default value is such that the C{/etc/passwd} database will be tried first, followed by the C{/etc/shadow} database. Nc.| ttg}||_yr')rIrN_getByNameFunctions)r*getByNameFunctionss r+__init__zUNIXPasswordDatabase.__init__s  %"/1A!B #5 r-c|jjtj}|jjtj}|j D]F} ||}||d}|dk(rt ||s'tj|jcStjtdS#t$r#tjtdcYcSwxYw)Nr?zinvalid usernamezunable to verify password) r6rDrErFpasswordrRrrsucceedKeyErrorfailr)r* credentialsr6rWfuncpwnamcrypteds r+requestAvatarIdz$UNIXPasswordDatabase.requestAvatarIds''..s/H/H/JK''..s/H/H/JK,, CD CX$#AhG"} ,Wh?$}}[-A-ABB Czz+,GHII Izz"34F"GHH Is+C'C:9C:r')r.r/r0r1rcredentialInterfacesrTr_r(r-r+rPrPs./6 Jr-rPcReZdZUdZefZeeeZ ee d<dZ dZ dZ dZdZy) SSHPublicKeyDatabasez Checker that authenticates SSH public keys, based on public keys listed in authorized_keys and authorized_keys2 files in user .ssh/ directories. _userdbctj|j|}|j|j||j |j |Sr')r maybeDeferredcheckKey addCallback_cbRequestAvatarId addErrback_ebRequestAvatarIdr*r[ds r+r_z$SSHPublicKeyDatabase.requestAvatarIdsC    { ; d--{; T,,-r-c"|stjtdS|js'tjt j S t jj|j}|j|j|jr |jS tjtdS#t$r6tjdtjtdcYSwxYw)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 signaturerValidPublicKeyrKey fromStringblobverifysigDatar6 Exception_log)r*validKeyr[pubKeys r+rhz'SSHPublicKeyDatabase._cbRequestAvatarIds*??#4]#CD D$$??5#7#7#9: : W,,[-=-=>==!6!6 8K8KL&///M 01GHII W 89'89T'UVV WsAC}. 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_keys2)rGrcr6r!r,child)r*r[pwentrootfilesrMs r+getAuthorizedKeysFilesz+SSHPublicKeyDatabase.getAuthorizedKeysFilessZ DLL+*>*>? %++F3"$67',-! 1 ---s A(cTt|j|jdd\}}|j|D]}}|j s |j }|5|D]H}|j}t|dkr" t|d|jk(r dddyJ dddy#t $r@}|jtjk(rt|||j }nYd}~d}~wwxYw#tj$rYwxYw#1swYxYw)zg Retrieve files containing authorized keys and check against user credentials. Nr?TF)rGrcr6rexistsopenOSErrorerrnoEACCESr"splitlenrrtbinasciiError) r*r[ouidogidfilepathlinesell2s r+rfzSSHPublicKeyDatabase.checkKeys* !{/C/CDQqI d33K@ !H??$    !!AB2w{ !&r!u-1A1AA#' ! ! B ! ! ! !( 77ell*.tT8==IE $>>! ! ! !sN B9%DD D+D9 D6C==DD DD DD' c|jts?tjd|jt j tdS|S)Nz1Unauthorized login due to internal error: {error}rzunable to get avatar id)checkrrxrvaluerro)r*rMs r+rjz'SSHPublicKeyDatabase._ebRequestAvatarId"sFww() JJC177  ??#45N#OP Pr-N)r.r/r0r1rr`r r5r;rc__annotations__r_rhrrfrjr(r-r+rbrbs> +,63'GV' !JF.*8r-rbc>eZdZdZdZedZdZdZdZ dZ y) 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. c i|_i|_yr')checkerssuccessfulCredentialsr)s r+rTzSSHProtocolChecker.__init__8s %'"r-cHt|jjSr')listrrr)s r+r`z'SSHProtocolChecker.credentialInterfaces<sDMM&&())r-cL|s |j}|D]}||j|<yr')r`r)r*checkerr`credentialInterfaces r+registerCheckerz"SSHProtocolChecker.registerChecker@s0##*#?#? #7 9 18DMM- . 9r-c lt|}|D]]}|jj|}|!tj|j |}|j |j|cStjtddjttj|zS)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 zNo checker for %sz, )rrgetrrer_rg_cbGoodAuthenticationrZrjoinmaprqual)r*r[ifacicrls r+r_z"SSHProtocolChecker.requestAvatarIdFs+& NA !!!$A}''(9(9;G}}T%?%?MM  N zz #diiGLL$0G&HH   r-c||jvrg|j|<|j|j||j|r|j|=|Stj)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. )rappendareDonerNotEnoughAuthentication)r*avatarIdr[s r+rz(SSHProtocolChecker._cbGoodAuthentication]si 455 535D & &x 0 ""8,33K@ << !**84O//1 1r-cy)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*rs r+rzSSHProtocolChecker.areDonemsr-N) r.r/r0r1rTr2r`rr_rrr(r-r+rr+s4 (**9  .2 r-rTwistedzPlease use twisted.conch.checkers.SSHPublicKeyChecker, initialized with an instance of twisted.conch.checkers.UNIXAuthorizedKeysFiles instead.ceZdZdZdZy)IAuthorizedKeysDBzb An object that provides valid authorized ssh keys mapped to usernames. @since: 15.0 cy)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()rs r+getAuthorizedKeysz#IAuthorizedKeysDB.getAuthorizedKeysr:r-N)r.r/r0r1rr(r-r+rrs   r-rfileobjparseKeyc#K|D]2}|j}|s|jdr( ||4y#tj$r"}tj d||Yd}~fd}~wwxYww)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})linerN)strip startswithr BadKeyErrorrxr)rrrrs r+readAuthorizedKeyFilersu  zz| - tn$  ##  G s0A3A3 ;A3A0A+&A3+A00A3 filepathsc#$K|D]A}|js |j5}t||Ed{dddCy7#1swYxYw#t$r,}tj d|j |Yd}~d}~wwxYww)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} @since: 15.0 Nz"Unable to read {path!r}: {error!s})pathr)rrrrrxrr)rrfprMrs r+_keysFromFilepathsrs&X 99; XWWYB!4QAAABXBBB X ?bggUV WW XsTBAA A A AB A  A A B !"BBB  BcneZdZdZdeeeejfddfdZ dedeejfdZ y)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 mappingr%Nc||_y)z Initializes a new L{InMemorySSHKeyDB}. @param mapping: mapping of usernames to iterables of L{twisted.conch.ssh.keys.Key}s N)_mapping)r*rs r+rTzInMemorySSHKeyDB.__init__s   r-r6c:|jj|gS)zd Look up the authorized keys for a user. @param username: Name of the user )rrr8s r+rz"InMemorySSHKeyDB.getAuthorizedKeyss }}  2..r-) r.r/r0r1r bytesrrrrrTrr(r-r+rrsI x/A(A B t /%/HTXX4F/r-rceZdZUdZeed<dejjfde ede e gejffdZ de de ejfd Zy) 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 rcNrBrcl|||_||_ytt|_||_ytd)a Initializes a new L{UNIXAuthorizedKeysFiles}. @param userdb: access to the Unix user account and password database (default is the Python module L{pwd}, if available) @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}. Nz3No pwd module found, and no userdb argument passed.)rcr; ValueError _parseKey)r*rBrs r+rTz UNIXAuthorizedKeysFiles.__init__s?  !DL " _DL"RS Sr-r6r%c t|j|}t|jj dddg}t fd|D|jS#t$rYywxYw)Nr(r|r}r~c3@K|]}j|ywr')r).0rMrs r+ z.s"@Q4::a="@s)rGrcrYr!r,rrr)r*r6passwdrrs @r+rz)UNIXAuthorizedKeysFiles.getAuthorizedKeyssi  x8F &,,V4"$67!"@%"@$..QQ   sA A,+A,)r.r/r0r1r5rrrrrsr rrrTrrr(r-r+rrskO$(040C0C" "E7DHH,-".R%RHTXX4FRr-rc>eZdZdZefZdeddfdZdZdZ dZ d Z y) 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 keydbr%Nc||_y)zq Initializes a L{SSHPublicKeyChecker}. @param keydb: a provider of L{IAuthorizedKeysDB} N)_keydb)r*rs r+rTzSSHPublicKeyChecker.__init__+s  r-ctj|j|}|j|j||j|j ||Sr')rexecute_sanityCheckKeyrg _checkKey _verifyKeyrks r+r_z#SSHPublicKeyChecker.requestAvatarId3sA MM$.. < dnnk2 doo{3r-c|jstjtjj |j S)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} )rprrqrrrrsrt)r*r[s r+rz#SSHPublicKeyChecker._sanityCheckKey9s7"$$&&( (xx"";#3#344r-ctfd|jj|jDrSt d)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} c3(K|] }|k( ywr'r()rkeyrzs r+rz0SSHPublicKeyChecker._checkKey..as !C6M szKey not authorized)anyrrr6r)r*rzr[s ` r+rzSSHPublicKeyChecker._checkKeyOsB$  %)[[%B%B;CWCW%X  M 455r-c |j|j|jr |jS t d#t$r}t d|d}~wwxYw)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} rnNzKey signature invalid.)rurprvr6rwr)r*rzr[rs r+rzSSHPublicKeyChecker._verifyKeyhsd$ H}}[22K4G4GH"+++I  899 H#$?@a G Hs1A A AA) r.r/r0r1rr`rrTr_rrrr(r-r+rrs:+,/D 5,62:r-r)Or1rrrEbase64rtypingrrrrrr r r r zope.interfacer rr incrementalrrr twisted.conchrtwisted.conch.sshrtwisted.cred.checkersrtwisted.cred.credentialsrrtwisted.cred.errorrrtwisted.internetrtwisted.loggerrtwisted.plugins.cred_unixrtwisted.pythonrrtwisted.python.deprecater twisted.python.filepathr!twisted.python.utilr"rxr3intr$r5rr;_pwd ImportErrorrK_spwdr=rrGrIrNrPrbrr.rrrrsrrrrrr(r-r+rs   XXX==$"5FF"!;+>,2 x  sCc3S89    X  f vt C D  H   I I% IJ I?C?H-B$C?$NsNx0E'FN* !%J%J"%JP !jj"jZ !JJ"JZ Ir1a  B    *AE@S@S Y"*E7DHH+<"= dhh:X &X2:E7DHH;L2MX dhhX8 // /6 +R+R +R\ !b:b:"b:u C Ds$H H HHH%$H%