
    g9                        d Z ddlmZ ddlmZmZmZmZ ddlm	Z	m
Z
mZ ddlmZ ddlmZmZ ddlmZmZmZmZmZmZmZmZ dd	lmZ erdd
lmZ  G d d          ZdS )z5Implementing support for MySQL Authentication Plugins    )annotations)TYPE_CHECKINGAnyDictOptional   )InterfaceErrorNotSupportedErrorget_exception)logger)MySQLAuthPluginget_auth_plugin)AUTH_SWITCH_STATUSDEFAULT_CHARSET_IDDEFAULT_MAX_ALLOWED_PACKET
ERR_STATUSEXCHANGE_FURTHER_STATUS
MFA_STATUS	OK_STATUSMySQLProtocol)HandShakeType)MySQLSocketc                      e Zd ZdZd5dZed6d            Zed7d            Zd8d
Ze	de
fd9dZ	 	 	 d:d;dZd<d"Zd<d#Zd$d$d$d$de	de
dddd%ddfd=d4ZdS )>MySQLAuthenticatorz$Implements the authentication phase.returnNonec                Z    d| _         i | _        i | _        d| _        d| _        d| _        dS )zConstructor. FN)	_username
_passwords_plugin_config_ssl_enabled_auth_strategy_auth_plugin_classselfs    j/var/www/html/nodeJS/PythonScripts/venv3.11/lib/python3.11/site-packages/mysql/connector/authentication.py__init__zMySQLAuthenticator.__init__8   s6     *,.0"'9=15    boolc                    | j         S )z&Signals whether or not SSL is enabled.)r"   r%   s    r'   ssl_enabledzMySQLAuthenticator.ssl_enabledA   s       r)   Dict[str, Any]c                    | j         S )a  Custom arguments that are being provided to the authentication plugin when called.

        The parameters defined here will override the ones defined in the
        auth plugin itself.

        The plugin config is a read-only property - the plugin configuration
        provided when invoking `authenticate()` is recorded and can be queried
        by accessing this property.

        Returns:
            dict: The latest plugin configuration provided when invoking
                  `authenticate()`.
        )r!   r%   s    r'   plugin_configz MySQLAuthenticator.plugin_configF   s     ""r)   configc                :    | j                             |           dS )z,Update the 'plugin_config' instance variableN)r!   update)r&   r0   s     r'   update_plugin_configz'MySQLAuthenticator.update_plugin_configW   s    ""6*****r)   r   sockr   hoststrssl_optionsOptional[Dict[str, Any]]charsetintclient_flagsmax_allowed_packetbytesc                ^   |i }t          j        |||          }|                    |           t          j        d           |                    |                    d          |                    d          |                    d          |                    dd          |                    d	d          |                    d
          |                    d                    }t          j        d           |                    ||           t          j        d           d| _        |S )a  Sets up an SSL communication channel.

        Args:
            sock: Pointer to the socket connection.
            host: Server host name.
            ssl_options: SSL and TLS connection options (see
                         `network.MySQLSocket.build_ssl_context`).
            charset: Client charset (see [1]), only the lower 8-bits.
            client_flags: Integer representing client capabilities flags.
            max_allowed_packet: Maximum packet size.

        Returns:
            ssl_request_payload: Payload used to carry out SSL authentication.

        References:
            [1]: https://dev.mysql.com/doc/dev/mysql-server/latest/                page_protocol_basic_character_set.html#a_protocol_character_set
        N)r9   r;   r<   zBuilding SSL contextcacertkeyverify_certFverify_identitytls_versionstls_ciphersuites)ssl_cassl_certssl_keyssl_verify_certssl_verify_identityrD   tls_cipher_suiteszSwitching to SSLzSSL has been enabledT)	r   make_auth_sslsendr   debugbuild_ssl_contextgetswitch_to_sslr"   )	r&   r4   r5   r7   r9   r;   r<   ssl_request_payloadssl_contexts	            r'   	setup_sslzMySQLAuthenticator.setup_ssl[   s)   6 K ,9%1
 
 

 			%&&&+,,,,,??4(( __V,,OOE**'OOM5AA +0A5 I I$88)oo.@AA - 
 
 	'(((;---+,,, ""r)   Nr   new_strategy_namestrategy_classOptional[str]usernamepassword_factorc                    || j         }|| j        }t          j        d|            t	          ||          || j                            |d          | j                  | _        dS )a  Switches the authorization plugin.

        Args:
            new_strategy_name: New authorization plugin name to switch to.
            strategy_class: New authorization plugin class to switch to
                            (has higher precedence than the authorization plugin name).
            username: Username to be used - if not defined, the username
                      provided when `authentication()` was invoked is used.
            password_factor: Up to three levels of authentication (MFA) are allowed,
                             hence you can choose the password corresponding to the 1st,
                             2nd, or 3rd factor - 1st is the default.
        NzSwitching to strategy %s)plugin_nameauth_plugin_classr   )r,   )	r   r$   r   rN   r   r    rP   r,   r#   )r&   rU   rV   rX   rY   s        r'   _switch_auth_strategyz(MySQLAuthenticator._switch_auth_strategy   s    & ~H!!4N/1BCCC
o)^
 
 
 O44(
 
 
r)   pktOptional[bytes]c                   d}|d         t           k    r|| j        vrt          d          t          j        |          \  }}|                     ||           t          j        d|| j        j	                    | j        j
        ||fi | j        }|d         t          k    r-t          j        |          } | j        j        ||fi | j        }|d         t          k    rt          j        d           |S |d         t           k    rt#          |          |dz  }|d         t           k    t          j        d           d	S )
a  Handles MFA (Multi-Factor Authentication) response.

        Up to three levels of authentication (MFA) are allowed.

        Args:
            sock: Pointer to the socket connection.
            pkt: MFA response.

        Returns:
            ok_packet: If last server's response is an OK packet.
            None: If last server's response isn't an OK packet and no ERROR was raised.

        Raises:
            InterfaceError: If got an invalid N factor.
            errors.ErrorTypes: If got an ERROR response.
              z5Failed Multi Factor Authentication (invalid N factor))rY   zMFA %i factor %szMFA completed succesfullyr   z"MFA terminated with a no ok packetN)r   r    r	   r   parse_auth_next_factorr]   r   rN   r#   nameauth_switch_responser!   r   parse_auth_more_dataauth_more_responser   r   r   warning)r&   r4   r^   n_factorrU   	auth_datas         r'   _mfa_n_factorz MySQLAuthenticator._mfa_n_factor   sx   * !f
""t..$K   ,9+OPS+T+T(y&&'8(&SSSL+Xt7J7OPPP:$%:i #'#6 C 1v000)>sCC	<d)<) '+':  1v""8999
1v###C(((MH7 !f
"": 	;<<<tr)   c                <   |d         t           k    r"t          |          dk    rt          d          |d         t           k    rYt          j        d           t          j        |          \  }}|                     |            | j        j	        ||fi | j
        }|d         t          k    rAt          j        d           t          j        |          } | j        j        ||fi | j
        }|d         t          k    r!t          j        d| j        j                   |S |d         t           k    rIt          j        d           t          j        d| j        j                   |                     ||          S |d         t$          k    rt'          |          d	S )
a  Handles server's response.

        Args:
            sock: Pointer to the socket connection.
            pkt: Server's response after completing the `HandShakeResponse`.

        Returns:
            ok_packet: If last server's response is an OK packet.
            None: If last server's response isn't an OK packet and no ERROR was raised.

        Raises:
            errors.ErrorTypes: If got an ERROR response.
            NotSupportedError: If got Authentication with old (insecure) passwords.
        rb      zAuthentication with old (insecure) passwords is not supported. For more information, lookup Password Hashing in the latest MySQL manualz+Server's response is an auth switch requestzExchanging further packetsz%s completed succesfullyz$Starting multi-factor authenticationzMFA 1 factor %sN)r   lenr
   r   rN   r   parse_auth_switch_requestr]   r#   re   r!   r   rf   rg   r   rd   r   rk   r   r   )r&   r4   r^   rU   rj   s        r'   _handle_server_responsez*MySQLAuthenticator._handle_server_response   s   & q6'''CHHMM#>   q6'''LFGGG+8+RSV+W+W(y&&'8999:$%:i #'#6 C q6,,,L5666%:3??I8$%8i #'#6 C q6YL3T5H5MNNNJq6ZL?@@@L*D,?,DEEE%%dC000q6Z$$$tr)   r   F	handshaker   	password1	password2	password3databaseauth_pluginr\   
conn_attrsOptional[Dict[str, str]]is_change_user_requestread_timeoutOptional[int]write_timeoutc                f   || _         |||d| _        || _        t          j        ||||||	|
||||| j        | j                  \  }| _        |rdd|fndd|f} |j        |g|R   t          |
                    |                    }|                     ||          }|t          d          d|S )a  Performs the authentication phase.

        During re-authentication you must set `is_change_user_request` to True.

        Args:
            sock: Pointer to the socket connection.
            handshake: Initial handshake.
            username: Account's username.
            password1: Account's password factor 1.
            password2: Account's password factor 2.
            password3: Account's password factor 3.
            database: Initial database name for the connection.
            charset: Client charset (see [1]), only the lower 8-bits.
            client_flags: Integer representing client capabilities flags.
            max_allowed_packet: Maximum packet size.
            auth_plugin: Authorization plugin name.
            auth_plugin_class: Authorization plugin class (has higher precedence
                               than the authorization plugin name).
            conn_attrs: Connection attributes.
            is_change_user_request: Whether is a `change user request` operation or not.
            read_timeout: Timeout in seconds upto which the connector should wait for
                          the server to reply back before raising an ReadTimeoutError.
            write_timeout: Timeout in seconds upto which the connector should spend to
                           send data to the server before raising an WriteTimeoutError.
        Returns:
            ok_packet: OK packet.

        Raises:
            InterfaceError: If OK packet is NULL.
            ReadTimeoutError: If the time taken for the server to reply back exceeds
                              'read_timeout' (if set).
            WriteTimeoutError: If the time taken to send data packets to the server
                               exceeds 'write_timeout' (if set).

        References:
            [1]: https://dev.mysql.com/doc/dev/mysql-server/latest/                page_protocol_basic_character_set.html#a_protocol_character_set
        )r   ra      )rq   rX   passwordru   r9   r;   r<   rv   r\   rw   ry   r,   r/   r   NzGot a NULL ok_pkt)r   r    r$   r   	make_authr,   r/   r#   rM   r=   recvrp   r	   )r&   r4   rq   rX   rr   rs   rt   ru   r9   r;   r<   rv   r\   rw   ry   rz   r|   response_payload	send_argsr^   ok_pkts                        r'   authenticatezMySQLAuthenticator.authenticate#  s   t "'I)DD"3 1>0G%1#/!#9(,1
 1
 1
-$-& &-Q=!!m, 	
 		"/Y//// DIIl++,,--dC88> !4554?r)   )r   r   )r   r*   )r   r-   )r0   r-   r   r   )r4   r   r5   r6   r7   r8   r9   r:   r;   r:   r<   r:   r   r=   )NNr   )
rU   r6   rV   rW   rX   rW   rY   r:   r   r   )r4   r   r^   r=   r   r_   )"r4   r   rq   r   rX   r6   rr   r6   rs   r6   rt   r6   ru   rW   r9   r:   r;   r:   r<   r:   rv   rW   r\   rW   rw   rx   ry   r*   rz   r{   r|   r{   r   r=   )__name__
__module____qualname____doc__r(   propertyr,   r/   r3   r   r   rT   r]   rk   rp   r    r)   r'   r   r   5   sB       ..6 6 6 6 ! ! ! X! # # # X# + + + + *"<7# 7# 7# 7# 7#x )-"&  
  
  
  
  
D4 4 4 4l5 5 5 5v "&)"<%)+//3',&*'+#^ ^ ^ ^ ^ ^ ^r)   r   N)r   
__future__r   typingr   r   r   r   errorsr	   r
   r   r   pluginsr   r   protocolr   r   r   r   r   r   r   r   typesr   networkr   r   r   r)   r'   <module>r      sY  : < ; " " " " " " 5 5 5 5 5 5 5 5 5 5 5 5 D D D D D D D D D D       5 5 5 5 5 5 5 5	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 !           %$$$$$$L L L L L L L L L Lr)   