
    Evg!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>dS )-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     S/var/www/pixelcanvas.ch/venv/lib/python3.11/site-packages/django/middleware/csrf.py_get_failure_viewr   2   s    2333r   c                  8    t          t          t                    S )N)allowed_chars)r   CSRF_SECRET_LENGTHCSRF_ALLOWED_CHARSr   r   r   _get_new_csrf_stringr"   7   s    /?QRRRRr   c                     t                      }t          t          fd| D             fd|D                       }d                    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   B   K   | ]}                     |          V  d S Nindex.0xcharss     r   	<genexpr>z&_mask_cipher_secret.<locals>.<genexpr>B   s-      00AQ000000r   c              3   B   K   | ]}                     |          V  d S r%   r&   r(   s     r   r,   z&_mask_cipher_secret.<locals>.<genexpr>B   s-      2P2Pa5;;q>>2P2P2P2P2P2Pr    c              3   T   K   | ]"\  }}||z   t                    z           V  #d S r%   )lenr)   r*   yr+   s      r   r,   z&_mask_cipher_secret.<locals>.<genexpr>C   s;      CCTQUAESZZ/0CCCCCCr   )r"   r!   zipjoin)secretmaskpairscipherr+   s       @r   _mask_cipher_secretr9   ;   s~    
  !!DE00000002P2P2P2P42P2P2PQQEWWCCCCUCCCCCF&=r   c                     | dt                    }| t           d         } t          t          fd| D             fd|D                       }d                    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   B   K   | ]}                     |          V  d S r%   r&   r(   s     r   r,   z'_unmask_cipher_token.<locals>.<genexpr>P   s-      //AQ//////r   c              3   B   K   | ]}                     |          V  d S r%   r&   r(   s     r   r,   z'_unmask_cipher_token.<locals>.<genexpr>P   s-      1O1OQ%++a..1O1O1O1O1O1Or   r.   c              3   4   K   | ]\  }}||z
           V  d S r%   r   r1   s      r   r,   z'_unmask_cipher_token.<locals>.<genexpr>Q   s/      22DAq5Q<222222r   )r    r!   r3   r4   )tokenr6   r7   r+   s      @r   _unmask_cipher_tokenr?   G   s     $$$%D$%%&EE///////1O1O1O1O$1O1O1OPPE772222E222222r   c                 \    t                      }| 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_cookierH   T   s?    &((KL&(,	
 	
   r   c                     d| j         v r| j         d         }d| j         d<   n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.
    rA   TrB   )rC   rH   r9   rE   s     r   	get_tokenrJ   `   sJ     $$l=1 48/00*733{+++r   c                 $    t          |            dS )zi
    Change the CSRF token in use for a request - should be done on login
    for security purposes.
    N)rH   )rF   s    r   rotate_tokenrL   u   s    
 !!!!!r   c                       e Zd Zd ZdS )InvalidTokenFormatc                     || _         d S r%   reasonselfrQ   s     r   __init__zInvalidTokenFormat.__init__~       r   N__name__
__module____qualname__rT   r   r   r   rN   rN   }   #            r   rN   c                     t          |           t          t          fvrt          t                    t
                              |           rt          t                    dS )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)r0   CSRF_TOKEN_LENGTHr    rN   REASON_INCORRECT_LENGTHinvalid_token_chars_researchREASON_INVALID_CHARACTERS)r>   s    r   _check_token_formatra      sZ     5zz+-?@@@ !89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.
    )r0   r\   r?   r    r   )request_csrf_tokenrG   s     r   _does_token_matchrd      sT     "33312DEE!""&88888 !3[AAAr   c                       e Zd Zd ZdS )RejectRequestc                     || _         d S r%   rP   rR   s     r   rT   zRejectRequest.__init__   rU   r   NrV   r   r   r   rf   rf      rZ   r   rf   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dS )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                 .    d t           j        D             S )Nc                 \    g | ])}t          |          j                            d           *S *)r   netloclstripr)   origins     r   
<listcomp>zACsrfViewMiddleware.csrf_trusted_origins_hosts.<locals>.<listcomp>   sA     
 
 
 V#**3//
 
 
r   r   CSRF_TRUSTED_ORIGINSrS   s    r   csrf_trusted_origins_hostsz-CsrfViewMiddleware.csrf_trusted_origins_hosts   s&    
 
"7
 
 
 	
r   c                 .    d t           j        D             S )Nc                     h | ]}d |v|	S rl   r   rp   s     r   	<setcomp>z;CsrfViewMiddleware.allowed_origins_exact.<locals>.<setcomp>   s#    XXX6cQWFWFWFWFWFWr   rs   ru   s    r   allowed_origins_exactz(CsrfViewMiddleware.allowed_origins_exact   s    XXX%BXXXXr   c                     t          t                    }d t          j        D             D ]:}||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 t          |          V  dS )rm   Nr   rp   s     r   r,   z?CsrfViewMiddleware.allowed_origin_subdomains.<locals>.<genexpr>   s<       
 
f}} V}}}
 
r   rm   )r   listr   rt   schemeappendrn   ro   )rS   allowed_origin_subdomainsparseds      r   r   z,CsrfViewMiddleware.allowed_origin_subdomains   sv     %0$5$5!
 
"7
 
 
 	W 	WF
 &fm4;;FM<P<PQT<U<UVVVV((r   c                     d|_         d S )NT)csrf_processing_done)rS   rF   s     r   _acceptzCsrfViewMiddleware._accept   s     (,$tr   c                 v     t                      ||          }t          d||j        ||t                     |S )NrP   zForbidden (%s): %s)responserF   logger)r   r   pathr   )rS   rF   rQ   r   s       r   _rejectzCsrfViewMiddleware._reject   sO    &$&&wv>>> L	
 	
 	
 	
 r   c                 d   t           j        r>	 |j                            t                    }nW# t
          $ r t          d          w xY w	 |j        t           j                 }t          |           n# t          $ r d}Y nw xY w|dS t          |          t          k    rt          |          }|S )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_NAMEra   KeyErrorr0   r\   r?   rS   rF   rG   s      r   _get_secretzCsrfViewMiddleware._get_secret   s     % 	1%o112BCC!   *%  1%oh.GH
 $K0000	  # # #"#
 4{000.{;;Ks   . AA3 3BBc           
         t           j        rL|j                            t                    |j        d         k    r|j        d         |j        t          <   d S d S |                    t           j        |j        d         t           j        t           j	        t           j
        t           j        t           j        t           j                   t          |d           d S )NrA   )max_agedomainr   securehttponlysamesite)Cookie)r   r   r   r   r   rC   
set_cookier   CSRF_COOKIE_AGECSRF_COOKIE_DOMAINCSRF_COOKIE_PATHCSRF_COOKIE_SECURECSRF_COOKIE_HTTPONLYCSRF_COOKIE_SAMESITEr   rS   rF   r   s      r   _set_csrf_cookiez#CsrfViewMiddleware._set_csrf_cookie   s    % 	6""#344]8SSS4;L4O 0111 TS )]+ 02.2!6!6   	 	 	 x55555r   c                    |j         d         }	 |                                }|                                rdndd|}||k    rdS n# t          $ r Y nw xY w|| j        v rdS 	 t          |          }n# t          $ r Y dS w xY w|j        }|j        t          fd| j
                            |d          D                       S )	NHTTP_ORIGINhttpshttpz://TFc              3   8   K   | ]}t          |          V  d S r%   r   )r)   hostrequest_netlocs     r   r,   z6CsrfViewMiddleware._origin_verified.<locals>.<genexpr>$  sA       
 
 >400
 
 
 
 
 
r   r   )rC   get_host	is_securer   rz   r   
ValueErrorr~   rn   anyr   r   )rS   rF   request_origin	good_hostgood_originparsed_originrequest_schemer   s          @r   _origin_verifiedz#CsrfViewMiddleware._origin_verified  s0    m4
	((**I
 #,,..:F::	K ,,t -  	 	 	D	 T7774	$^44MM 	 	 	55	&-&- 
 
 
 
6::>2NN
 
 
 
 
 	
s#   A
 

AA&A6 6
BBc                 8   |j                             d          t          t                    	 t	                    n"# t
          $ r t          t                    w xY wdj        j        fv rt          t                    j        dk    rt          t                    t          fd| j        D                       rd S t          j        rt          j        nt          j        }|M	 |                                }nV# t"          $ r* t          t$                                          z            w xY w|                                }|dvr|d|}t+          j        |          s)t          t$                                          z            d S )NHTTP_REFERERr.   r   c              3   B   K   | ]}t          j        |          V  d S r%   )r   rn   )r)   r   referers     r   r,   z4CsrfViewMiddleware._check_referer.<locals>.<genexpr>;  sC       
 
 7>400
 
 
 
 
 
r   )44380:)rC   r   rf   REASON_NO_REFERERr   r   REASON_MALFORMED_REFERERr~   rn   REASON_INSECURE_REFERERr   rv   r   r   SESSION_COOKIE_DOMAINr   r   r   REASON_BAD_REFERERgeturlget_portr   )rS   rF   good_refererserver_portr   s       @r   _check_refererz!CsrfViewMiddleware._check_referer)  s   ,"">22? 1222	:w''GG 	: 	: 	: 8999	: '.'.111 8999 >W$$ 7888 
 
 
 
7
 
 
 
 
 	 F )-H**, 	
 K&//11! K K K#$69I9I$IJJJK "**,,K-//*6,,Dgnl;; 	G 2W^^5E5E EFFF	G 	Gs   A A"1D 4D:c                 T    |dk    rt          j        |          }d|d}d| d| dS )NPOSTzthe z HTTP headerzCSRF token from  .)r	   parse_header_name)rS   rQ   token_sourceheader_names       r   _bad_token_messagez%CsrfViewMiddleware._bad_token_messageV  sF    6!!%7EEK=+===L:,::::::r   c                    	 |                      |          }n*# t          $ r}t          d|j         d          d }~ww xY w|t          t                    d}|j        dk    r-	 |j                            dd          }n# t          $ r Y nw xY w|dk    rH	 |j	        t          j                 }n"# t          $ r t          t                    w xY wt          j        }nd}	 t          |           n<# t          $ r/}|                     |j        |          }t          |          d }~ww xY wt!          ||          s%|                     d|          }t          |          d S )NzCSRF cookie r   r.   r   csrfmiddlewaretoken	incorrect)r   rN   rf   rQ   REASON_NO_CSRF_COOKIEmethodr   r   r
   rC   r   CSRF_HEADER_NAMEr   REASON_CSRF_TOKEN_MISSINGra   r   rd   )rS   rF   rG   excrc   r   rQ   s          r   _check_tokenzCsrfViewMiddleware._check_token]  s   	>**733KK! 	> 	> 	> <sz < < <===	>    5666  >V##%,\%5%56KR%P%P""&   
  ##?
 &-\(2K%L"" ? ? ?#$=>>>?#4LL!L	( 23333! 	( 	( 	(,,SZFFF'''	( !!3[AA 	(,,[,GGF'''	( 	(sF    
?:?&B 
BBB1 1C#C3 3
D,=*D''D,c                     	 |                      |          }|||j        d<   d S d S # t          $ r t          |           Y d S w xY w)NrA   )r   rC   rN   rH   r   s      r   process_requestz"CsrfViewMiddleware.process_request  sr    
	:**733K &
 /:]+++ '& " 	* 	* 	* ))))))	*s   ' AAc                    t          |dd          rd S t          |dd          rd S |j        dv r|                     |          S t          |dd          r|                     |          S d|j        v r?|                     |          s)|                     |t          |j        d         z            S n]|                                rI	 |                     |           n2# t          $ r%}|                     ||j
                  cY d }~S d }~ww xY w	 |                     |           n2# t          $ r%}|                     ||j
                  cY d }~S d }~ww xY w|                     |          S )Nr   Fcsrf_exempt)GETHEADOPTIONSTRACE_dont_enforce_csrf_checksr   )getattrr   r   rC   r   r   REASON_BAD_ORIGINr   r   rf   rQ   r   )rS   rF   callbackcallback_argscallback_kwargsr   s         r   process_viewzCsrfViewMiddleware.process_view  s   72E:: 	4 8]E22 	4 >@@@<<(((77?? 	)
 <<((( GL((((11 ||.m1LL      	9$9##G,,,,  9 9 9||GSZ888888889	5g&&&& 	5 	5 	5<<44444444	5 ||G$$$s<   C 
D(DDDD' '
E1EEEc                 z    |j                             d          r |                     ||           d|j         d<   |S )NrB   F)rC   r   r   r   s      r   process_responsez#CsrfViewMiddleware.process_response  sE    <677 		=!!'8444 8=GL34r   N)rW   rX   rY   __doc__r   rv   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ri   ri      s         
 
 _
 Y Y _Y ) ) _)   
 
 
  @6 6 6$
 
 
4+G +G +GZ; ; ;2( 2( 2(h: : :7% 7% 7%r    r   ri   )?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]   r`   r    r\   ascii_lettersdigitsr!   r   r   r"   r9   r?   rH   rJ   rL   	ExceptionrN   ra   rd   rf   ri   r   r   r   <module>r      s      # # # # # # ! ! ! ! ! !             G G G G G G G G 8 8 8 8 8 8 8 8 $ $ $ $ $ $ 1 1 1 1 1 1 H H H H H H H H 4 4 4 4 4 4 3 3 3 3 3 3 , , , , , , ) ) ) ) ) ) 6 6 6 6 6 6		1	2	2)).99 U ; W . 1 L I  1 4  ** )FM9  4 4 4
S S S	 	 	
3 
3 
3	 	 	, , ,*" " "       

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