
    si/                     `    d Z ddlZddlmZ ddlmZ  ej                  e      Z G d d      Z	y)zH
Security middleware to handle malformed requests and protocol attacks.
    N)HttpResponseBadRequest)cachec                   6    e Zd ZdZd Zd Zd Zd Zd Zd	dZ	y)
SecurityFilterMiddlewarez
    Middleware to detect and block malformed requests, protocol confusion attacks,
    and other low-level security threats before they reach the application.
    c                 2    || _         g d| _        g | _        y )N)    s   

s   %00)get_responsemalicious_patternssuspicious_patterns)selfr	   s     ?/var/www/python-projects/worksol/horilla/security_middleware.py__init__z!SecurityFilterMiddleware.__init__   s    (#
 $&     c                    | j                  |      ra| j                  |      }t        j                  d| d|j                   d|j
                          | j                  |       t        dd      S | j                  |      ra| j                  |      }t        j                  d| d|j                   d|j
                          | j                  |       t        dd      S | j                  |      }|S )	NzMALFORMED REQUEST from z:  zMalformed requestz
text/plain)content_typezPROTOCOL CONFUSION from zProtocol error)
is_malformed_requestget_client_iploggerwarningmethodpathtemporary_block_ipr   is_protocol_confusionr	   )r   request
ip_addressresponses       r   __call__z!SecurityFilterMiddleware.__call__    s    $$W-++G4JNN4ZL7>>BRRST[T`T`Sabc ##J/)*=LYY %%g.++G4JNN5j\GNNCSSTU\UaUaTbcd ##J/)*:VV$$W-r   c                 v   	 |j                         j                  d      }| j                  D ]  }||v s y d}| j                  D ]  }||v s|dz  } t	        |j                               dkD  r|dz  }|j
                  j                  dd      }t	        |      dkD  r|dz  }|j
                  j                         D ]F  \  }}|j                  d	      st        |t              s)t        d
 |D              }|dkD  sA|dz  } n |dk\  S # t        $ r"}	t        j                  d|	        Y d}	~	yd}	~	ww xY w)zDetect malformed requests.zutf-8Tr      i  HTTP_USER_AGENT i  HTTP_c              3   H   K   | ]  }t        |      d k  s|dvsd  yw)    z	
r    N)ord).0cs     r   	<genexpr>z@SecurityFilterMiddleware.is_malformed_request.<locals>.<genexpr>W   s#     +b!APQYaPaA+bs   """      zError analyzing request: NF)get_full_pathencoder
   r   lenMETAgetitems
startswith
isinstancestrsum	Exceptionr   error)
r   r   raw_pathpatternsuspicious_count
user_agentkeyvaluecontrol_charses
             r   r   z-SecurityFilterMiddleware.is_malformed_request8   sW   )	,,.55g>H22  h& 
  !  33 *h&$)$*
 7((*+d2 A%  !))*;R@J:% A%  &ll002 "
U>>'*!%-(++bu+b(b(1,,1,!" $q(( 	LL4QC89		s:   2D D D BD D (D  D 	D8D33D8c                 B   	 |j                         }|j                  d      dk7  ry|j                  dv r=|j                  j	                  dd      j                         }d|v r|j                  dvryy	# t        $ r"}t        j                  d
|        Y d}~y	d}~ww xY w)z"Detect protocol confusion attacks.z\x16\x03T)POSTPUTPATCHCONTENT_TYPEr"   zapplication/octet-stream)z/upload/z/api/upload/Fz'Exception in protocol confusion check: N)
r,   findr   r/   r0   lowerr   r6   r   debug)r   r   r8   r   r?   s        r   r   z.SecurityFilterMiddleware.is_protocol_confusione   s    	,,.H }}\*b0 ~~!99&||//CIIK-=',,VrBr 	LLB1#FG	s   $A3 A
A3 3	B<BBc                 4   |j                   j                  d      }|r$|j                  d      d   j                         }|S |j                   j                  d      xs9 |j                   j                  d      xs |j                   j                  dd      }|S )zGet the real client IP address.HTTP_X_FORWARDED_FOR,r   HTTP_X_REAL_IPHTTP_CF_CONNECTING_IPREMOTE_ADDRr"   )r/   r0   splitstrip)r   r   x_forwarded_forips       r   r   z&SecurityFilterMiddleware.get_client_ip}   s    !,,**+AB &&s+A.446B
 	 ,,""#34 6,,""#:;6,,""="5  	r   c                 t    d| }t        j                  |d|       t        j                  d| d| d       y)z/Temporarily block an IP for malformed requests.security_block_TzTemporarily blocked IP z for z! seconds due to malformed requestN)r   setr   info)r   r   duration	block_keys       r   r   z+SecurityFilterMiddleware.temporary_block_ip   s;    %j\2			)T8,-j\xjHijkr   N)i,  )
__name__
__module____qualname____doc__r   r   r   r   r   r    r   r   r   r      s'    
&0+Z0	lr   r   )
r\   loggingdjango.httpr   django.core.cacher   	getLoggerrY   r   r   r]   r   r   <module>rb      s5     . #			8	$Al Alr   