
    g!L                        d 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
mZ ddlmZmZ ddlmZ dd	lmZ dd
lmZ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  ej@                  d      Z! ed      Z"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+dZ,de,z  Z-ej\                  ej^                  z   Z0dZ1d Z2d Z3d  Z4d! Z5d" Z6d# Z7d$ Z8 G d% d&e9      Z:d' Z;d( Z< G d) d*e9      Z= G d+ d,e      Z>y)-z
Cross Site Request Forgery Middleware.

This module provides a middleware that implements protection
against request forgeries from other sites.
    N)defaultdicturlparse)settings)DisallowedHostImproperlyConfigured)HttpHeadersUnreadablePostError)get_callable)patch_vary_headers)constant_time_compareget_random_string)MiddlewareMixin)cached_propertyis_same_domain)log_response)_lazy_re_compilezdjango.security.csrfz[^a-zA-Z0-9]z?Origin checking failed - %s does not match any trusted origins.z%Referer checking failed - no Referer.z@Referer checking failed - %s does not match any trusted origins.zCSRF cookie not set.zCSRF token missing.z/Referer checking failed - Referer is malformed.zCReferer checking failed - Referer is insecure while host is secure.zhas incorrect lengthzhas invalid characters       
_csrftokenc                  4    t        t        j                        S )z/Return the view to be used for CSRF rejections.)r   r   CSRF_FAILURE_VIEW     n/var/www/python.vincentserveurtest.ovh/public_html/venv/lib/python3.12/site-packages/django/middleware/csrf.py_get_failure_viewr   2   s    2233r   c                  ,    t        t        t              S )N)allowed_chars)r   CSRF_SECRET_LENGTHCSRF_ALLOWED_CHARSr   r   r   _get_new_csrf_stringr"   7   s    /?QRRr   c                     t               }t        t        fd| D        fd|D              }dj                  fd|D              }||z   S )z
    Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
    token by adding a mask and applying it to the secret.
    c              3   @   K   | ]  }j                  |        y wNindex.0xcharss     r   	<genexpr>z&_mask_cipher_secret.<locals>.<genexpr>B   s     0AQ   c              3   @   K   | ]  }j                  |        y wr%   r&   r(   s     r   r,   z&_mask_cipher_secret.<locals>.<genexpr>B   s     2P4a5;;q>4r-    c              3   L   K   | ]  \  }}||z   t              z       y wr%   )lenr)   r*   yr+   s      r   r,   z&_mask_cipher_secret.<locals>.<genexpr>C   s(     CUTQUAESZ/0Us   !$)r"   r!   zipjoin)secretmaskpairscipherr+   s       @r   _mask_cipher_secretr:   ;   sH    
  !DE002P42PQEWWCUCCF&=r   c                     | dt          }| t         d } t        t        fd| D        fd|D              }dj                  fd|D              S )z
    Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
    CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
    the second half to produce the original secret.
    Nc              3   @   K   | ]  }j                  |        y wr%   r&   r(   s     r   r,   z'_unmask_cipher_token.<locals>.<genexpr>P   s     /AQr-   c              3   @   K   | ]  }j                  |        y wr%   r&   r(   s     r   r,   z'_unmask_cipher_token.<locals>.<genexpr>P   s     1O$Q%++a.$r-   r/   c              3   4   K   | ]  \  }}||z
       y wr%   r   r2   s      r   r,   z'_unmask_cipher_token.<locals>.<genexpr>Q   s     2EDAq5Q<Es   )r    r!   r4   r5   )tokenr7   r8   r+   s      @r   _unmask_cipher_tokenr@   G   sS     $$%D$%&EE//1O$1OPE772E222r   c                 V    t               }| j                  j                  |dd       |S )zDGenerate a new random CSRF_COOKIE value, and add it to request.META.T)CSRF_COOKIECSRF_COOKIE_NEEDS_UPDATE)r"   METAupdaterequestcsrf_secrets     r   _add_new_csrf_cookierI   T   s/    &(KLL&(,	
 r   c                     d| j                   v r)| j                   d   }d| j                   d<   t        |      S t        |       }t        |      S )a  
    Return the CSRF token required for a POST form. The token is an
    alphanumeric value. A new token is created if one is not already set.

    A side effect of calling this function is to make the csrf_protect
    decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
    header to the outgoing response.  For this reason, you may need to use this
    function lazily, as is done by the csrf context processor.
    rB   TrC   )rD   rI   r:   rF   s     r   	get_tokenrK   `   sS     $ll=1 48/0 {++ +73{++r   c                     t        |        y)zi
    Change the CSRF token in use for a request - should be done on login
    for security purposes.
    N)rI   )rG   s    r   rotate_tokenrM   u   s    
 !r   c                       e Zd Zd Zy)InvalidTokenFormatc                     || _         y r%   reasonselfrR   s     r   __init__zInvalidTokenFormat.__init__~   	    r   N__name__
__module____qualname__rU   r   r   r   rO   rO   }       r   rO   c                     t        |       t        t        fvrt        t              t
        j                  |       rt        t              y)z
    Raise an InvalidTokenFormat error if the token has an invalid length or
    characters that aren't allowed. The token argument can be a CSRF cookie
    secret or non-cookie CSRF token, and either masked or unmasked.
    N)r1   CSRF_TOKEN_LENGTHr    rO   REASON_INCORRECT_LENGTHinvalid_token_chars_researchREASON_INVALID_CHARACTERS)r?   s    r   _check_token_formatrb      sB     5z+-?@@ !899$$U+ !:;; ,r   c                 |    t        |       t        k(  rt        |       } t        |       t        k(  sJ t	        | |      S )a  
    Return whether the given CSRF token matches the given CSRF secret, after
    unmasking the token if necessary.

    This function assumes that the request_csrf_token argument has been
    validated to have the correct length (CSRF_SECRET_LENGTH or
    CSRF_TOKEN_LENGTH characters) and allowed characters, and that if it has
    length CSRF_TOKEN_LENGTH, it is a masked secret.
    )r1   r]   r@   r    r   )request_csrf_tokenrH   s     r   _does_token_matchre      sB     "3312DE!"&8888 !3[AAr   c                       e Zd Zd Zy)RejectRequestc                     || _         y r%   rQ   rS   s     r   rU   zRejectRequest.__init__   rV   r   NrW   r   r   r   rg   rg      r[   r   rg   c                       e Zd ZdZed        Zed        Zed        Zd Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd Zd Zy)CsrfViewMiddlewarez
    Require a present and correct csrfmiddlewaretoken for POST requests that
    have a CSRF cookie, and set an outgoing CSRF cookie.

    This middleware should be used in conjunction with the {% csrf_token %}
    template tag.
    c                     t         j                  D cg c]&  }t        |      j                  j	                  d      ( c}S c c}w N*)r   CSRF_TRUSTED_ORIGINSr   netloclstriprT   origins     r   csrf_trusted_origins_hostsz-CsrfViewMiddleware.csrf_trusted_origins_hosts   sE     #77
7 V##**3/7
 	
 
s   +Ac                 R    t         j                  D ch c]	  }d|vs| c}S c c}w rl   )r   rn   rq   s     r   allowed_origins_exactz(CsrfViewMiddleware.allowed_origins_exact   s*    %-%B%BX%B6cQWFW%BXXXs   	$$c                     t        t              }d t        j                  D        D ]9  }||j                     j                  |j                  j                  d             ; |S )z
        A mapping of allowed schemes to list of allowed netlocs, where all
        subdomains of the netloc are allowed.
        c              3   :   K   | ]  }d |v rt        |        yw)rm   Nr   )r)   rr   s     r   r,   z?CsrfViewMiddleware.allowed_origin_subdomains.<locals>.<genexpr>   s$      
7f} V7s   rm   )r   listr   rn   schemeappendro   rp   )rT   allowed_origin_subdomainsparseds      r   r{   z,CsrfViewMiddleware.allowed_origin_subdomains   sZ     %0$5!
"77
F
 &fmm4;;FMM<P<PQT<UV
 )(r   c                     d|_         y )NT)csrf_processing_done)rT   rG   s     r   _acceptzCsrfViewMiddleware._accept   s     (,$r   c                 h     t               ||      }t        d||j                  ||t               |S )NrQ   zForbidden (%s): %s)responserG   logger)r   r   pathr   )rT   rG   rR   r   s       r   _rejectzCsrfViewMiddleware._reject   s9    &$&wv> LL	
 r   c                 L   t         j                  r!	 |j                  j                  t              }n)	 |j                  t         j                     }t        |       |yt        |      t        k(  rt        |      }|S # t
        $ r t        d      w xY w# t        $ r d}Y Gw xY w)a  
        Return the CSRF secret originally associated with the request, or None
        if it didn't have one.

        If the CSRF_USE_SESSIONS setting is false, raises InvalidTokenFormat if
        the request's secret has invalid characters or an invalid length.
        zCSRF_USE_SESSIONS is enabled, but request.session is not set. SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE.N)r   CSRF_USE_SESSIONSsessiongetCSRF_SESSION_KEYAttributeErrorr   COOKIESCSRF_COOKIE_NAMErb   KeyErrorr1   r]   r@   rT   rG   rH   s      r   _get_secretzCsrfViewMiddleware._get_secret   s     %%%oo112BC1%ooh.G.GH
 $K0{00.{;K' " *%   #"#s   A= B =BB#"B#c           
         t         j                  rQ|j                  j                  t              |j
                  d   k7  r!|j
                  d   |j                  t        <   y y |j                  t         j                  |j
                  d   t         j                  t         j                  t         j                  t         j                  t         j                  t         j                         t        |d       y )NrB   )max_agedomainr   securehttponlysamesite)Cookie)r   r   r   r   r   rD   
set_cookier   CSRF_COOKIE_AGECSRF_COOKIE_DOMAINCSRF_COOKIE_PATHCSRF_COOKIE_SECURECSRF_COOKIE_HTTPONLYCSRF_COOKIE_SAMESITEr   rT   rG   r   s      r   _set_csrf_cookiez#CsrfViewMiddleware._set_csrf_cookie   s    %%""#34]8SS4;LL4O 01 T ))]+ 0022..22!66!66   	 x5r   c                    |j                   d   }	 |j                         }|j                         rdndd|}||k(  ry|| j                  v ry	 t        |      }|j                  }|j                  t        fd| j                  j                  |d      D              S # t        $ r Y lw xY w# t        $ r Y yw xY w)	NHTTP_ORIGINhttpshttpz://TFc              3   6   K   | ]  }t        |        y wr%   r   )r)   hostrequest_netlocs     r   r,   z6CsrfViewMiddleware._origin_verified.<locals>.<genexpr>$  s       
N >40Ns   r   )rD   get_host	is_securer   ru   r   
ValueErrorry   ro   anyr{   r   )rT   rG   request_origin	good_hostgood_originparsed_originrequest_schemer   s          @r   _origin_verifiedz#CsrfViewMiddleware._origin_verified  s     m4
	((*I
 #,,.F:K ,T777	$^4M '--&-- 
66::>2N
 
 	
#  		  		s#   B" B1 "	B.-B.1	B=<B=c                    |j                   j                  d      t        t              	 t	              dj                  j                  fv rt        t              j                  dk7  rt        t              t        fd| j                  D              ry t        j                  rt        j                  nt        j                  }|	 |j!                         }n|j)                         }|dvr|d|}t+        j                  |      s t        t$        j'                         z        y # t
        $ r t        t              w xY w# t"        $ r! t        t$        j'                         z        w xY w)NHTTP_REFERERr/   r   c              3   J   K   | ]  }t        j                  |        y wr%   )r   ro   )r)   r   referers     r   r,   z4CsrfViewMiddleware._check_referer.<locals>.<genexpr>;  s$      
7 7>>407s    #)44380:)rD   r   rg   REASON_NO_REFERERr   r   REASON_MALFORMED_REFERERry   ro   REASON_INSECURE_REFERERr   rs   r   r   SESSION_COOKIE_DOMAINr   r   r   REASON_BAD_REFERERgeturlget_portr   )rT   rG   good_refererserver_portr   s       @r   _check_refererz!CsrfViewMiddleware._check_referer)  si   ,,"">2? 122	:w'G
 '..'..11 899 >>W$ 788 
77
 
  )) **,, 	
 K&//1 "**,K-/*6Dgnnl; 2W^^5E EFF <G  	: 899	:8 " K#$69I$IJJKs   D6 E 6E*E<c                 T    |dk7  rt        j                  |      }d|d}d| d| dS )NPOSTzthe z HTTP headerzCSRF token from  .)r	   parse_header_name)rT   rR   token_sourceheader_names       r   _bad_token_messagez%CsrfViewMiddleware._bad_token_messageV  s=    6!%77EK!+=L!,q::r   c                    	 | j                  |      }|t        t              d}|j
                  dk(  r	 |j                  j                  dd      }|dk(  r/	 |j                  t        j                     }t        j                  }nd}	 t        |       t!        ||      s| j                  d|      }t        |      y # t        $ r}t        d|j                   d      d }~ww xY w# t        $ r Y w xY w# t        $ r t        t              w xY w# t        $ r,}| j                  |j                  |      }t        |      d }~ww xY w)NzCSRF cookie r   r/   r   csrfmiddlewaretoken	incorrect)r   rO   rg   rR   REASON_NO_CSRF_COOKIEmethodr   r   r
   rD   r   CSRF_HEADER_NAMEr   REASON_CSRF_TOKEN_MISSINGrb   r   re   )rT   rG   rH   excrd   r   rR   s          r   _check_tokenzCsrfViewMiddleware._check_token]  sb   	>**73K    566  >>V#%,\\%5%56KR%P" #?
 &-\\(2K2K%L" $44L!L	( 23
 !!3[A,,[,GF'' BU " 	>,szzl! <==	> ' 
    ?#$=>>? " 	(,,SZZFF''	(sL   B> C( C7 	D >	C%C  C%(	C43C47D	E'EEc                     	 | j                  |      }|||j                  d<   y y # t        $ r t        |       Y y w xY w)NrB   )r   rD   rO   rI   r   s      r   process_requestz"CsrfViewMiddleware.process_request  sM    
	:**73K &
 /:]+ ' " 	* )	*s   & ==c                    t        |dd      ry t        |dd      ry |j                  dv r| j                  |      S t        |dd      r| j                  |      S d|j                  v r7| j	                  |      sH| j                  |t        |j                  d   z        S |j                         r	 | j                  |       	 | j                  |       | j                  |      S # t        $ r&}| j                  ||j                        cY d }~S d }~ww xY w# t        $ r&}| j                  ||j                        cY d }~S d }~ww xY w)Nr~   Fcsrf_exempt)GETHEADOPTIONSTRACE_dont_enforce_csrf_checksr   )getattrr   r   rD   r   r   REASON_BAD_ORIGINr   r   rg   rR   r   )rT   rG   callbackcallback_argscallback_kwargsr   s         r   process_viewzCsrfViewMiddleware.process_view  s2   72E: 8]E2 >>@@<<((77?
 <<(( GLL(((1||.m1LL   $9##G,	5g& ||G$$ ! 9||GSZZ889
  	5<<44	5s<   0C$ D $	D-DDD	EE :E Ec                 ~    |j                   j                  d      r!| j                  ||       d|j                   d<   |S )NrC   F)rD   r   r   r   s      r   process_responsez#CsrfViewMiddleware.process_response  s;    <<67!!'84 8=GLL34r   N)rX   rY   rZ   __doc__r   rs   ru   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rj   rj      s     
 
 Y Y ) ) 
@6$
4+GZ;2(h:7%rr   rj   )?r   loggingstringcollectionsr   urllib.parser   django.confr   django.core.exceptionsr   r   django.httpr	   r
   django.urlsr   django.utils.cacher   django.utils.cryptor   r   django.utils.deprecationr   django.utils.functionalr   django.utils.httpr   django.utils.logr   django.utils.regex_helperr   	getLoggerr   r_   r   r   r   r   r   r   r   r^   ra   r    r]   ascii_lettersdigitsr!   r   r   r"   r:   r@   rI   rK   rM   	ExceptionrO   rb   re   rg   rj   r   r   r   <module>r      s     # !   G 8 $ 1 H 4 3 , ) 6			1	2).9 U ; W . 1 L I  1 4  ** ))FMM9  4
S	
3	,*" 

<B"I 
~ ~r   