o SbM @s~UdZddlZddlZddlZddlZddlZddlmZmZddl m Z ddl m Z m Z ddlmZddlmZddlmZdd lmZdd lmZmZdd lmZd Zd ZzddlZee e!ej"#ddddkrod ZWne$yzddlZWn e$yd ZYnwYnwe%gdZ& Gddde'Z(e dgdZ) e dgdZ* e ddgZ+ ddZ,ddZ-ddZ.d d!Z/d"d#Z0d$d%Z1d&d'Z2d(d)Z3d*d+Z4d,d-Z5d.d/Z6d0d1Z7d2d3Z8e4e7e6ee5ej9e0d4d5ej9e0d6d5e8dZ:e e;e feGdd4d5ej9e>d6d5ej9e>d6d5d>Z@e e;e fes rMongoCredential) mechanismsourceusernamepasswordmechanism_propertiescacheGSSAPIProperties service_namecanonicalize_host_name service_realm_AWSPropertiesaws_session_tokencCs|dvr|durtd|f|dkrF|dur|dkrtd|di}|dd }|d d }|d } t||| d } t|d||| dS|dkrg|durRtd|dur^|dkr^tdt|d|dddS|dkr|durw|durwtd|dur|dkrtd|di}|d} t| d} t|d||| dS|dkr|p|pd} t|| ||ddS|p|pd} |durtdt|| ||dtS)z8Build and return a mechanism specific credentials tuple.)rrNz%s requires a username.r $externalz:authentication source must be $external or None for GSSAPIZauthmechanismpropertiesZ SERVICE_NAMEZmongodbZCANONICALIZE_HOST_NAMEFZ SERVICE_REALMr9rz+Passwords are not supported by MONGODB-X509z@authentication source must be $external or None for MONGODB-X509rz;username without a password is not supported by MONGODB-AWSz?authentication source must be $external or None for MONGODB-AWSZAWS_SESSION_TOKEN)r>rZadminzA password is required.)r ValueErrorgetr8r1r=r)Zmechr3userpasswdextraZdatabase propertiesr: canonicalizer<propsr>Z aws_propsZsource_databaserrr_build_credentials_tuplefsN         rHcCsdddt||DS)z+XOR two byte strings together (python 3.x).cSsg|] \}}t||AgqSr)bytes).0xyrrr sz_xor..)joinzip)Zfirsecrrr_xorsrRcCstdd|dDS)z-Split a scram response into key, value pairs.css|] }|ddVqdS)=N)split)rKitemrrr sz(_parse_scram_response..,)dictrU)responserrr_parse_scram_responsesr[cCsr|j}|ddddd}ttd}d|d|}td d |fd td |fd dddifg}|||fS)Nutf-8rSs=3DrXs=2C sn=s,r=Z saslStartrTr2payloadsn,,Z autoAuthorizerToptionsZskipEmptyExchangeT)r4encodereplacerosurandomr r) credentialsr2r4rBnonce first_barecmdrrr_authenticate_scram_starts  rjc Csd|j}|dkrd}tj}t|jd}nd}tj}t||jd}|j}|j }t j } |j } | r>| r>| j\} } | j} nt||\} } }|||} | d}t|}t|d}|dkrbtd|d }|d }|| sstd d |}|jr|j\}}}}nd \}}}}|r||ks||krt||t||}| |d|}| |d|}||||f|_||}d| ||f}| |||}dtt||}d||f}t| |||}tdd| dfdt|fg}|||} t| d}t |d|s td| ds.tdd| dfdtdfg}|||} | ds0tddSdS)zAuthenticate using SCRAM.rsha256r\sha1r_iiz+Server returned an invalid iteration count.srz!Server returned an invalid nonce.s c=biws,r=)NNNNs Client Keys Server KeyrXsp=Z saslContinuerTconversationIdvz%Server returned an invalid signature.donerIz%SASL conversation failed to complete.N) r4hashlibrkr r5rbrl_password_digestr3r7hmacHMACauth_ctxspeculate_succeeded scram_dataspeculative_authenticaterjcommandr[intr startswithr pbkdf2_hmacrdigestrOrrRr rcompare_digest) rf sock_infor2r4r digestmodrr3r7_hmacctxrgrhresriZ server_firstparsedZ iterationssaltZrnonceZ without_proofZ client_keyZ server_keyZcsaltZ citerationsZ salted_passZ stored_keyZauth_msgZ client_sigZ client_proofZ client_finalZ server_sigrrr_authenticate_scrams~                 rcCsdt|ts tdt|dkrtdt|tstdt}d||f}||d| S)z0Get a password digest to use for authentication.z#password must be an instance of strrzpassword can't be emptyz#username must be an instance of strz %s:mongo:%sr\) r$str TypeErrorlenr@rtmd5updaterb hexdigest)r4r5md5hashrrrrrus    rucCs8t||}t}d|||f}||d|S)z*Get an auth key to use for authentication.z%s%s%sr\)rurtrrrbr)rgr4r5rrrrrr _auth_keys rcCsbt|dddtjtjd\}}}}}z t|tj}Wntjy*|YSw|dS)z2Canonicalize hostname following MIT-krb5 behavior.Nr)socket getaddrinfo IPPROTO_TCP AI_CANONNAME getnameinfo NI_NAMEREQDgaierrorlower)hostnameafsocktypeproto canonnamesockaddrnamerrr_canonicalize_hostnames  rc Csxtstdz |j}|j}|j}|jd}|jrt|}|jd|}|j dur0|d|j }|durmt rMd t |t |f}t j||t jd\}} n*d|vrZ|dd\} } n|d} } t j|t j| | |d\}} n t j|t jd\}} |t jkrtd zt | d dkrtd t | } td d d| fdg} |d| }tdD]5}t | t|d}|dkrtd t | pd } tdd|dfd| fg} |d| }|t jkrnqtdt | t|ddkrtdt | t | |dkrtdt | } tdd|dfd| fg} |d| Wt | WdSt | wt jy;}ztt|d}~ww)zAuthenticate using GSSAPI.zEThe "kerberos" module must be installed to use GSSAPI authentication.r@N:)gssflagsrT)rrBdomainr5z&Kerberos context failed to initialize.z*Unknown kerberos failure in step function.r^)r2rr_r`r? rprqz+Kerberos authentication failed to complete.z0Unknown kerberos failure during GSS_Unwrap step.z.Unknown kerberos failure during GSS_Wrap step.) HAVE_KERBEROSr r4r5r6addressr;rr:r<_USE_PRINCIPALrOrkerberosZauthGSSClientInitZGSS_C_MUTUAL_FLAGrUZAUTH_GSS_COMPLETEr ZauthGSSClientStepZauthGSSClientResponser r|rangerZauthGSSClientUnwrapZauthGSSClientWrapZauthGSSClientCleanZKrbError)rfrr4r5rGhostZserviceZ principalresultrrBrr_rirZ_excrrr_authenticate_gssapi-s               rcCsL|j}|j}|j}d||fd}tdddt|fdg}|||dS)z(Authenticate using SASL PLAIN (RFC 4616)z%s%sr\r^)r2rr_r`N)r3r4r5rbr rr|)rfrr3r4r5r_rirrr_authenticate_plains rcCs2|j}|r |r dSt|}|d|dS)z Authenticate using MONGODB-X509.Nr?)rxry _X509Contextspeculate_commandr|)rfrrrirrr_authenticate_x509s   rc Csb|j}|j}|j}||ddi}|d}t|||}tdd|fd|fd|fg}|||dS)zAuthenticate using MONGODB-CR.ZgetnoncerTrg authenticaterTrBkeyN)r3r4r5r|rr ) rfrr3r4r5rZrgrqueryrrr_authenticate_mongo_crs rcCs||jdkr8|jr |j}n|j}|}|d|j|d<|j||dddg}d|vr2t||dSt||dSt||dS)NrZsaslSupportedMechsF)Zpublish_eventsrr)Zmax_wire_versionZnegotiated_mechsr3Z hello_cmdr4r|rAr)rfrZmechsr3rirrr_authenticate_defaults    rr)r2r _AUTH_MAPc@s8eZdZddZeddZddZddZd d Zd S) _AuthContextcCs||_d|_dSr)rfr{)rrfrrrr s z_AuthContext.__init__cCst|j}|r ||SdSr)_SPECULATIVE_AUTH_MAPrAr2)credsZspec_clsrrrfrom_credentialss z_AuthContext.from_credentialscCstr)NotImplementedErrorrrrrrsz_AuthContext.speculate_commandcCs |j|_dSr)r{)rZhellorrrparse_responses z_AuthContext.parse_responsecCs t|jSr)boolr{rrrrryr!z _AuthContext.speculate_succeededN) r,r-r.r staticmethodrrrryrrrrrs  rcs$eZdZfddZddZZS) _ScramContextcs tt||d|_||_dSr)superrr rzr2)rrfr2 __class__rrr s z_ScramContext.__init__cCs.t|j|j\}}}|jj|d<||f|_|S)Ndb)rjrfr2r3rz)rrgrhrirrrrs  z_ScramContext.speculate_command)r,r-r.r r __classcell__rrrrrs rc@seZdZddZdS)rcCs(tddg}|jjdur|jj|d<|S)Nr)r2rrB)r rfr4)rrirrrrs   z_X509Context.speculate_commandN)r,r-r.rrrrrrs r)rrrrrcCs|j}t|}|||dS)zAuthenticate sock_info.N)r2r)rfrr2Z auth_funcrrrr!sr)B__doc__ functoolsrtrvrdrbase64rr collectionsrtypingrr urllib.parserZ bson.binaryrZbson.sonr Zpymongo.auth_awsr Zpymongo.errorsr r Zpymongo.saslprepr rrZ winkerberosrtuplemapr} __version__rU ImportError frozensetZ MECHANISMSobjectrr1r8r=rHrRr[rjrrurrrrrrrpartialrr__annotations__rrrrrrrrrs      "     0T u