zmc
2023-08-08 e792e9a60d958b93aef96050644f369feb25d61b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
U
£ý°dßMã@sÜdZddlZddlmZmZddlmZmZddlm    Z    m
Z
m Z m Z m Z ddlmZddlmZmZdd    lmZdd
lmZz ddlZWnek
r¦ed ƒd‚YnXdd lmZmZd dlmZdZGdd„deƒZ dS)z LDAP SASL Authentication Plugin.éN)Ú    b64decodeÚ    b64encode)Úsha1Úsha256)ÚAnyÚCallableÚListÚOptionalÚTuple)Úuuid4é)ÚInterfaceErrorÚProgrammingError)Úlogger)Ú
StrOrByteszwModule gssapi is required for GSSAPI authentication mechanism but was not found. Unable to authenticate with the server)Únormalize_unicode_stringÚ"validate_normalized_unicode_stringé)ÚBaseAuthPluginÚMySQLLdapSaslPasswordAuthPluginc@sìeZdZUdZdddgZeeed<dZe    ed<dZ
eed    <e Z e ed
<d Zeeed <d Zeed <d Zeeed<d Zeeed<dZeed<d Zeeed<d Zeejed<d Zejed<d Zeeed<d Zeeed<ee e e dœdd„ƒZ!e e e dœdd„Z"ee ee dœdd„Z#eeed œd!d"„ƒZ$e d#œd$d%„Z%ee d#œd&d'„Z&ee e'ee e    fd(œd)d*„Z(e e d+œd,d-„Z)d?eeee d.œd/d0„Z*e d#œd1d2„Z+e d d3œd4d5„Z,e e d6œd7d8„Z-e.e    d9œd:d;„Z/e.e    d<œd=d>„Z0d S)@ra5Class implementing the MySQL ldap sasl authentication plugin.
 
    The MySQL's ldap sasl authentication plugin support two authentication
    methods SCRAM-SHA-1 and GSSAPI (using Kerberos). This implementation only
    support SCRAM-SHA-1 and SCRAM-SHA-256.
 
    SCRAM-SHA-1 amd SCRAM-SHA-256
        This method requires 2 messages from client and 2 responses from
        server.
 
        The first message from client will be generated by prepare_password(),
        after receive the response from the server, it is required that this
        response is passed back to auth_continue() which will return the
        second message from the client. After send this second message to the
        server, the second server respond needs to be passed to auth_finalize()
        to finish the authentication process.
    z SCRAM-SHA-1z SCRAM-SHA-256ZGSSAPIÚsasl_mechanismsFÚ requires_sslZauthentication_ldap_sasl_clientÚ plugin_nameÚdef_digest_modeNÚ client_nonceÚ client_saltÚ server_saltÚkrb_service_principalrÚ
iterationsÚserver_auth_varÚ target_nameÚctxÚ servers_firstÚ server_nonce)Úbytes1Úbytes2ÚreturncCstdd„t||ƒDƒƒS)NcSsg|]\}}||A‘qS©r')Ú.0Zb1Zb2r'r'únd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\mysql/connector/plugins/authentication_ldap_sasl_client.pyÚ
<listcomp>asz8MySQLLdapSaslPasswordAuthPlugin._xor.<locals>.<listcomp>)ÚbytesÚzip)r$r%r'r'r)Ú_xor_sz$MySQLLdapSaslPasswordAuthPlugin._xor)ÚpasswordÚsaltr&cCst |||j¡}| ¡S)N)ÚhmacÚnewrÚdigest)Úselfr.r/Z digest_makerr'r'r)Ú_hmaccsz%MySQLLdapSaslPasswordAuthPlugin._hmac)r.r/Úcountr&cCsJ| ¡}| ||d¡}|}t|dƒD]}| ||¡}| ||¡}q(|S)zPrepares Hi
        Hi(password, salt, iterations) where Hi(p,s,i) is defined as
        PBKDF2 (HMAC, p, s, i, output length of H).
        sr)Úencoder4Úranger-)r3r.r/r5ÚpwÚhiZauxÚ_r'r'r)Ú_higs z#MySQLLdapSaslPasswordAuthPlugin._hi)Ústringr&cCs*t|ƒ}t|ƒ}|dk    r&td|›ƒ‚|S)Nz broken_rule: )Ú    norm_ustrÚ
valid_normr )r<Znorm_strZ broken_ruler'r'r)Ú
_normalizets
z*MySQLLdapSaslPasswordAuthPlugin._normalize)r&cCsHd}ttƒƒ dd¡|_|j| |j¡|jd}t|tƒrD| d¡}|S)aqThis method generates the first message to the server to start the
 
        The client-first message consists of a gs2-header,
        the desired username, and a randomly generated client nonce cnonce.
 
        The first message from the server has the form:
            b'n,a=<user_name>,n=<user_name>,r=<client_nonce>
 
        Returns client's first message
        z.n,a={user_name},n={user_name},r={client_nonce}ú-Ú)Ú    user_namerÚutf8)    Ústrr ÚreplacerÚformatr?Ú    _usernameÚ
isinstancer6)r3Z
cfm_fprnatZcfmr'r'r)Ú_first_message|s 
þ
 
z.MySQLLdapSaslPasswordAuthPlugin._first_messagec
Csütjjj|j d¡tjjd}zpt ¡}t     
d¡z
|j WnNtjj j k
rŠ}z*t     d|¡| |¡td|›ƒ|‚W5d}~XYnXWn¬tjjjk
r:}z†|js¾td|›ƒ|‚z0t     
d¡tjj||j d¡d    d
}|d }Wn:tjjjk
r(}ztd |›ƒ|‚W5d}~XYnXW5d}~XYnXtjjtjjtjjf}|jrb|j}nd }t     
d|¡tj|tjjd}||_tj||t|ƒd    d|_ z|j  !¡}    Wn:tjjjk
rê}ztd|›ƒ|‚W5d}~XYnXt     
d|    ¡|    S)z–Get a TGT Authentication request and initiates security context.
 
        This method will contact the Kerberos KDC in order of obtain a TGT.
        rC)Z    name_typezE# Stored credentials found, if password was given it will be ignored.z Credentials has expired: %szCredentials has expired: Nz-Unable to retrieve stored credentials error: z5# Attempt to retrieve credentials with given passwordZinitiate)Úusagerz8Unable to retrieve credentials with the given password: z ldap/ldapauthz# service principal: %s)ÚnameÚcredsÚflagsrJz%Unable to initiate security context: z# initial client token: %s)"ÚgssapiÚrawÚnamesÚ import_namerGr6ZNameTypeÚuserZ CredentialsrÚdebugZlifetimeÚ
exceptionsZExpiredCredentialsErrorÚwarningÚacquirer ÚmiscZGSSErrorÚ    _passwordZacquire_cred_with_passwordrZRequirementFlagZmutual_authenticationZextended_errorZdelegate_to_peerrÚNameZkerberos_principalr ÚSecurityContextÚsumr!Ústep)
r3rBÚcredÚerrZacquire_cred_resultZerr2Zflags_lZservice_principalZservkZinitial_client_tokenr'r'r)Ú_first_message_krb’sz
ÿÿ
 
&ÿþ
 
ý ÿþ&ý ÿÿ" z2MySQLLdapSaslPasswordAuthPlugin._first_message_krb)Útgt_auth_challenger&cCs@t d|¡|j |¡}t d|¡t d|jj¡||jjfS)a Continue with the Kerberos TGT service request.
 
        With the TGT authentication service given response generate a TGT
        service request. This method must be invoked sequentially (in a loop)
        until the security context is completed and an empty response needs to
        be send to acknowledge the server.
 
        Args:
            tgt_auth_challenge the challenge for the negotiation.
 
        Returns: tuple (bytearray TGS service request,
                        bool True if context is completed otherwise False).
        ztgt_auth challenge: %sz# context step response: %sz# context completed?: %s)rrSr!r\Úcomplete)r3r`Úrespr'r'r)Úauth_continue_krbÛs
   z1MySQLLdapSaslPasswordAuthPlugin.auth_continue_krb)Úmessager&c
CsÒ|jjstdƒ‚t d|¡t d|jj¡z|j |¡}t d|¡Wn8tjj    j
k
r€}zt d|›ƒ|‚W5d}~XYnXt d|¡t dƒ}t d    |¡|jj |d
d }t d |d t|d ƒ¡|jS)aPAccept handshake and generate closing handshake message for server.
 
        This method verifies the server authenticity from the given message
        and included signature and generates the closing handshake for the
        server.
 
        When this method is invoked the security context is already established
        and the client and server can send GSSAPI formated secure messages.
 
        To finish the authentication handshake the server sends a message
        with the security layer availability and the maximum buffer size.
 
        Since the connector only uses the GSSAPI authentication mechanism to
        authenticate the user with the server, the server will verify clients
        message signature and terminate the GSSAPI authentication and send two
        messages; an authentication acceptance b'' and a
        OK packet (that must be received after sent the returned message from
        this method).
 
        Args:
            message a wrapped hssapi message from the server.
 
        Returns: bytearray closing handshake message to be send to the server.
        z"Security context is not completed.z# servers message: %sz# GSSAPI flags in use: %sz# unwraped: %sz!Unable to unwrap server message: Nz# unwrapped server message: %ssz# message response: %sF)Zencryptz*# wrapped message response: %s, length: %dr)r!rarrrSZ actual_flagsÚunwraprNrOrTZ BadMICErrorr Ú    bytearrayÚwrapÚlenrd)r3rdZunwrapedr^ÚresponseZwrapedr'r'r)Úauth_accept_close_handshakeós&  "  
ýz;MySQLLdapSaslPasswordAuthPlugin.auth_accept_close_handshake)Ú    auth_datar&cCsŠ|}|j ¡}||_t d|¡||jkr`d |jdd…¡}td|›d|›d|jd›dƒ‚d    |jkrr| ¡S|jd
kr‚t    |_
|  ¡S) z„This method will prepare the fist message to the server.
 
        Returns bytes to send to the server as the first message.
        z read_method_name_from_server: %sz", "Néÿÿÿÿz The sasl authentication method "z4" requested from the server is not supported. Only "z" and "z" are supportedsGSSAPIs SCRAM-SHA-256) Ú
_auth_dataÚdecoderrrSrÚjoinr r_rrrI)r3rkrZauth_mechanismZauth_mechanismsr'r'r)Ú auth_response's
 
ÿ
 
z-MySQLLdapSaslPasswordAuthPlugin.auth_responsec CsÐ|jstdƒ‚| |j¡}| |t|jƒ|j¡}t     dt
|ƒ  ¡¡|  |d¡}t     dt
|ƒ  ¡¡|  |¡ ¡}t     dt
|ƒ  ¡¡|  |d¡}t     dt
|ƒ  ¡¡d d    | |j¡›d
|j›g¡}t     d |¡t
d | |j¡›d ¡ƒ  ¡}d ||jd |›d
|j›g¡}t     d|¡|  || ¡¡}    t     dt
|    ƒ  ¡¡| ||    ¡}
t     dt
|
ƒ  ¡¡t
|  || ¡¡ƒ  ¡|_t     d|j¡d d |›d
|j›dt
|
ƒ  ¡›g¡} t     d| ¡|  ¡S)a¥This method generates the second message to the server
 
        Second message consist on the concatenation of the client and the
        server nonce, and cproof.
 
        c=<n,a=<user_name>>,r=<server_nonce>,p=<client_proof>
        where:
            <client_proof>: xor(<client_key>, <client_signature>)
 
            <client_key>: hmac(salted_password, b"Client Key")
            <client_signature>: hmac(<stored_key>, <auth_msg>)
            <stored_key>: h(<client_key>)
            <auth_msg>: <client_first_no_header>,<servers_first>,
                        c=<client_header>,r=<server_nonce>
            <client_first_no_header>: n=<username>r=<client_nonce>
        z"Missing authentication data (seed)zsalted_password: %ss
Client Keyzclient_key: %szstored_key: %ss
Server Keyzserver_key: %sú,zn=úr=zclient_first_no_header: %szn,a=zc=z auth_msg: %szclient_signature: %szclient_proof: %szserver_auth_var: %szp=zsecond_message: %s)rmr r?rXr;rrrrrSrrnr4rr2rorGrr6r"r#r-r) r3ZpasswZsalted_passwordZ
client_keyZ
stored_keyZ
server_keyZclient_first_no_headerZ client_headerZauth_msgZclient_signatureZ client_proofÚmsgr'r'r)Ú_second_messageCsX   
þÿ ÿ
üÿ  ÿ
 
ýÿ z/MySQLLdapSaslPasswordAuthPlugin._second_message)r"r&c
CsR|rt|ttfƒs$tdt|ƒ›ƒ‚z"| ¡}||_| d¡\}}}Wn$tk
rjtd|›ƒd‚YnX|     d¡rŠ|     d¡rŠ|     d¡s˜td|›ƒ‚|j
|krÀ|dd…|_ t   d    |j ¡ntd
|›ƒ‚|dd…|_t   d |jt|jƒ¡z&|dd…}t   d |¡t|ƒ|_Wn4tk
rL}ztd |›ƒ|‚W5d}~XYnXdS)zâValidates first message from the server.
 
        Extracts the server's salt and iterations from the servers 1st response.
        First message from the server is in the form:
            <server_salt>,i=<iterations>
        zUnexpected server message: rqNrrzs=zi=z$Incomplete reponse from the server: r zserver_nonce: %sz:Unable to authenticate response: response not well formed zserver_salt: %s length: %sziterations: %sz-Unable to authenticate: iterations not found )rHrfr+r Úreprrnr"ÚsplitÚ
ValueErrorÚ
startswithrr#rrSrrhÚintrÚ    Exception)r3r"Zservers_first_strZr_server_nonceZs_saltZ    i_counterr^r'r'r)Ú_validate_first_reponsesVÿþÿþýÿ
ÿý  ÿþz7MySQLLdapSaslPasswordAuthPlugin._validate_first_reponse)Úservers_first_responser&cCs| |¡| ¡S)zwreturn the second message from the client.
 
        Returns bytes to send to the server as the second message.
        )r{rt)r3r|r'r'r)Ú auth_continue¿s
z-MySQLLdapSaslPasswordAuthPlugin.auth_continue)Úservers_secondr&cCsR|r$t|tƒr$t|ƒdks$| d¡s,tdƒ‚|dd… ¡}t d|¡|j|kS)aXValidates second message from the server.
 
        The client and the server prove to each other they have the same Auth
        variable.
 
        The second message from the server consist of the server's proof:
            server_proof = HMAC(<server_key>, <auth_msg>)
            where:
                <server_key>: hmac(<salted_password>, b"Server Key")
                <auth_msg>: <client_first_no_header>,<servers_first>,
                            c=<client_header>,r=<server_nonce>
 
        Our server_proof must be equal to the Auth variable send on this second
        response.
        r sv=z'The server's proof is not well formatedNzserver auth variable: %s)    rHrfrhrxr rnrrSr)r3r~Z
server_varr'r'r)Ú_validate_second_reponseÇsÿþ
ýü z8MySQLLdapSaslPasswordAuthPlugin._validate_second_reponse)Úservers_second_responser&cCs| |¡stdƒ‚dS)zºfinalize the authentication process.
 
        Raises InterfaceError if the ervers_second_response is invalid.
 
        Returns True in successful authentication False otherwise.
        z6Authentication failed: Unable to proof server identityT)rr )r3r€r'r'r)Ú auth_finalizeâs
 
ÿz-MySQLLdapSaslPasswordAuthPlugin.auth_finalize)N)1Ú__name__Ú
__module__Ú __qualname__Ú__doc__rrrDÚ__annotations__rÚboolrrrrrr    rrrrrrryrr rNrYr!rZr"r#Ú staticmethodr+r-r4r;r?rIr_r
rcrjrprtr{r}rfrrr'r'r'r)r=sJ
      Jþ 6þý L0)!r…r0Úbase64rrÚhashlibrrÚtypingrrrr    r
Úuuidr Úerrorsr rrÚtypesrrNÚ ImportErrorÚutilsrr=rr>rArZAUTHENTICATION_PLUGIN_CLASSrr'r'r'r)Ú<module>s(    ÿü