
    G)f6                        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 erddlmZ  G d d      Zy)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)HandShakeType)MySQLSocketc                     e Zd ZdZddZedd       Zedd       Zede	f	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
	 	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 dd	Z	 	 	 	 	 	 dd
Zdddddede	ddddf	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZy)MySQLAuthenticatorz$Implements the authentication phase.c                X    d| _         i | _        i | _        d| _        d| _        d| _        y)zConstructor. FN)	_username
_passwords_plugin_config_ssl_enabled_auth_strategy_auth_plugin_classselfs    [/var/www/html/flask-app/venv/lib/python3.12/site-packages/mysql/connector/authentication.py__init__zMySQLAuthenticator.__init__:   s0     *,.0"'9=15    c                    | j                   S )z&Signals whether or not SSL is enabled.)r    r#   s    r%   ssl_enabledzMySQLAuthenticator.ssl_enabledC   s        r'   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_configH   s     """r'   r   c                   |i }t        j                  |||      }|j                  |       t        j                  d       |j                  |j                  d      |j                  d      |j                  d      |j                  dd      |j                  dd      |j                  d	      |j                  d
            }t        j                  d       |j                  ||       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
        )charsetclient_flagsmax_allowed_packetz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_identityr5   tls_cipher_suiteszSwitching to SSLzSSL has been enabledT)	r   make_auth_sslsendr   debugbuild_ssl_contextgetswitch_to_sslr    )	r$   sockhostssl_optionsr-   r.   r/   ssl_request_payloadssl_contexts	            r%   	setup_sslzMySQLAuthenticator.setup_sslY   s    6 K ,99%1

 			%&+,,,??4( __V,OOE*'OOM5A +0A5 I$8)oo.@A - 
 	'(;-+, ""r'   Nc                    || j                   }|| j                  }t        j                  d|        t	        ||      || j
                  j                  |d      | j                        | _        y)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   r?   r   r   rA   r)   r!   )r$   new_strategy_namestrategy_classusernamepassword_factors        r%   _switch_auth_strategyz(MySQLAuthenticator._switch_auth_strategy   sq    & ~~H!!44N/1BC
o)^
 OO4((
r'   c                   d}|d   t         k(  r-|| j                  vrt        d      t        j                  |      \  }}| 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(  r-t        j$                  d       y	)
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))rO   zMFA %i factor %szMFA completed succesfullyr   z"MFA terminated with a no ok packetN)r   r   r	   r   parse_auth_next_factorrP   r   r?   r!   nameauth_switch_responser   r   parse_auth_more_dataauth_more_responser   r   r   warning)r$   rC   pktn_factorrL   	auth_datas         r%   _mfa_n_factorz MySQLAuthenticator._mfa_n_factor   sP   * !f
"t.$K  ,9+O+OPS+T(y&&'8(&SLL+Xt7J7J7O7OP:$%%::i#'#6#6C 1v00)>>sC	<d))<<)'+':': 1v"89
1v##C((MH7 !f
": 	;<r'   c                F   |d   t         k(  rt        |      dk(  rt        d      |d   t         k(  rft        j                  d       t        j                  |      \  }}| j                  |        | j                  j                  ||fi | j                  }|d   t        k(  rRt        j                  d       t        j                  |      } | j                  j                  ||fi | j                  }|d   t        k(  r,t        j                  d| j                  j                         |S |d   t         k(  rQt        j                  d       t        j                  d| j                  j                         | j#                  ||      S |d   t$        k(  rt'        |      y	)
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.
        rS      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   r?   r   parse_auth_switch_requestrP   r!   rV   r   r   rW   rX   r   rU   r   r]   r   r   )r$   rC   rZ   rL   r\   s        r%   _handle_server_responsez*MySQLAuthenticator._handle_server_response   s   & q6''CHM#>  q6''LLFG+8+R+RSV+W(y&&'89:$%%::i#'#6#6C q6,,LL56%::3?I8$%%88i#'#6#6C q6YLL3T5H5H5M5MNJq6ZLL?@LL*D,?,?,D,DE%%dC00q6Z$$r'   r   Fc                   || _         |||d| _        t        j                  |      | _        || _        t        j                  ||||||	|
||||| j                  | j                        \  }| _
        |rdnd} |j                  |g|  t        |j                               }| j                  ||      }|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.
            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   rR      )	handshakerN   passworddatabaser-   r.   r/   auth_pluginrK   
conn_attrsis_change_user_requestr)   r+   )r   r   )NNNzGot a NULL ok_pkt)r   r   copydeepcopyr   r"   r   	make_authr)   r+   r!   r>   bytesrecvrb   r	   )r$   rC   re   rN   	password1	password2	password3rg   r-   r.   r/   rh   rK   ri   rj   r+   response_payload	send_argsrZ   ok_pkts                       r%   authenticatezMySQLAuthenticator.authenticate!  s    j "'I)D"mmM:"3 1>0G0G%1#/!#9((,,1
-$-" 5F,			"/Y/ DIIK --dC8> !454?r'   )returnNone)rw   bool)rw   zDict[str, Any])rC   r   rD   strrE   zOptional[Dict[str, Any]]r-   intr.   r{   r/   r{   rw   rn   )NNr   )
rL   rz   rM   Optional[str]rN   r|   rO   r{   rw   rx   )rC   r   rZ   rn   rw   zOptional[bytes]) rC   r   re   r   rN   rz   rp   rz   rq   rz   rr   rz   rg   r|   r-   r{   r.   r{   r/   r{   rh   r|   rK   r|   ri   zOptional[Dict[str, str]]rj   ry   r+   r   rw   rn   )__name__
__module____qualname____doc__r&   propertyr)   r+   r   r   rH   rP   r]   rb   rv    r'   r%   r   r   7   s   .6 ! ! # #* *"<7#7# 7# .	7#
 7# 7#  7# 
7#x )-"&  
 
 & 
  	 

  
 
 
D44 4 
	4l55 5 
	5v "&)"<%)+//3',VV !V 	V
 V V V  V V V  V #V )V -V !%V  !V" 
#Vr'   r   )r   
__future__r   rk   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      sH   : < "  5 5 D D  5	 	 	 !$@ @r'   