
    ZeIi'                     L   d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ dZ ej        e          ZddZddZ	 ddZ G d de          Z G d d          Z G d de          Zd Z dS )    N)urlparse)	Blueprint)current_app)g)request)session)BadData)SignatureExpired)URLSafeTimedSerializer)
BadRequest)ValidationError)CSRF)generate_csrfvalidate_csrfCSRFProtectc                    t          | dt          j        d          } t          |ddd          }|t          vrt	          | d          }|t
          vr@t          j        t          j	        d	                    
                                t
          |<   	 |                    t
          |                   }np# t          $ rc t          j        t          j	        d	                    
                                t
          |<   |                    t
          |                   }Y nw xY wt          t          ||           t          j        |          S )
a  Generate a CSRF token. The token is cached for a request, so multiple
    calls to this function will generate the same token.

    During testing, it might be useful to access the signed token in
    ``g.csrf_token`` and the raw token in ``session['csrf_token']``.

    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param token_key: Key where token is stored in session for comparison.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.
    WTF_CSRF_SECRET_KEY%A secret key is required to use CSRF.messageWTF_CSRF_FIELD_NAME
csrf_token%A field name is required to use CSRF.wtf-csrf-tokensalt@   )_get_configr   
secret_keyr   r   r   hashlibsha1osurandom	hexdigestdumps	TypeErrorsetattrget)r   	token_key
field_namestokens        S/var/www/html/MCyber-Diagnostic/venv/lib/python3.11/site-packages/flask_wtf/csrf.pyr   r      s:    7	  J 7	  J ":4DEEEW$$"),rz"~~">">"H"H"J"JGJ	1GGGJ/00EE 	1 	1 	1"),rz"~~">">"H"H"J"JGJGGGJ/00EEE	1 	:u%%%5s    B7 7A*D$#D$c                    t          |dt          j        d          }t          |ddd          }t          |ddd	
          }| st          d          |t          vrt          d          t          |d          }	 |                    | |          }n?# t          $ r}t          d          |d}~wt          $ r}t          d          |d}~ww xY wt          j
        t          |         |          st          d          dS )a  Check if the given data is a valid CSRF token. This compares the given
    signed token to the one stored in the session.

    :param data: The signed CSRF token to be checked.
    :param secret_key: Used to securely sign the token. Default is
        ``WTF_CSRF_SECRET_KEY`` or ``SECRET_KEY``.
    :param time_limit: Number of seconds that the token is valid. Default is
        ``WTF_CSRF_TIME_LIMIT`` or 3600 seconds (60 minutes).
    :param token_key: Key where token is stored in session for comparison.
        Default is ``WTF_CSRF_FIELD_NAME`` or ``'csrf_token'``.

    :raises ValidationError: Contains the reason that validation failed.

    .. versionchanged:: 0.14
        Raises ``ValidationError`` with a specific error message rather than
        returning ``True`` or ``False``.
    r   r   r   r   r   r   WTF_CSRF_TIME_LIMIT  F)requiredzThe CSRF token is missing.z"The CSRF session token is missing.r   r   )max_agezThe CSRF token has expired.NzThe CSRF token is invalid.zThe CSRF tokens do not match.)r   r   r   r   r   r   loadsr
   r	   hmaccompare_digest)datar   
time_limitr)   r*   r+   r,   es           r-   r   r   B   sV   & 7	  J 7	  J Z)>uUUUJ <:;;;  BCCCz0@AAAACj11 D D D;<<!C C C C:;;BC wz2E:: ?=>>>? ?s$   ?B 
C!B11C>CCTCSRF is not configured.c                 p    |  t           j                            ||          } |r| t          |          | S )a  Find config value based on provided value, Flask config, and default
    value.

    :param value: already provided config value
    :param config_name: Flask ``config`` key
    :param default: default value if not provided or configured
    :param required: whether the value must not be ``None``
    :param message: error message if required config is not found
    :raises KeyError: if required config is not found
    )r   configr(   RuntimeError)valueconfig_namedefaultr1   r   s        r-   r   r   v   s@     }"&&{G<< $EM7###L    c                   *     e Zd Z fdZd Zd Z xZS )_FlaskFormCSRFc                 ^    |j         | _         t                                          |          S N)metasuper
setup_form)selfform	__class__s     r-   rG   z_FlaskFormCSRF.setup_form   s$    I	ww!!$'''r@   c                 L    t          | j        j        | j        j                  S )N)r   r)   )r   rE   csrf_secretcsrf_field_name)rH   csrf_token_fields     r-   generate_csrf_tokenz"_FlaskFormCSRF.generate_csrf_token   s(    y,	8Q
 
 
 	
r@   c                    t          j        dd          rd S 	 t          |j        | j        j        | j        j        | j        j                   d S # t          $ r+}t          
                    |j        d                     d }~ww xY w)N
csrf_validFr   )r   r(   r   r6   rE   rL   csrf_time_limitrM   r   loggerinfoargs)rH   rI   fieldr8   s       r-   validate_csrf_tokenz"_FlaskFormCSRF.validate_csrf_token   s    5u%% 	F		
	%	)	)	      	 	 	KKq	"""	s   5A 
B&B  B)__name__
__module____qualname__rG   rO   rW   __classcell__)rJ   s   @r-   rB   rB      sV        ( ( ( ( (
 
 

      r@   rB   c                   8    e Zd ZdZd	dZd Zd Zd Zd Zd Z	dS )
r   a[  Enable CSRF protection globally for a Flask app.

    ::

        app = Flask(__name__)
        csrf = CSRFProtect(app)

    Checks the ``csrf_token`` field sent with forms, or the ``X-CSRFToken``
    header sent with JavaScript requests. Render the token in templates using
    ``{{ csrf_token() }}``.

    See the :ref:`csrf` documentation.
    Nc                     t                      | _        t                      | _        |r|                     |           d S d S rD   )set_exempt_views_exempt_blueprintsinit_app)rH   apps     r-   __init__zCSRFProtect.__init__   sD     UU"%%% 	MM#	 	r@   c                 D     j         d<   j                            dd           j                            dd           t          j                            dg d                    j        d<   j                            dd           j                            d	d
dg           j                            dd           j                            dd           t
          j        j        d<                       d            j	         fd            }d S )NcsrfWTF_CSRF_ENABLEDTWTF_CSRF_CHECK_DEFAULTWTF_CSRF_METHODS)POSTPUTPATCHDELETEr   r   WTF_CSRF_HEADERSzX-CSRFTokenzX-CSRF-Tokenr/   r0   WTF_CSRF_SSL_STRICTc                      dt           iS )Nr   )r    r@   r-   <lambda>z&CSRFProtect.init_app.<locals>.<lambda>   s    |]&C r@   c                     j         d         sd S j         d         sd S t          j        j         d         vrd S t          j        sd S j                            t          j                  j        v rd S j                            t          j                  } | j	         d| j
         }|j        v rd S                                  d S )Nrf   rg   rh   .)r;   r   methodendpoint
blueprintsr(   	blueprintr`   view_functionsrY   rX   r_   protect)viewdestrb   rH   s     r-   csrf_protectz*CSRFProtect.init_app.<locals>.csrf_protect   s    :01 :67 ~SZ0B%CCC# ~!!'"3448OOO%))'*:;;Do7777Dt)))LLNNNNNr@   )

extensionsr;   
setdefaultr^   r(   r   	jinja_envglobalscontext_processorbefore_request)rH   rb   r|   s   `` r-   ra   zCSRFProtect.init_app   s<   !%v
0$777
6===),JNN-/Q/Q/QRR*
 *

%& 	
3\BBB
0=.2QRRR
3T:::
3T:::.;l+CCDDD			 	 	 	 	 
		 	 	r@   c                 \   t           j        d         }t          j                            |          }|r|S t          j        D ]/}|                    |          rt          j        |         }|r|c S 0t           j        d         D ]'}t          j                            |          }|r|c S (d S )Nr   rm   )r   r;   r   rI   r(   endswithheaders)rH   r*   
base_tokenkeyr   header_names         r-   _get_csrf_tokenzCSRFProtect._get_csrf_token   s     '(=>
\%%j11
 	 < 	& 	&C||J'' &$\#.
 &%%%% '-.@A 	" 	"K ,,[99J "!!!!" tr@   c                 X   t           j        t          j        d         vrd S 	 t	          |                                            n\# t          $ rO}t                              |j	        d                    | 
                    |j	        d                    Y d }~nd }~ww xY wt           j        rrt          j        d         r`t           j        s| 
                    d           dt           j         d}t          t           j        |          s| 
                    d           dt          _        d S )	Nrh   r   rn   zThe referrer header is missing.zhttps:///z%The referrer does not match the host.T)r   rt   r   r;   r   r   r   rS   rT   rU   _error_response	is_securereferrerhostsame_originr   rQ   )rH   r8   good_referrers      r-   ry   zCSRFProtect.protect   s'   >!34F!GGGF	,$..001111 	, 	, 	,KKq	"""  ++++++++	,  	N!34I!J 	N# H$$%FGGG6w|666Mw/?? N$$%LMMMs   !A 
BABBc                    t          |t                    r| j                            |           |S t          |t                    r|}n!d                    |j        |j        f          }| j                            |           |S )a  Mark a view or blueprint to be excluded from CSRF protection.

        ::

            @app.route('/some-view', methods=['POST'])
            @csrf.exempt
            def some_view():
                ...

        ::

            bp = Blueprint(...)
            csrf.exempt(bp)

        rs   )	
isinstancer   r`   addstrjoinrY   rX   r_   )rH   rz   view_locations      r-   exemptzCSRFProtect.exempt  s    " dI&& 	#''---KdC   	G MMHHdot}%EFFM}---r@   c                      t          |          rD   )	CSRFError)rH   reasons     r-   r   zCSRFProtect._error_response2  s    r@   rD   )
rX   rY   rZ   __doc__rc   ra   r   ry   r   r   rp   r@   r-   r   r      s~            ' ' 'R  2  *  :         r@   r   c                       e Zd ZdZdZdS )r   zRaise if the client sends invalid CSRF data with the request.

    Generates a 400 Bad Request response with the failure reason by default.
    Customize the response by registering a handler with
    :meth:`flask.Flask.errorhandler`.
    zCSRF validation failed.N)rX   rY   rZ   r   descriptionrp   r@   r-   r   r   6  s          ,KKKr@   r   c                     t          |           }t          |          }|j        |j        k    o|j        |j        k    o|j        |j        k    S rD   )r   schemehostnameport)current_uricompare_uricurrentcompares       r-   r   r   A  sS    {##G{##G 	'.( 	) 00	)LGL(r@   )NN)NNN)NTr9   )!r    r4   loggingr"   urllib.parser   flaskr   r   r   r   r   itsdangerousr	   r
   r   werkzeug.exceptionsr   wtformsr   wtforms.csrf.corer   __all__	getLoggerrX   rS   r   r   r   rB   r   r   r   rp   r@   r-   <module>r      s      				 ! ! ! ! ! !                                           ) ) ) ) ) ) / / / / / / * * * * * * # # # # # # " " " " " "
;		8	$	$( ( ( (V1? 1? 1? 1?j >W   .    T   6K  K  K  K  K  K  K  K \, , , , ,
 , , ,    r@   