o
    Jli#7                     @  s   d Z ddlmZ ddl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mZ erTddlmZ G dd dZdS )z5Implementing support for MySQL Authentication Plugins    )annotationsN)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)ConnAttrsTypeHandShakeType)MySQLSocketc                   @  s   e Zd ZdZd:ddZed;ddZed<d
dZede	fd=ddZ
			d>d?d!d"Zd@d%d&Zd@d'd(Zd)d)d)d)dede	dddd*fdAd8d9ZdS )BMySQLAuthenticatora  Implements the authentication phase.

    The caller has access to the following API:
        - ssl_enabled (property, read-only): signals whether or not SSL is enabled.

        - plugin_config (property, read-only): custom arguments that will be provided
        to the authentication plugin when called.

        - setup_ssl (method): Set up an SSL communication channel.

        - authenticate (method): Performs the authentication phase.
    returnNonec                 C  s(   d| _ i | _i | _d| _d| _d| _dS )zConstructor. FN)	_username
_passwords_plugin_config_ssl_enabled_auth_strategy_auth_plugin_classself r%   n/var/www/html/tatsat2dev/dashboard-backend/venv/lib/python3.10/site-packages/mysql/connector/authentication.py__init__E   s   
zMySQLAuthenticator.__init__boolc                 C     | j S )z&Signals whether or not SSL is enabled.)r    r#   r%   r%   r&   ssl_enabledN   s   zMySQLAuthenticator.ssl_enabledDict[str, Any]c                 C  r)   )zCustom arguments that will be provided to the authentication
        plugin when called.

        The parameters defined here will override the ones defined in
        the auth plugin itself.
        )r   r#   r%   r%   r&   plugin_configS   s   z MySQLAuthenticator.plugin_configr   sockr   hoststrssl_optionsOptional[Dict[str, Any]]charsetintclient_flagsmax_allowed_packetbytesc           	   
   C  s   |du ri }t j|||d}|| td |j|d|d|d|dd|d	d|d
|dd}td ||| td d| _|S )a  Set 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)r2   r4   r5   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_identityr<   tls_cipher_suiteszSwitching to SSLzSSL has been enabledT)	r   make_auth_sslsendr   debugbuild_ssl_contextgetswitch_to_sslr    )	r$   r-   r.   r0   r2   r4   r5   ssl_request_payloadssl_contextr%   r%   r&   	setup_ssl]   s.   






zMySQLAuthenticator.setup_sslNr   new_strategy_namestrategy_classOptional[str]usernamepassword_factorc                 C  sP   |du r| j }|du r| j}td| t||d|| j|d| jd| _dS )a  Switch 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 called 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.

        Returns:
            None.
        NzSwitching to strategy %s)plugin_nameauth_plugin_classr   )r*   )	r   r"   r   rF   r   r   rH   r*   r!   )r$   rM   rN   rP   rQ   r%   r%   r&   _switch_auth_strategy   s   z(MySQLAuthenticator._switch_auth_strategypktOptional[bytes]c                 C  s   d}|d t krl|| jvrtdt|\}}| j||d td|| jj	 | jj
||fi | j}|d tkrKt|}| jj||fi | j}|d tkrXtd |S |d tkrbt||d7 }|d t kstd d	S )
a  Handle 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))rQ   zMFA %i factor %szMFA completed succesfullyr   z"MFA terminated with a no ok packetN)r   r   r   r   parse_auth_next_factorrT   r   rF   r!   nameauth_switch_responser   r   parse_auth_more_dataauth_more_responser   r   r
   warning)r$   r-   rU   n_factorrM   	auth_datar%   r%   r&   _mfa_n_factor   s<   



z MySQLAuthenticator._mfa_n_factorc                 C  s  |d t krt|dkrtd|d t kr3td t|\}}| | | jj	||fi | j
}|d tkrOtd t|}| jj||fi | j
}|d tkr_td| jj |S |d tkrxtd td| jj | ||S |d tkrt|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.
        rX      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   rF   r   parse_auth_switch_requestrT   r!   r[   r   r   r\   r]   r   rZ   r   ra   r   r
   )r$   r-   rU   rM   r`   r%   r%   r&   _handle_server_response   s>   




z*MySQLAuthenticator._handle_server_responser   F	handshaker   	password1	password2	password3databaseauth_pluginrS   
conn_attrsOptional[ConnAttrsType]is_change_user_requestr,   r   c                 K  s   || _ |||d| _t|| _|| _tj||||||	|
||||| j| j	d\}| _
|r.dnd}|j|g|R   t| }| ||}|du rNtdd|S )a  Performs the authentication phase.

        During re-authentication you should 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.
            plugin_config: Custom configuration to be passed to the auth plugin
                when invoked. The parameters defined here will override the ones
                defined in the auth plugin itself.

        Returns:
            ok_packet: OK packet.

        Raises:
            InterfaceError: If OK packet is NULL.

        References:
            [1]: https://dev.mysql.com/doc/dev/mysql-server/latest/
                page_protocol_basic_character_set.html#a_protocol_character_set
        )r   rW      )rf   rP   passwordrj   r2   r4   r5   rk   rS   rl   rn   r*   r,   )r   r   )NNNzGot a NULL ok_pkt)r   r   copydeepcopyr   r"   r   	make_authr*   r,   r!   rE   r6   recvre   r   )r$   r-   rf   rP   rg   rh   ri   rj   r2   r4   r5   rk   rS   rl   rn   r,   response_payload	send_argsrU   ok_pktr%   r%   r&   authenticate(  s4   5
zMySQLAuthenticator.authenticate)r   r   )r   r(   )r   r+   )r-   r   r.   r/   r0   r1   r2   r3   r4   r3   r5   r3   r   r6   )NNr   )
rM   r/   rN   rO   rP   rO   rQ   r3   r   r   )r-   r   rU   r6   r   rV   ) r-   r   rf   r   rP   r/   rg   r/   rh   r/   ri   r/   rj   rO   r2   r3   r4   r3   r5   r3   rk   rO   rS   rO   rl   rm   rn   r(   r,   r   r   r6   )__name__
__module____qualname____doc__r'   propertyr*   r,   r   r   rL   rT   ra   re   rx   r%   r%   r%   r&   r   7   s<    
	<
%
6;r   ) r|   
__future__r   rq   typingr   r   r   r   errorsr   r	   r
   r   pluginsr   r   protocolr   r   r   r   r   r   r   r   typesr   r   networkr   r   r%   r%   r%   r&   <module>   s   (
