o bC@@sdZddlZddlZddlZddlZddlZddlmZddlm Z ddl m Z m Z ddl mZddlmZmZmZddlmZmZdd lmZdd lmZdd lmZGd d d e ZGdddeZGdddeZGdddeZGdddeZ e eeGdddZ!GdddZ"e eGdddZ#e eGdddZ$e eGdddZ%e e Gd d!d!Z&Gd"d#d#eZ'e e'Gd$d%d%Z(dS)&z This module defines L{ICredentials}, an interface for objects that represent authentication credentials to provide, and also includes a number of useful implementations of that interface. N)hexlify)md5) Interface implementer)error)calcHA1calcHA2 calcResponse) nativeString networkString)deprecatedModuleAttribute) secureRandom)Versionc@eZdZdZdS) ICredentialsz I check credentials. Implementors I{must} specify the sub-interfaces of ICredentials to which it conforms, using L{zope.interface.implementer}. N__name__ __module__ __qualname____doc__rr:/usr/lib/python3/dist-packages/twisted/cred/credentials.pyrrc@eZdZdZddZdS)IUsernameDigestHashz This credential is used when a CredentialChecker has access to the hash of the username:realm:password as in an Apache .htdigest file. cCdS)a- @param digestHash: The hashed username:realm:password to check against. @return: C{True} if the credentials represented by this object match the given hash, C{False} if they do not, or a L{Deferred} which will be called back with one of these values. Nr) digestHashrrr checkHash-zIUsernameDigestHash.checkHashN)rrrrrrrrrr's rc@r)IUsernameHashedPassworda I encapsulate a username and a hashed password. This credential is used when a hashed password is received from the party requesting authentication. CredentialCheckers which check this kind of credential must store the passwords in plaintext (or as password-equivalent hashes) form so that they can be hashed in a manner appropriate for the particular credentials class. @type username: L{bytes} @ivar username: The username associated with these credentials. cCra Validate these credentials against the correct password. @type password: L{bytes} @param password: The correct, plaintext password against which to check. @rtype: C{bool} or L{Deferred} @return: C{True} if the credentials represented by this object match the given password, C{False} if they do not, or a L{Deferred} which will be called back with one of these values. Nrpasswordrrr checkPasswordErz%IUsernameHashedPassword.checkPasswordNrrrrr#rrrrr7s rc@r)IUsernamePasswordaK I encapsulate a username and a plaintext password. This encapsulates the case where the password received over the network has been hashed with the identity function (That is, not at all). The CredentialsChecker may store the password in whatever format it desires, it need only transform the stored password in a similar way before performing the comparison. @type username: L{bytes} @ivar username: The username associated with these credentials. @type password: L{bytes} @ivar password: The password associated with these credentials. cCrr rr!rrrr#erzIUsernamePassword.checkPasswordNr$rrrrr%Ts r%c@r) IAnonymouszs I am an explicitly anonymous request for access. @see: L{twisted.cred.checkers.AllowAnonymousAccess} Nrrrrrr&trr&c@s(eZdZdZddZddZddZdS) DigestedCredentialsz? Yet Another Simple HTTP Digest authentication scheme. cCs||_||_||_||_dSN)usernamemethodrealmfields)selfr)r*r+r,rrr__init__s zDigestedCredentials.__init__c Cs|jd}|jd}|jd}|jd}|jd}|jdd}|jdd }tt||j|j|||t||j||d |||||} | |kS) a Verify that the credentials represented by this object agree with the given plaintext C{password} by hashing C{password} in the same way the response hash represented by this object was generated and comparing the results. responseurinoncecnoncenc algorithmmd5qopauthN) r,getlowerr rr)r+rr*) r-r"r/r0r1r2r3algor6expectedrrrr#s"      z!DigestedCredentials.checkPasswordc Cs|jd}|jd}|jd}|jd}|jd}|jdd}|jdd }tt|d d d |||d t||j||d |||||} | |kS) a4 Verify that the credentials represented by this object agree with the credentials represented by the I{H(A1)} given in C{digestHash}. @param digestHash: A precomputed H(A1) value based on the username, realm, and password associate with this credentials object. r/r0r1r2r3r4r5r6r7N)preHA1)r,r8r9r rrr*) r-rr/r0r1r2r3r:r6r;rrrrs"      zDigestedCredentials.checkHashN)rrrrr.r#rrrrrr'|s  r'c@sZeZdZdZedZdZdZddZ ddZ d d Z d d Z d dZ ddZddZdS)DigestCredentialFactoryar Support for RFC2617 HTTP Digest Authentication @cvar CHALLENGE_LIFETIME_SECS: The number of seconds for which an opaque should be valid. @type privateKey: L{bytes} @ivar privateKey: A random string used for generating the secure opaque. @type algorithm: L{bytes} @param algorithm: Case insensitive string specifying the hash algorithm to use. Must be either C{'md5'} or C{'sha'}. C{'md5-sess'} is B{not} supported. @type authenticationRealm: L{bytes} @param authenticationRealm: case sensitive string that specifies the realm portion of the challenge s ([^= ]+)=(?:"([^"]*)"|([^,]+)),?isdigestcCs||_||_td|_dS)N )r4authenticationRealmr privateKey)r-r4r?rrrr.sz DigestCredentialFactory.__init__cCs(|}|||}||d|j|jdS)a Generate the challenge for use in the WWW-Authenticate header. @param address: The client address to which this challenge is being sent. @return: The L{dict} that can be used to generate a WWW-Authenticate header. r7)r1opaquer6r4r+)_generateNonce_generateOpaquer4r?)r-addresscorrr getChallenges z$DigestCredentialFactory.getChallengecCs ttdS)z Create a random value suitable for use as the nonce parameter of a WWW-Authenticate challenge. @rtype: L{bytes} r>)rr r-rrrrBs z&DigestCredentialFactory._generateNoncecCstS)z Parameterize the time based seed used in C{_generateOpaque} so we can deterministically unittest it's behavior. )timerHrrr_getTimesz DigestCredentialFactory._getTimecCsvdt|f}|sd}n t|tr|d}d|||f}tt||j }t |}d|| ddfS)z Generate an opaque to be returned to the client. This is a unique string that can be returned to us and verified. s%dascii,- ) intrJ isinstancestrencodejoinrrr@digestbase64 b64encodereplace)r-r1clientipnowkeyrUekeyrrrrC s   z'DigestCredentialFactory._generateOpaquec Cs|d}t|dkrtd|sd}n t|tr|d}t|d}|d}t|dkr6td|d |krAtd |d|krLtd zt |d}Wn t y`td wt | |t j krqtd tt||j}||d krtddS)a Given the opaque and nonce from the request, as well as the client IP that made the request, verify that the opaque was generated by us. And that it's not too old. @param opaque: The opaque value from the Digest response @param nonce: The nonce value from the Digest response @param clientip: The remote IP address of the client making the request or L{None} if the request was submitted over a channel where this does not make sense. @return: C{True} if the opaque was successfully verified. @raise error.LoginFailed: if C{opaque} could not be parsed or contained the wrong values. rNz&Invalid response, invalid opaque valuerKrLrMrz2Invalid response, incompatible opaque/nonce valuesz3Invalid response, incompatible opaque/client valuesz,Invalid response, invalid opaque/time valuesz3Invalid response, incompatible opaque/nonce too oldT)splitlenr LoginFailedrQrRrSrV b64decoderP ValueErrorrJr=CHALLENGE_LIFETIME_SECSrrr@rU) r-rAr1rY opaquePartsr[keyPartswhenrUrrr _verifyOpaque sD              z%DigestCredentialFactory._verifyOpaquec Csd|}|j|}i}|D]\}}}|p|} | |t|<q|d} | s1tdd|vr:tdd|vrCtd| |d|d|rXt | ||j |SdS) a Decode the given response and attempt to generate a L{DigestedCredentials} from it. @type response: L{bytes} @param response: A string of comma separated key=value pairs @type method: L{bytes} @param method: The action requested to which this response is addressed (GET, POST, INVITE, OPTIONS, etc). @type host: L{bytes} @param host: The address the request was sent from. @raise error.LoginFailed: If the response does not contain a username, a nonce, an opaque, or if the opaque is invalid. @return: L{DigestedCredentials}  r)z$Invalid response, no username given.rAz"Invalid response, no opaque given.r1z!Invalid response, no nonce given.N) rT splitlines _parsepartsfindallstripr r8rrbrir'r?) r-r/r*hostpartsauthr[barequotedvaluer)rrrdecodeas       zDigestCredentialFactory.decodeN)rrrrrecompilerlreschemer.rGrBrJrCrirurrrrr=s   Ar=c@sFeZdZdZdZdZdZdddZddZdd Z d d Z d d Z dS)CramMD5Credentialsas An encapsulation of some CramMD5 hashed credentials. @ivar challenge: The challenge to be sent to the client. @type challenge: L{bytes} @ivar response: The hashed response from the client. @type response: L{bytes} @ivar username: The username from the response from the client. @type username: L{bytes} or L{None} if not yet provided. NrKcCs ||_dSr()ro)r-rorrrr. zCramMD5Credentials.__init__cCsH|jr|jStd}t}td|||jrt|jndf|_|jS)Niz <%d.%d@%s>) challengerandom randrangerIr ror )r-rtrrrrGs zCramMD5Credentials.getChallengecCs|dd\|_|_dS)Nr^)r`r)r/)r-r/rrr setResponseszCramMD5Credentials.setResponsecCr)NFrrHrrrmoreChallengessz!CramMD5Credentials.moreChallengescCs$ttj||jtd}||jkS)N) digestmod)rhmacHMACr{rrUr/)r-r"verifyrrrr#s z CramMD5Credentials.checkPasswordr() rrrrr)r{r/r.rGrrr#rrrrrys   ryc@s4eZdZeedddddddddZd d Zd S) UsernameHashedPasswordTwistedr]rz6Use twisted.cred.credentials.UsernamePassword instead.ztwisted.cred.credentialscC||_||_dSr()r)hashed)r-r)rrrrr. zUsernameHashedPassword.__init__cC |j|kSr()rr-r"rrrr#rzz$UsernameHashedPassword.checkPasswordN)rrrr rr.r#rrrrrs  rc@seZdZddZddZdS)UsernamePasswordcCrr()r)r")r-r)r"rrrr.rzUsernamePassword.__init__cCrr(r!rrrrr#rzzUsernamePassword.checkPasswordN)rrrr.r#rrrrrs rc@s eZdZdS) AnonymousN)rrrrrrrrsrc@r)ISSHPrivateKeyaj L{ISSHPrivateKey} credentials encapsulate an SSH public key to be checked against a user's private key. @ivar username: The username associated with these credentials. @type username: L{bytes} @ivar algName: The algorithm name for the blob. @type algName: L{bytes} @ivar blob: The public key blob as sent by the client. @type blob: L{bytes} @ivar sigData: The data the signature was made from. @type sigData: L{bytes} @ivar signature: The signed data. This is checked to verify that the user owns the private key. @type signature: L{bytes} or L{None} Nrrrrrrrrc@seZdZddZdS) SSHPrivateKeycCs"||_||_||_||_||_dSr()r)algNameblobsigData signature)r-r)rrrrrrrr.s  zSSHPrivateKey.__init__N)rrrr.rrrrrs r))rrVrr|rvrIbinasciirhashlibrzope.interfacerr twisted.credrtwisted.cred._digestrrr twisted.python.compatr r twisted.python.deprecater twisted.python.randbytesr twisted.python.versionsrrrrr%r&r'r=ryrrrrrrrrrsF        CL0