
    ?h                        d Z ddlZddlmc mZ ddlZddlZddl	Z	ddl
Z
ddlZddlZ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 ej2                  j4                  d        Zej2                  j4                  d        Zej2                  j4                  d	        Zej2                  j4                  d
        Zej2                  j4                  d        Zej2                  j4                  d        Z ej2                  j4                  d        Z!ej2                  j4                  d        Z"ej2                  j4                  d        Z#y)a,  
test_security_penetration.py

Purpose:
  Red-team level security penetration testing suite for the Flask camera management application.
  This file implements comprehensive security vulnerability testing to validate protection against
  common attack vectors including timing attacks, SQL injection, session hijacking, privilege
  escalation, and malicious input fuzzing. Follows OWASP testing guidelines and industry
  security standards to ensure robust defense against sophisticated attacks.

Security Test Categories:
  - Timing attack resistance (username enumeration prevention)
  - SQL injection penetration testing with parameterized query validation
  - Session security (hijacking, fixation, token entropy)
  - CSRF token cryptographic strength analysis
  - File upload security and path traversal prevention
  - Rate limiting bypass techniques and header manipulation
  - Privilege escalation (horizontal and vertical)
  - Information disclosure through error messages and timing

Test Philosophy:
  Each test simulates real-world attack scenarios with malicious payloads designed to
  exploit specific vulnerabilities. Tests validate both that attacks are blocked AND
  that security measures don't interfere with legitimate usage. All tests follow
  red-team methodology with comprehensive edge case coverage.
    N)patch)session)get_db)parse_ts_from_anyc           	          |        | j                         }|d   d   }g d}g }t        d      D ]  }t        j                         }|j	                  d|dd      }	t        j                         }
|j                  |
|z
         |	j                  }d	}||k(  }|st        j                  d
|fd||f      dt        j                         v st        j                  |	      rt        j                  |	      ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}  g }|D ]/  }t        d      D ]  }t        j                         }|j	                  d|dd      }	t        j                         }
|j                  |
|z
         |	j                  }d	}||k(  }|st        j                  d
|fd||f      dt        j                         v st        j                  |	      rt        j                  |	      ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}  2 t        j                   |      }t        j                   |      }t#        ||z
        }t%        d|dd|dd|dd       |dk\  rt%        d|dd       t%        d       yt%        d|dd       y)a  
    Test that login timing is consistent regardless of username validity to prevent username enumeration.
    
    Security Risk: Timing differences between valid vs invalid usernames can allow attackers
    to enumerate valid usernames by measuring response times. Valid usernames trigger bcrypt
    operations while invalid ones fail immediately.
    
    Attack Scenario: Attacker measures login response times with various usernames to identify
    which ones exist in the system, then focuses brute-force attacks on valid accounts.
    regularusername)nonexistent1
fakeuser99
notreal123
   /loginwrongpassword123r	   passworddata.  ==z3%(py2)s
{%(py2)s = %(py0)s.status_code
} == %(py5)sresponsepy0py2py5assert %(py7)spy7N   zValid username avg: .4fzs, Invalid avg: z	s, Diff: s皙?u;   ⚠️  SECURITY VULNERABILITY DETECTED: Timing difference zs allows username enumerationuT   🔧 Recommendation: Implement secure_password_check() from security_enhancements.pyu&   ✅ Timing attack protection working: zs difference)test_clientrangetimeperf_counterpostappendstatus_code
@pytest_ar_call_reprcompare@py_builtinslocals_should_repr_global_name	_safereprAssertionError_format_explanation
statisticsmeanabsprint)app
test_usersclear_rate_limitsclient
valid_userinvalid_usernamesvalid_times_
start_timer   end_time@py_assert1@py_assert4@py_assert3@py_format6@py_format8invalid_timesr	   	valid_avginvalid_avgtiming_differences                        [C:\Users\algun\Documents\ceba web\Ceba - Github\tests\security\test_security_penetration.py#test_login_timing_attack_resistancerJ   ,   s    __FI&z2JD K2Y&&(
;;x"*/
;  $$&8j01##*s*#s****#s******x***x***#***s*******  M%qA**,J{{8$.3{ H ((*H  J!67''.3.'3....'3......8...8...'...3.......  & ,I//-0KI34 
 3/?C?PPYZkloYppq
rs D KL]^aKbb  A  	Bde67H6M\Z[    c           	      h	    |        | j                         }g d}|D ]  }|j                  d|dd      }|j                  }g d}||v }	|	st        j                  d|	fd||f      d	t        j                         v st        j                  |      rt        j                  |      nd	t        j                  |      t        j                  |      d
z  }
t        j                  d|j                   d|       dz   d|
iz  }t        t        j                  |            dx}x}	}|j                  d      j                         }g d}|D ]  }||v}|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      nddt        j                         v st        j                  |      rt        j                  |      nddz  }t        j                  d| d|       dz   d|iz  }t        t        j                  |            d}   |d   }|j                  d|d   |d   d       |j                  d       |j                         5 }|j                  d d!      }ddd       |dd" D ]  }|j                  d# |d$|dd%  d&d'(      }|j                  }d)d*g}||v }	|	st        j                  d|	fd||f      d	t        j                         v st        j                  |      rt        j                  |      nd	t        j                  |      t        j                  |      d
z  }
t        j                  d+|       dz   d|
iz  }t        t        j                  |            dx}x}	}|j                  d#| d,|d&d'(      }|j                  }g d-}||v }	|	st        j                  d|	fd||f      d	t        j                         v st        j                  |      rt        j                  |      nd	t        j                  |      t        j                  |      d
z  }
t        j                  d.|       dz   d|
iz  }t        t        j                  |            dx}x}	} y# 1 sw Y   xY w)/a  
    Test all endpoints against SQL injection attempts with sophisticated payloads.
    
    Security Risk: SQL injection allows attackers to manipulate database queries,
    potentially accessing sensitive data, escalating privileges, or destroying data.
    
    Attack Scenarios:
    - Union-based injection to extract password hashes
    - Boolean-based blind injection for data extraction  
    - Time-based blind injection for delayed responses
    - Second-order injection through stored data
    )z4' UNION SELECT password_hash FROM users WHERE '1'='1z51' UNION SELECT username, password_hash FROM users --z' OR '1'='1' --z' OR 1=1 --zadmin'--z'; WAITFOR DELAY '00:00:05' --zz' OR (SELECT COUNT(*) FROM users) > 0 AND (SELECT SUBSTRING(password_hash,1,1) FROM users WHERE username='admin') = 'a' --z'; DROP TABLE cameras; --z<'; UPDATE users SET is_admin=1 WHERE username='testuser'; --z' OR '1'='1' /*z"1'; DELETE FROM users WHERE '1'='1z%27%20OR%20%271%27%3D%271z&#39; OR &#39;1&#39;=&#39;1r   testpassr   r   )r       inz3%(py2)s
{%(py2)s = %(py0)s.status_code
} in %(py5)sr   r   zUnexpected response z for payload: 
>assert %(py7)sr   NTas_text)zsyntax errorsqlitedatabasetablecolumnselectunionpassword_hashnot inz%(py0)s not in %(py2)skeywordresponse_textr   r   z)SQL injection may have occurred - found 'z' in response for payload: 
>assert %(py4)spy4r   r	   r   /
csrf_token    /api/kamere/add?csrf_token=zTest Camera r   	camera_idcamera_nameapplication/jsonjsoncontent_typerN     z#Should reject malicious camera_id: 123456789012)   rN   i  rq   z/Unexpected response for malicious camera_name: )r#   r'   r)   r*   r+   r,   r-   r.   r/   _format_assertmsgr0   r1   get_datalowergetsession_transaction)r6   r7   r8   r9   malicious_payloadspayloadr   r@   rA   rB   rC   rD   ra   dangerous_keywordsr`   @py_format3@py_format5usersessrf   s                       rI   test_sql_injection_resistancer   j   s    __F8 &;;x"/
; 
 ##||#6|||#||||||x|||x|||#||||||:NxOcOcNddrszr{8|||||||| !))$)7==?z)G-/  K  K  K7-  K  K  K  K  K  K7  K  K  K7  K  K  K  K  K  K-  K  K  K-  K  K  K  K3\]d\e  fA  BI  AJ  2K  K  K  K  K  K  K * & i D
KK$$ K  JJsO		#	#	%XXlB/
 
& &bq);;!<ZLI/63?~1N$  ,>  ? ##bSzb#z1bbb#zbbbbbbxbbbxbbb#bbbzbbb5XY`Xa3bbbbbbbb ;;!<ZLI/=18$  ,>  ? ##x';x#';;xxx#';xxxxxxxxxxxxxx#xxx';xxx?novnw=xxxxxxxx) *	 
&	%s   R''R1c                     |        g }t        d      D ]a  }| j                         }|j                  d      }|j                         5 }|j                  dd      }|r|j	                  |       ddd       c t        |      }	t        |	      }
t        |      }|
|k(  }|st        j                  d|fd|
|f      dt        j                         v st        j                  t              rt        j                  t              ndd	t        j                         v st        j                  t
              rt        j                  t
              nd	d
t        j                         v st        j                  |      rt        j                  |      nd
t        j                  |	      t        j                  |
      dt        j                         v st        j                  t              rt        j                  t              ndd
t        j                         v st        j                  |      rt        j                  |      nd
t        j                  |      dz  }t        j                  d      dz   d|iz  }t        t        j                  |            dx}	x}
x}}|r<|D cg c]  }t        |       }}t!        |      }d}
||
k\  }|st        j                  d|fd||
f      dt        j                         v st        j                  t               rt        j                  t               nddt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |
      dz  }t        j                  d      dz   d|iz  }t        t        j                  |            dx}x}}
dj#                  |      }i }|D ]  }|j                  |d      dz   ||<    t        |      }d}||kD  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }t        j                  d| d       d!z   d"|iz  }t        t        j                  |            dx}}| j                         }|j                  d       |j                         5 }t%        |      }|j                  dd      }ddd       |d#   }|j'                  d$|d%   |d&   d'(      }|j(                  }d)}||k(  }	|	st        j                  d|	fd*||f      d+t        j                         v st        j                  |      rt        j                  |      nd+t        j                  |      t        j                  |      d,z  }d-d.|iz  } t        t        j                  |             dx}x}	}|j                  d       |j                         5 }|j                  dd      }!ddd       !s{t        j                  d/      d0z   d1d2t        j                         v st        j                  |!      rt        j                  |!      nd2iz  }"t        t        j                  |"            |j                         5 }|j                  d3      }#d}|#|u}|st        j                  d4|fd5|#|f      d6t        j                         v st        j                  |#      rt        j                  |#      nd6t        j                  |      dz  }t        j                  d7      d!z   d"|iz  }t        t        j                  |            dx}}ddd       | j                         }$|d8   }%|$j'                  d$|%d%   |%d&   d'(       |j                         5 }&|&j                  dd      }'|&j                  d3      }(ddd       |$j                         5 })|)j                  dd      }*|)j                  d3      }+ddd       '*k7  }|st        j                  d9|fd:|'|*f      d;t        j                         v st        j                  |'      rt        j                  |'      nd;d<t        j                         v st        j                  |*      rt        j                  |*      nd<d=z  },t        j                  d>      d?z   d@|,iz  }-t        t        j                  |-            d}(+k7  }|st        j                  d9|fd:|(|+f      dAt        j                         v st        j                  |(      rt        j                  |(      ndAdBt        j                         v st        j                  |+      rt        j                  |+      ndBd=z  },t        j                  dC      d?z   d@|,iz  }-t        t        j                  |-            d}d}|(|u}|st        j                  d4|fd5|(|f      dAt        j                         v st        j                  |(      rt        j                  |(      ndAt        j                  |      dz  }t        j                  dD      d!z   d"|iz  }t        t        j                  |            dx}}d}|+|u}|st        j                  d4|fd5|+|f      dBt        j                         v st        j                  |+      rt        j                  |+      ndBt        j                  |      dz  }t        j                  dE      d!z   d"|iz  }t        t        j                  |            dx}}y# 1 sw Y   xY wc c}w # 1 sw Y   xY w# 1 sw Y   uxY w# 1 sw Y    xY w# 1 sw Y   xY w# 1 sw Y   xY w)Fa  
    Test session tokens cannot be hijacked, predicted, or reused across different contexts.
    
    Security Risk: Weak session management allows attackers to impersonate users
    by stealing, predicting, or reusing session tokens.
    
    Attack Scenarios:
    - Session token prediction through weak random number generation
    - Session fixation attacks by forcing specific session IDs
    - Cross-browser session reuse
    - Session token extraction from URLs or logs
    2   re   rf   rg   Nr   )zn%(py6)s
{%(py6)s = %(py0)s(%(py4)s
{%(py4)s = %(py1)s(%(py2)s)
})
} == %(py11)s
{%(py11)s = %(py8)s(%(py9)s)
}lensetsession_tokens)r   py1r   rd   py6py8py9py11zASession tokens are not unique - potential collision vulnerabilityz
>assert %(py13)spy13    >=z0%(py3)s
{%(py3)s = %(py0)s(%(py1)s)
} >= %(py6)smintoken_lengthsr   r   py3r   z4Session tokens too short - vulnerable to brute force
>assert %(py8)sr   r      r   >z%(py0)s > %(py3)sunique_charsr   r   z-Poor character distribution in tokens - only z unique characters
>assert %(py5)sr   r   r   r	   r   r   r   r   r   r   r   r   r   zNo CSRF token after loginz
>assert %(py0)sr   post_login_csrfuser_idis notz%(py0)s is not %(py3)slogged_in_user_idz)User not logged in after successful loginlimited)!=)z%(py0)s != %(py2)stoken1token2rb   zGSession tokens shared between clients - critical security vulnerabilityrc   rd   user1_iduser2_idz User IDs shared between sessionszUser1 session has no user_idzUser2 session has no user_id)r$   r#   rw   rx   r(   r   r   r*   r+   r,   r-   r.   r/   rt   r0   r1   r   joinidr'   r)   ).r6   r7   r8   r   ir9   r   r   rf   rB   @py_assert5@py_assert10@py_assert7@py_format12@py_format14tokenr   @py_assert2rA   @py_format7@py_format9	all_charschar_countscharr   r@   @py_format4rC   client1initial_session_idinitial_csrfr~   rD   r   @py_format1r   client2user2sess1r   r   sess2r   r   r|   r}   s.                                                 rI   !test_session_hijacking_protectionr      sk     N2Y"::c?'')T,3J%%j1 *)	  >"3"#s>':#'::#':33ss>>"#ss>>':< 1?@U@=!_R_!R'___!R______s___s______=___=___!___R___)________ GGN+	D +a 81 <K  ;' r|b rrr|brrrrrr|rrr|rrrbrrr$QR^Q__q"rrrrrrr ooG KK		$	$	&$Xxxb1 
'
 i D||H$$,| H &3&3&&&&3&&&&&&8&&&8&&&&&&3&&&&&&& KK 
	$	$	&$((<4 
' 777777777?777?77777		$	$	&$ HHY/(,Y ,YYY YYYYYY YYY YYYYYY.YYYYYYY 
' ooG y!ELL*%*%!L  
	$	$	&%<,99Y' 
' 
	$	$	&%<,99Y' 
'
 Vfff6Vffffff6fff6ffffffVfffVfffffffffffxCCC8xCCCCCC8CCC8CCCCCCxCCCxCCCC!CCCCCCC?84???84??????8???8???4???!????????84???84??????8???8???4???!???????_ *) A$ 
'	&  
'	& 
'	&  
'	& 
'	&sO   	&n$$n1n6=o%Co;$o7$o*$n.	6o ooo'*o4c                   &  |        g }g }t        d      D ]r  }| j                         }|j                  |       |j                  d      }|j	                         5 }|j                  dd      }|r|j                  |       ddd       t t        |      }	d}
|	|
k\  }|st        j                  d|fd|	|
f      d	t        j                         v st        j                  t
              rt        j                  t
              nd	d
t        j                         v st        j                  |      rt        j                  |      nd
t        j                  |	      t        j                  |
      dz  }t        j                  d      dz   d|iz  }t        t        j                  |            dx}	x}}
t        |      }dt        |      t        |      z  z
  }d}	||	k(  }|st        j                  d|fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |	      dz  }t        j                  d|dz  dd      dz   d|iz  }t        t        j                  |            dx}}	|D cg c]  }t        |       }}t!        |      }t#        |      }d}	||	k\  }|st        j                  d|fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |	      dz  }t        j                  d| d      dz   d|iz  }t        t        j                  |            dx}}	d}	||	k  }|st        j                  d |fd!||	f      d"t        j                         v st        j                  |      rt        j                  |      nd"t        j                  |	      dz  }t        j                  d#| d$      dz   d|iz  }t        t        j                  |            dx}}	dj%                  |      }t        |      }t        t&        j(                  t&        j*                  z   d%z         }||z
  }t        |      }	d}
|	|
k(  }|st        j                  d|fd&|	|
f      d	t        j                         v st        j                  t
              rt        j                  t
              nd	d't        j                         v st        j                  |      rt        j                  |      nd't        j                  |	      t        j                  |
      dz  }t        j                  d(|       dz   d|iz  }t        t        j                  |            dx}	x}}
t        |      }	d)}
|	|
k\  }|st        j                  d|fd|	|
f      d	t        j                         v st        j                  t
              rt        j                  t
              nd	d*t        j                         v st        j                  |      rt        j                  |      nd*t        j                  |	      t        j                  |
      dz  }t        j                  d+t        |       d,      dz   d|iz  }t        t        j                  |            dx}	x}}
i }|D ]  }|j                  |d      dz   ||<    t        |      }|j-                         D cg c]  }||z  	 }}ddl&t1        &fd-|D               }&j3                  t        |            } || z  }!d.}	|!|	kD  }|st        j                  d/|fd0|!|	f      d1t        j                         v st        j                  |!      rt        j                  |!      nd1t        j                  |	      dz  }t        j                  d2|!d3d4      dz   d|iz  }t        t        j                  |            dx}}	|d   }|j	                         5 }|j                  dd      }"ddd       | j                         }#|#j	                         5 }"|d<   ddd       |#j5                  d5" d6d7d8d9:      }|j6                  }d;d<g}||v }$|$st        j                  d=|$fd>||f      d?t        j                         v st        j                  |      rt        j                  |      nd?t        j                  |      t        j                  |      d@z  }t        j                  dA|j6                         dBz   dC|iz  }%t        t        j                  |%            dx}x}$}y# 1 sw Y   	xY wc c}w c c}w # 1 sw Y   VxY w# 1 sw Y   5xY w)Dag  
    Test CSRF tokens are cryptographically secure with sufficient entropy.
    
    Security Risk: Weak CSRF tokens can be predicted or brute-forced,
    allowing attackers to bypass CSRF protection.
    
    Attack Scenarios:
    - Token prediction through weak randomness
    - Token collision through birthday attacks
    - Token extraction and reuse
    d   re   rf   rg   NZ   r   r   r   tokensr   z1Failed to generate sufficient tokens for analysisr   r   r   r   r   )z%(py0)s == %(py3)scollision_rater   z CSRF token collision detected - z.2fz% collision rater   r   r   )z%(py0)s >= %(py3)s
min_lengthzCSRF tokens too short: z chars (minimum 32 required)   )<=)z%(py0)s <= %(py3)s
max_lengthzCSRF tokens too long: z  chars (maximum 256 recommended)z-_z0%(py3)s
{%(py3)s = %(py0)s(%(py1)s)
} == %(py6)sunexpected_charsz+CSRF tokens contain unexpected characters: r   r   z"Insufficient character diversity: z unique charsc              3   R   K   | ]  }|d kD  s	|j                  |      z     yw)r   N)log2).0pmaths     rI   	<genexpr>z7test_csrf_token_entropy_and_strength.<locals>.<genexpr>t  s%     B[AE1tyy|#[s   
''g?r   r   entropy_ratiozLow entropy in CSRF tokens: z.3fz (should be > 0.8)ri   rr   Testrj   rm   rn   r     rP   rR   r   r   z*CSRF token reuse should be prevented, got rS   r   )r$   r#   r(   rw   rx   r   r*   r+   r,   r-   r.   r/   rt   r0   r1   r   r   maxr   stringascii_lettersdigitsvaluesr   sumr   r'   r)   )'r6   r8   r   clientsr   r9   r   r   r   r   r   rA   r   r   unique_tokensr   r@   r   rC   r   r   r   r   r   expected_charsr   	char_freqr   total_charscountfrequenciesentropymax_entropyr   original_token
new_clientrB   rD   r   s'                                         @rI   $test_csrf_token_entropy_and_strengthr   2  s     FG3Z"v::c?'')THH\2.Ee$ *)  v;Q"Q;"QQQ;"QQQQQQ3QQQ3QQQQQQvQQQvQQQ;QQQ"QQQQQQQQQQQ KM#m,s6{:;Nk>Qkkk>Qkkkkkk>kkk>kkkQkkk"B>RUCUVYBZZj kkkkkkk .44VESZVM4]#J]#J_:___:______:___:______6zlB^_______c:ccc:cccccc:ccc:cccccc 6zlBbccccccc Iy>L --=DEN#n4 gAg A%ggg Agggggg3ggg3gggggggggggg gggAggg)TUeTf'gggggggg|ii"iiiiiiiii3iii3iiiiii|iii|iiiiiiiii&H\IZH[[h$iiiiiiii I#--a014	$  i.K4=4D4D4FG4F55;&4FKG B[BBBG ))C-.Kk)Md=3ddd=3dddddd=ddd=ddd3ddd">}S>QQc ddddddd QZF 
	#	#	%,3 
& "J		'	'	)T+\ 
* !<^<LM2@QW$X,>  @H
 rC:r:-rrr:rrrrrr8rrr8rrrrrr:rrr1[\d\p\p[q/rrrrrrrrI *) 52 H  
&	%
 
*	)s0   &f!!f.5f3f8g!f+	8ggc                 x    |        | j                         }|d   }|j                  d|d   |d   d       |j                  d       |j                         5 }|j                  dd	      }d
d
d
       g d}|D ]  }	|j                  d d|	id      }
|
j                  }g d}||v }|st        j                  d|fd||f      dt        j                         v st        j                  |
      rt        j                  |
      ndt        j                  |      t        j                  |      dz  }t        j                  d|	       dz   d|iz  }t        t        j                  |            d
x}x}}|
j                  d      j                         }g d}|
j                  dv s3|
j!                         }|sGd|v sM|d   j                         }d}||v}|st        j                  d|fd||f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndd z  }t        j                  d!|	       d"z   d#|iz  }t        t        j                  |            d
x}}d$}||v}|st        j                  d|fd||f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndd z  }t        j                  d!|	       d"z   d#|iz  }t        t        j                  |            d
x}} g d%}|D ]  }|j                  d&|       }
|
j                  }g d'}||v }|st        j                  d|fd||f      dt        j                         v st        j                  |
      rt        j                  |
      ndt        j                  |      t        j                  |      dz  }t        j                  d(|       dz   d|iz  }t        t        j                  |            d
x}x}}|
j                  d      }d)}||v}|st        j                  d|fd||f      t        j                  |      d*t        j                         v st        j                  |      rt        j                  |      nd*d z  }t        j                  d+|       d"z   d#|iz  }t        t        j                  |            d
x}}d,}||v}|st        j                  d|fd||f      t        j                  |      d*t        j                         v st        j                  |      rt        j                  |      nd*d z  }t        j                  d-|       d"z   d#|iz  }t        t        j                  |            d
x}} d.}|j                  d/ |d0d1d       d2d3z  }t"        j$                  j'                  |d4| d5      }	 t)        |d6      5 }|j+                  |       d
d
d
       d7| d5}|j                  d8|       }
|
j                  }g d9}||v }|st        j                  d|fd||f      dt        j                         v st        j                  |
      rt        j                  |
      ndt        j                  |      t        j                  |      dz  }t        j                  d:      dz   d|iz  }t        t        j                  |            d
x}x}}d7| d5}	 d;d<lm}  ||      }|d
d= d>z   |j3                  d?d@      dAd	g} | D ]  }!|j                  dB|!       }
|
j                  }g d}||v }|st        j                  d|fd||f      dt        j                         v st        j                  |
      rt        j                  |
      ndt        j                  |      t        j                  |      dz  }t        j                  dC|!d
dD  dE      dz   d|iz  }t        t        j                  |            d
x}x}} y
# 1 sw Y   xY w# 1 sw Y   CxY w# t,        $ r Y Yw xY w# t4        $ r Y y
w xY w)Fa  
    Test file upload security including path traversal prevention and malicious file handling.
    
    Security Risk: Insecure file handling allows path traversal attacks, malicious file uploads,
    and potential remote code execution.
    
    Attack Scenarios:
    - Path traversal to access files outside allowed directories
    - Upload of executable files (PHP, JSP, etc.)
    - Filename injection with special characters
    - Oversized file uploads (DoS)
    r   r   r	   r   r   r   re   rf   rg   N)z../../../etc/passwdz$..\..\..\windows\system32\config\samz....//....//....//etc/passwdz$User-photos/../../sensitive_file.txtzUser-photos/../app.pyz'%2e%2e%2f%2e%2e%2f%2e%2e%2fetc%2fpasswdz#..%252f..%252f..%252fetc%252fpasswd/api/image/delete?csrf_token=relrm   rn   rN   r     rP   rR   r   r   zPath traversal not blocked: rS   r   TrT   )zaccess deniedzpermission deniedzfile not found	forbidden)rN   r   messageetcr]   )z%(py1)s not in %(py3)s)r   r   z.Path traversal response reveals system paths: r   r   windows)
ztest.phpztest.jspztest.aspztest.pyz!<script>alert('xss')</script>.jpgz'; DROP TABLE images; --.jpgz	test .jpgaC  very_long_filename_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.jpgz	.htaccessz
web.configz/slika?rel=User-photos/)rs   rN   r   r   z,Unexpected response for malicious filename: z<script>ra   z!XSS vulnerability with filename: z
DROP TABLEz+SQL injection vulnerability with filename: rr   ri   zSecurity Test Camerarj      Xi   PICT_20231201_120000_z.jpgwbz!User-photos/PICT_20231201_120000_/slika?rel=)rs   rN   r   r   i  rq   zLarge file handling failedr   )generate_media_tokenAAAAAABfake_token_12345z/media/z"Manipulated media token accepted:    z...)r#   r'   rw   rx   r)   r*   r+   r,   r-   r.   r/   rt   r0   r1   ru   rv   get_jsonospathr   openwriteOSErrorapp_modules.helpersr   replaceImportError)"r6   r7   temp_staticr8   r9   r~   r   rf   path_traversal_payloadsrz   r   r@   rA   rB   rC   rD   ra   r{   r   r   @py_assert0r   r   malicious_filenamesfilenametest_camera_idlarge_file_contentlarge_file_pathfrel_pathr   legitimate_tokenmanipulated_tokens	bad_tokens"                                     rI   ,test_file_upload_security_and_path_traversalr    s    __F i D
KK$$ K  JJsO		#	#	%XXlB/
 
& +;;!>zlK$)7#3+=  ?
 ##``#6```#``````x```x```#``````:VW^V_8```````` !))$)7==?b :-$$&D	T)y///1guG+ggguGggguggggggGgggGgggg/]^e]f-ggggggg ky/kkkykkkykkkkkkkkkkkkk3abiaj1kkkkkkkk' +, (:: 7zBC ##v';v#';;vvv#';vvvvvvxvvvxvvv#vvv';vvv?kltku=vvvvvvvv !))$)7^z.^^^z^^^z^^^^^^^^^^^^^2ST\S]0^^^^^^^j|=0jjj|=jjj|jjjjjj=jjj=jjjj4_`h_i2jjjjjjjj ( $N KK-j\:#1BXY/  1
 !12 ggll;2GGWW[0\]O/4(AGG&' ) 7~6FdK::H:67 ##c'Ec#'EEccc#'Eccccccxcccxccc#ccc'EcccGcccccccc 3>2B$GH< 09 Sb!G+$$S#.	
 ,IzzGI;"78H''t?t'?:ttt'?tttttt8ttt8ttt'ttt?ttt>`ajknlnao`pps<tttttttt ,Y 
&	%V )(  8  sJ   b1b =bDb D+b- bbb 	b*)b*-	b98b9c                     |        |d   }g d}d}|D ]T  }| j                         }t        d      D ]4  }|j                  d|d   ddd	|i
      }	|	j                  dk(  s/|dz  } T V |dk(  rt	        d       t	        d       g d}
 |        | j                         }d}t        d      D ]B  }|
|t        |
      z     }|j                  d|d   ddd|i
      }	|	j                  dk(  s@d} n |st	        d        |        d}t        d      D ]Q  }| j                         }t        d      D ]1  }|j                  d|d   dd      }	|	j                  dk(  s,|dz  } Q S |dk(  rt	        d        |        | j                         }|j                  d|d   |d   d      }	|	j                  }d}||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  |	      rt        j                  |	      ndt        j                  |      t        j                  |      dz  }t        j                  d      dz   d|iz  }t        t        j                  |            d x}x}}g }d!}|	j                  }||v }|}|s$|	j                  }|j                   }d"} ||      }|}|st        j                  d#|fd$||f      t        j                  |      dt        j                         v st        j                  |	      rt        j                  |	      ndt        j                  |      d%z  }d&d'|iz  }|j#                  |       |sd(dt        j                         v st        j                  |	      rt        j                  |	      ndt        j                        t        j                        t        j                        t        j                        d)z  }|j#                  |       t        j$                  |d      i z  }t        j                  d*      d+z   d,|iz  } t        t        j                  |             d x}x}x}x}x}x}x}x}}y )-a  
    Test rate limiting cannot be bypassed via header manipulation or distributed techniques.
    
    Security Risk: Bypassable rate limiting allows brute force attacks, credential stuffing,
    and denial of service attacks.
    
    Attack Scenarios:
    - X-Forwarded-For header spoofing
    - User-Agent rotation
    - Multiple source IP simulation
    - Session-based bypass attempts
    r   )z1.2.3.4z5.6.7.8z
9.10.11.12z13.14.15.16z17.18.19.20r      r   r	   wrongpasswordr   zX-Forwarded-For)r   headersrO   r   zLNote: Rate limiting may be disabled for localhost IPs (expected for testing)zOThis is acceptable - localhost exemption is intentional for testing environment)z<Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36zBMozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36z2Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36zKMozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15zAMozilla/5.0 (Android 11; Mobile; rv:88.0) Gecko/88.0 Firefox/88.0F   z
User-AgentTr      r   r   r   r   r   r   r   z,Legitimate login blocked after rate limitingrS   r   N/selectre   rP   z0%(py3)s in %(py7)s
{%(py7)s = %(py5)s.location
}r   r   r   %(py9)sr   zi%(py19)s
{%(py19)s = %(py15)s
{%(py15)s = %(py13)s
{%(py13)s = %(py11)s.location
}.endswith
}(%(py17)s)
})r   r   py15py17py19zLogin redirect failedz
>assert %(py22)spy22)r#   r$   r'   r)   r5   r   r*   r+   r,   r-   r.   r/   rt   r0   r1   locationendswithr(   _format_boolop)!r6   r7   r8   r~   spoofed_ipsfailed_attempts
spoofed_ipr9   attemptr   user_agentsrate_limitedr   
user_agentrate_limited_sessionssession_numfresh_clientr@   rA   rB   rC   rD   r   @py_assert6r  @py_assert12@py_assert14@py_assert16@py_assert18@py_format10@py_format20@py_format21@py_format23s!                                    rI   "test_rate_limiting_bypass_attemptsr6  !  s    i D UKO!
" RyG{{837
3CQ`&a*;Z)H # JH ##s*1$ !	 " !\]_`K __FL2Y S%5!56
;;x/3J/?_"]&2J%?  A 3&L  \]  Ry" QxG{{837
3CQ`&a # cH ##s*%*%  	 ! !\] ??$L  $$1  H V3V3&VVV3VVVVVV8VVV8VVVVVV3VVV(VVVVVVVV f9e))e9))eX->->e->-G-Gee-G-Le-Leee9)eee9eeeeeeeeeeee)eeeeeeeeeeXeeeXeee->eee-Geeeeee-LeeeeeeeeeNeeeeeeeeerK   c                   #  |        |d   }|d   }| j                         }| j                         }|j                  d|d   |d   d       |j                  d|d   |d   d       |j                  d       |j                         5 }|j                  d	d
      }ddd       |j                  d       |j                         5 }|j                  d	d
      }	ddd       d#|j                  d #ddd      }
|
j                  dk7  rt        d|
j                   d       yd}|j                  d	 |ddd      }
|
j                  dk7  rt        d|
j                   d       y|j                  d      }
|
j                  dk(  r|
j                         }|j                  dg       D cg c]  }|d   	 }}||v }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      nddt        j                         v st        j                  |      rt        j                  |      nddz  }t        j                  d       d!z   d"|iz  }t        t        j                  |            d}#|v}|st        j                  d#|fd$#|f      d%t        j                         v st        j                  #      rt        j                  #      nd%dt        j                         v st        j                  |      rt        j                  |      nddz  }t        j                  d&      d!z   d"|iz  }t        t        j                  |            d}nM|
j                  d'k(  r%t        d(|
j                   d)       t        d*       yt        d+|
j                   d,       |j                  d-|	 #d.dd      }
|
j                  }d/d0g}||v }|st        j                  d|fd1||f      d2t        j                         v st        j                  |
      rt        j                  |
      nd2t        j                  |      t        j                  |      d3z  }t        j                  d4      d5z   d6|iz  }t        t        j                  |            dx}x}}|j                  d7|	 d#id      }
|
j                  }d/d0g}||v }|st        j                  d|fd1||f      d2t        j                         v st        j                  |
      rt        j                  |
      nd2t        j                  |      t        j                  |      d3z  }t        j                  d8      d5z   d6|iz  }t        t        j                  |            dx}x}}|j                  d      }
|
j                  }d}||k(  }|st        j                  d9|fd:||f      d2t        j                         v st        j                  |
      rt        j                  |
      nd2t        j                  |      t        j                  |      d3z  }d;d6|iz  }t        t        j                  |            dx}x}}|
j                         }|j                  dg       D cg c]  }|d   	 }}#|v }|st        j                  d|fd#|f      d%t        j                         v st        j                  #      rt        j                  #      nd%d<t        j                         v st        j                  |      rt        j                  |      nd<dz  }t        j                  d=      d!z   d"|iz  }t        t        j                  |            d}t!        #fd>|d   D        d      }d}||u}|st        j                  d?|fd@||f      dAt        j                         v st        j                  |      rt        j                  |      ndAt        j                  |      dBz  }t        j                  dC      dDz   dE|iz  }t        t        j                  |            dx}}dF}|dG   }||v}|st        j                  d#|fdH||f      t        j                  |      t        j                  |      dIz  }t        j                  dJ      dKz   dL|iz  }t        t        j                  |            dx}x}}dMdNlm} | j'                         5  dOdPi}| j(                  j                  dQdR      }	  ||#|      }  ||||      }!	 ddd       |j                  dU        }
|
j                  }d/d0g}||v }|st        j                  d|fd1||f      d2t        j                         v st        j                  |
      rt        j                  |
      nd2t        j                  |      t        j                  |      d3z  }t        j                  dV      d5z   d6|iz  }t        t        j                  |            dx}x}}|j                  dW|	 dX| id      }
|
j                  }g dY}||v }|st        j                  d|fd1||f      d2t        j                         v st        j                  |
      rt        j                  |
      nd2t        j                  |      t        j                  |      d3z  }t        j                  dZ      d5z   d6|iz  }t        t        j                  |            dx}x}}y# 1 sw Y   
xY w# 1 sw Y   
xY wc c}w c c}w # t*        t,        f$ r+}"t        dS|"        t        dT       Y d}"~"ddd       yd}"~"ww xY w# 1 sw Y   WxY w)[a  
    Test users cannot access other users' data via parameter manipulation.
    
    Security Risk: Insufficient authorization allows users to access data belonging
    to other users by manipulating request parameters.
    
    Attack Scenarios:
    - Camera ID enumeration to access other users' cameras
    - User ID manipulation in admin functions
    - Direct object reference attacks
    r   r   r   r	   r   r   r   re   rf   rg   N111111111111ri   zUser1 Private Camerarj   rm   rn   rs   z"User1 camera creation failed with z" - this may indicate system issues222222222222zUser2 Private Cameraz"User2 camera creation failed with /api/kamerecamerasrk   rP   )z%(py0)s in %(py2)suser2_camera_id
camera_idsrb   z!User2 cannot see their own camerarc   rd   r]   r_   user1_camera_idzLUser2 can see User1's camera - horizontal privilege escalation vulnerabilityrq   zAPI returned server error (z() - skipping privilege escalation checkszLThis might indicate a legitimate server issue rather than a security problemzCamera API returned z( - may require additional authenticationz/api/kamere/rename?csrf_token=zHACKED BY USER2r   r   rR   r   r   zAUser2 can modify User1's camera - critical security vulnerabilityrS   r   z/api/kamere/delete?csrf_token=zAUser2 can delete User1's camera - critical security vulnerabilityr   r   r   user1_camera_idsz.User1's camera was affected by User2's actionsc              3   4   K   | ]  }|d    k(  s|  yw)rk   N )r   camr>  s     rI   r   z7test_horizontal_privilege_escalation.<locals>.<genexpr>  s!     h(@CDTXgDg(@s   r   r   user1_camerar   zUser1's camera not foundr   r   HACKEDrl   )z%(py1)s not in %(py4)sr   rd   z$User1's camera was modified by User2
>assert %(py6)sr   r   )create_test_image_filer   s!   PNG

   IHDR         wSUSER_PHOTOS_DIR_REALz/tmpzImage file creation failed: zISkipping image-based privilege escalation tests due to file system issuesr   z?User2 can view User1's images - horizontal privilege escalationr   r   r   z8User2 can delete User1's images - critical vulnerability)r#   r'   rw   rx   r)   r5   r   r*   r+   r,   r-   r.   r/   rt   r0   r1   nexttests.functional.test_imagesrG  app_contextconfigr   FileNotFoundError)$r6   r7   r8   user1r   r   r   r   csrf_token1csrf_token2r   r<  cameras_datarB  r=  r@   r|   r}   rA   rB   rC   rD   user1_camerasr?  rC  r   r   r  r   rG  sample_image_datatemp_diruser1_image_pathuser2_image_pather>  s$                                      @rI   $test_horizontal_privilege_escalationrX    s     y!Ey!EooGooG LLU:->ER\L] ^L_LLU:->ER\L] ^L_ KK		$	$	&$hh|R0 
' KK		$	$	&$hh|R0 
' %O||9+G.=Nd e(:  <H s"283G3G2HHjkl %O||9+G.=Nd e(:  <H s"283G3G2HHjkl {{=)H s"((*2>2B2B9b2QR2Q3c+&2Q
R *,QQQ*QQQQQQQQQQQQQQQ*QQQ*QQQQ.QQQQQQQj0  	A  	A  	Aj  	A  	A  	A  	A  	A  	A  	A  	A  	A  	A  	A  	A  	A  	A  	Aj  	A  	A  	Aj  	A  	A  	A  	A  3A  	A  	A  	A  	A  	A  	A				$+H,@,@+AAijk\] 	$X%9%9$::bcd ||<[MJ.=N_ `(:  <H
 rC:r:-rrr:rrrrrr8rrr8rrrrrr:rrr/rrrrrrrr ||<[MJ!,o >(:  <H
 rC:r:-rrr:rrrrrr8rrr8rrrrrr:rrr/rrrrrrrr {{=)H&3&3&&&&3&&&&&&8&&&8&&&&&&3&&&&&&&%%'M4A4E4EiQS4TU4TSK(4TU..```?.``````?```?``````.```.````0``````` hi(@hjnoL#?<t#???<t??????<???<???t???%???????^<6^866^^^86^^^8^^^6^^^8^^^^^^^^ D		#  &J  K ::>>"8&A	5hQbc5hQbc 
 {{[)9(:;<H pC:p:-ppp:pppppp8ppp8pppppp:ppp/pppppppp ||;K=I!&(8 9(:  <H
 n?n?2nnn?nnnnnn8nnn8nnnnnn?nnn4nnnnnnnna 
'	& 
'	&> SH V0 *+ 	045]^ 
		 
	sT   mm,2m9m>4!o nm),m6n=n8+o 8n==o  o
c                 #    |        |d   }|d   }| j                         }| j                         }|j                  d|d   |d   d      }|j                  }d}	||	k(  }
|
st        j                  d	|
fd
||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }dd|iz  }t        t        j                  |            dx}x}
}	|j                  d|d   |d   d      }|j                  }d}	||	k(  }
|
st        j                  d	|
fd
||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }dd|iz  }t        t        j                  |            dx}x}
}	|j                  d       |j                         5 }|j                  dd      }ddd       |j                  d       |j                         5 }|j                  dd      }ddd       |j                  d      }|j                  }ddg}	||	v }
|
st        j                  d|
fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }t        j                  d      dz   d|iz  }t        t        j                  |            dx}x}
}	|j                  dk(  rd}|j                  }	||	v}|st        j                  d|fd||	f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |	      dz  }t        j                  d      dz   d|iz  }t        t        j                  |            dx}x}}	g }d}|j                  }||v }	|	}|	sd}|j                  }||v }|}|st        j                  d|	fd||f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      d z  }d!d"|iz  }|j                  |       |	st        j                  dfd#f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      d$z  }d%d&|iz  }|j                  |       t        j                   |d'      i z  }t        j                  d(      d)z   d*|iz  }t        t        j                  |            dx}x}x}x}	x}x}x}}|j                  d+ d,d-d      }|j                  }g d.}	||	v }
|
st        j                  d|
fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }t        j                  d/      dz   d|iz  }t        t        j                  |            dx}x}
}	| j#                         5  t%               }|j'                  d0d1      j)                         }d}||u }|st        j                  d2|fd3||f      d4t        j                         v st        j                  |      rt        j                  |      nd4t        j                  |      d5z  }t        j                  d6      d7z   d8|iz  }t        t        j                  |            dx}}ddd       d9d:|d;    d<d:|d;    d=g}|D ]  }|j                  |      }|j                  }g d.}	||	v }
|
st        j                  d|
fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }t        j                  d>|       dz   d|iz  }t        t        j                  |            dx}x}
}	|j                  d?k(  s|j+                         } g }d}	| |	u }
|
}|
st-        |       }d@}!||!k(  }|}|st        j                  d2|
fdA| |	f      dBt        j                         v st        j                  |       rt        j                  |       ndBt        j                  |	      dCz  }dDd|iz  }|j                  |       |
st        j                  d	fdE!f      dFt        j                         v st        j                  t,              rt        j                  t,              ndFdBt        j                         v st        j                  |       rt        j                  |       ndBt        j                  |      t        j                  |!      dGz  }"dHdI|"iz  }#|j                  |#       t        j                   |d'      i z  }t        j                  dJ|       dKz   dL|iz  }$t        t        j                  |$            dx}x}x}
x}	x}x}}! |d;   }%dMdN|% i fdMdO|% dPdQifdMd:|% dR| dSdTifg}&|&D ]  \  }'}(} |'dMk(  r|j                  |(|       }n|j                  |(      }|j                  }g d.}	||	v }
|
st        j                  d|
fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }t        j                  dU|' dV|(       dz   d|iz  }t        t        j                  |            dx}x}
}	 | j#                         5  t%               }|j'                  d0|d   f      j)                         })|)5t/        dW|d           |j'                  dX|d   f      j)                         })d}|)|u}|st        j                  dY|fdZ|)|f      d[t        j                         v st        j                  |)      rt        j                  |)      nd[t        j                  |      d5z  }t        j                  d\|d    d]      d7z   d8|iz  }t        t        j                  |            dx}}|)d   }|d   }
||
k(  }|st        j                  d	|fd^||
f      t        j                  |      t        j                  |
      d_z  }*t        j                  d`      daz   db|*iz  }+t        t        j                  |+            dx}x}}
ddd       |j                         5 }|j                  dc      },dd|de<   dd|d<   d|df<   ddd       |j                  d      }|j                  d?k(  r|j                  d+| dgdgd      }|j                  }g d.}	||	v }
|
st        j                  d|
fd||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }t        j                  dh      dz   d|iz  }t        t        j                  |            dx}x}
}	| j#                         5  t%               }|j'                  d0di      j)                         }-|-t/        dj       t/        dk       t/        dl       |j'                  dmdi       |j1                          dn}|sNt        j                  do      dpz   dqt        j                  |      iz  }.t        t        j                  |.            d}ddd       |j                         5 },|dc<   de|v r|de= ddd       |j                  d      }|j                  }d?}	||	k(  }
|
st        j                  d	|
fd
||	f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |	      dz  }t        j                  dr      dz   d|iz  }t        t        j                  |            dx}x}
}	y# 1 sw Y   xxY w# 1 sw Y   IxY w# 1 sw Y   	xY w# 1 sw Y   txY w# 1 sw Y   HxY w# 1 sw Y   `xY w# 1 sw Y   HxY w)sa  
    Test regular users cannot access admin functions via direct URLs or parameter manipulation.
    
    Security Risk: Insufficient privilege checks allow regular users to access
    administrative functions, potentially compromising the entire system.
    
    Attack Scenarios:
    - Direct access to admin URLs
    - Admin function calls via API manipulation
    - Role modification through parameter tampering
    r   adminr   r	   r   r   r   r   r   r   r   r   r   r   Nre   rf   rg   z/adminr   rP   rR   z#Regular user can access admin panelrS   r]   )z4%(py1)s not in %(py5)s
{%(py5)s = %(py3)s.location
})r   r   r   z%Regular user redirected to admin arear  loginr  r  r  r   )z4%(py12)s in %(py16)s
{%(py16)s = %(py14)s.location
})py12py14py16z%(py18)spy18r   z.Invalid redirect for unauthorized admin accessz
>assert %(py21)spy21z/admin/add_user?csrf_token=hackeduser123hackedpass123)r   r   r   z0Regular user can create users via admin endpointz&SELECT * FROM users WHERE username = ?)ra  )is)z%(py0)s is %(py3)shacked_userr   zHRegular user successfully created a user - critical privilege escalationr   r   z/admin/users.jsonz/admin/user/r   z/cameras.jsonz/images.jsonz#Regular user can access admin API: rs   r   )z%(py2)s is %(py5)sr   )r   r   z%(py7)s)z4%(py12)s
{%(py12)s = %(py9)s(%(py10)s)
} == %(py15)sr   )r   py10r\  r  z%(py17)sr  z"Regular user got admin data from: z
>assert %(py20)spy20POSTz/admin/remove_user/z/admin/change_password/new_password	hacked123z/cameras/delete?csrf_token=rk   rr   z'Regular user can perform admin action:  z5Admin user check by ID failed, checking by username: z7SELECT * FROM users WHERE username = ? AND is_admin = 1r   r   admin_checkzAdmin user 'z(' was affected by regular user's actions)z%(py1)s == %(py4)srE  zAdmin user data corruptedrF  r   r   Tis_adminrolesessionhack123z*Session manipulation allowed admin actions)rn  uQ   🚨 CRITICAL SECURITY VULNERABILITY: Session manipulation allowed user creation!z]The application should validate admin privileges against the database, not just session data.z:This is a real security issue that needs immediate fixing.z$DELETE FROM users WHERE username = ?FzCSession manipulation allowed user creation - CRITICAL VULNERABILITYz
>assert %(py1)sr   z<Admin functionality broken during privilege escalation tests)r#   r'   r)   r*   r+   r,   r-   r.   r/   r0   r1   rw   rx   rt   r   r(   r"  rK  r   executefetchoner   r   r5   commit)/r6   r7   r8   regular_user
admin_userregular_clientadmin_clientr   r@   rA   rB   rC   rD   r   regular_csrf
admin_csrfr  r   r-  @py_assert11@py_assert15@py_assert13r2  @py_format17@py_format19r3  @py_format22dbrd  r   admin_endpointsendpointr   r/  @py_format16@py_format18r4  target_user_idadmin_actionsmethodurlrk  r}   r   original_user_idsession_hack_user@py_format2s/                                                  rI   "test_vertical_privilege_escalationr  #  sz     i(LG$J__&N??$L ""8 , ,3" H &3&3&&&&3&&&&&&8&&&8&&&&&&3&&&&&&&   z*z*1  H &3&3&&&&3&&&&&&8&&&8&&&&&&3&&&&&&& s		+	+	-xxb1 
. X		)	)	+tXXlB/
 
, !!(+H TC:T:-TTT:TTTTTT8TTT8TTTTTT:TTT/TTTTTTTTs"Yx00Yx00YYYx0YYYxYYYYYYxYYYxYYY0YYY2YYYYYYYYyH--y--H<M<M<M1My-yHH-<MHH<MO ""%@#O2A2A($ # %H f?f?2fff?ffffff8fff8ffffff?fff4ffffffff 
	Xjj!IK]^ggi"n{d"nnn{dnnnnnn{nnn{nnndnnn$nnnnnnn 
 	
|D)*-8
|D)*,7O $!%%h/ ##hh#6hhh#hhhhhhxhhhxhhh#hhhhhh:]^f]g8hhhhhhhh 3&$$&Db4b44<b3t9bb9>bbbb44bbbbbb4bbb4bbb4bbbbbbb9bbbbbb3bbb3bbbbbbtbbbtbbb9bbbbbbbbbbbbb5WX`Wa3bbbbbbbbb $  %N 
&~&67<	*>*:;nk=Z[	<//J<.Y\giw[xyM +TV%**3T*:H%))#.H ##pp#6ppp#ppppppxpppxppp#pppppp:abhaiijknjo8pppppppp + 
	Xjj!IJWaLbKdennpI*U_J`Iabc**%^aklvaw`yz  D  D  FK"&w{$&www{$wwwwww{www{www$www,z*7M6NNv(wwwwwww:&]*Z*@]&*@@]]]&*@]]]&]]]*@]]]B]]]]]]]] 
  
	+	+	-88I.ZWV 
. !!(+H s"!&&)D\N'S6F6F,( ' ) ##dd#6ddd#ddddddxdddxddd#dddddd8dddddddd __B "

+SUh i r r t ,ijuvRS

ACVW		cuccccccuccccc  
	+	+	-*YZ  
. )Hf3f3&fff3ffffff8fff8ffffff3fff(ffffffffA 
.	- 
,	+. 
	V 
	  
.	-,  
.	-sm   AF$AF1,C&AF>GAG1!AGCAG%BAG2F$AF.F1AF;F>AGGAGGAG"G%AG/G2AG<c                 v    |        | j                         }ddddddifddddd	fddd
ddfg}g d}|D ]  ^}}}|r|d   nd}	|dk(  r|j                  ||	      }
n|j                  |      }
|
j                  d      j	                         }ddl}|D ]K  }|j                  ||      }t        |      }d}||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  t              rt        j                  t              nddt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |      dz  }t        j                  d| d| d| d|dd        dz   d|iz  }t        t        j                   |            dx}x}}N  |j                  d      }
|
j"                  }d d!g}|D ]  }||v s	||   j	                         }g d"}|D ]  }||v}|st        j                  d#|fd$||f      d%t        j                         v st        j                  |      rt        j                  |      nd%d&t        j                         v st        j                  |      rt        j                  |      nd&d'z  }t        j                  d(| d)||          d*z   d+|iz  }t        t        j                   |            d}  |d,   d-   }g d.}g d/}|D ]  } g }!t%        d0      D ]S  }"t'        j(                         }#|j                  | d-|i1      }
t'        j(                         }$|!j+                  |$|#z
         U g }%|D ]S  }&t'        j(                         }#|j                  | d-|&i1      }
t'        j(                         }$|%j+                  |$|#z
         U |!s|%st-        j.                  |!      }'t-        j.                  |%      }(t1        |'|(z
        })d2}|)|k  }|st        j                  d3|fd4|)|f      d5t        j                         v st        j                  |)      rt        j                  |)      nd5t        j                  |      d6z  }*t        j                  d7|  d8|)d9d:      d;z   d<|*iz  }+t        t        j                   |+            dx}} |j                  d|d,   d-   |d,   d=   d	1       |j                  d       |j3                         5 },|,j                  d>d      }-ddd       g d?}.g d@}/|.D ]B  } |j                  |       }
|
j4                  dAk(  s%	 |
j7                         }	|	r
t9        |	      j	                         }0|/D ]  }1|1|0v}|st        j                  d#|fd$|1|0f      dBt        j                         v st        j                  |1      rt        j                  |1      ndBdCt        j                         v st        j                  |0      rt        j                  |0      ndCd'z  }t        j                  dD|1 dE|        d*z   d+|iz  }t        t        j                   |            d} E dGdHdIdddddfg}2|2D ]Q  ^}}}|r|d   nd}	|dk(  r|j                  ||	      }
n|j                  |      }
|
j                  d      j	                         }g dJ}3|3D ]  }4|4|v}|st        j                  d#|fd$|4|f      dKt        j                         v st        j                  |4      rt        j                  |4      ndKdFt        j                         v st        j                  |      rt        j                  |      ndFd'z  }t        j                  dL| d| d8|4       d*z   d+|iz  }t        t        j                   |            d} T y# 1 sw Y   xY w# t:        $ r |
j                  d      j	                         }|/D ]  }1|1|v}|st        j                  d#|fd$|1|f      dBt        j                         v st        j                  |1      rt        j                  |1      ndBdFt        j                         v st        j                  |      rt        j                  |      ndFd'z  }t        j                  dD|1 dE|        d*z   d+|iz  }t        t        j                   |            d} Y w xY w)Ma  
    Test for information disclosure through error messages, timing, and metadata leakage.
    
    Security Risk: Applications may leak sensitive information through detailed error messages,
    timing differences, or metadata exposure.
    
    Attack Scenarios:
    - Error message analysis to reveal system information
    - Timing analysis to infer system state
    - Metadata extraction from responses
    - Debug information exposure
    )GETz/nonexistent_endpoint)rg  z/api/invalid_apirg  z/api/kamere/addinvalidro   r     xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxr   rr   rg   rj   )rV   rW   rX   rY   
constraintzforeign keyz/usr/z/etc/z/var/zc:\\system32	traceback	exceptiondebugzstack tracezline \d+flaskwerkzeugpython__file__r   N)ro   TrT   r   r   r   matchesr   zInformation disclosure in rj  z	: found 'z' - r   r   r   re   ServerzX-Powered-By)r  r  r  apachenginxr]   r_   dangerous_valueheader_valuerb   zHeader z reveals technology: rc   rd   r   r	   )r
   	fakeuser2notreal3)z/reset_passwordz/forgot_passwordz
/api/resetrh   r   r"   )<)z%(py0)s < %(py3)stiming_diffr   zTiming difference in z: r    zs (user enumeration possible)r   r   r   rf   )r:  z/get_available_camerasz/get_marker_locations)
r   r\   secretr   keysalthashinternal_idsystem_pathdatabase_pathrs   sensitive_fieldresponse_strzSensitive field 'z' exposed in ra   )r  z/debug)r  z/_debug)r  z/console)z
debug modezwerkzeug debuggerconsoler  interactivezpython shell	indicatorzDebug information exposed via )r#   r'   rw   ru   rv   refindallr   r*   r+   r,   r-   r.   r/   rt   r0   r1   r  r$   r%   r&   r(   r2   r3   r4   rx   r)   r   str	Exception)5r6   r7   r8   r9   error_inducing_requestsdangerous_info_patternsr  r  argsr   r   ra   r  patternr  r   r   rA   r   r   r  dangerous_headersheaderr  dangerous_valuesr  r@   r|   r}   existing_usernon_existing_userspassword_reset_endpointsr  existing_timesr=   startendnonexisting_timesr	   existing_avgnonexisting_avgr  r   rC   r   rf   api_endpointssensitive_fieldsr  r  debug_triggersdebug_indicatorsr  s5                                                        rI   +test_information_disclosure_vulnerabilitiesr    s    __F
 	)$ 
"Y$78	

KL 
".QS$TU< 6dtAwDV{{3T{2Hzz#H ))$)7==? 	.Gjj-8Gw<t1t<1$ttt<1tttttt3ttt3ttttttwtttwttt<ttt1ttt(B6(!C5PYZaYbbfgnoqpqgrfs&tttttttt / 6" zz#HG 	
 $W"6?002LQ#3&l:tttltttttttttttttttltttlttttgfXMbcjkqcrbs<ttttttt $4 $ y)*5MB  -qA%%'E{{8:}2M{NH##%C!!#+.	  *H%%'E{{8:x2H{IH##%C$$S5[1	 + /%??>:L(oo.?@Ol_<=K "&y;%yyy;yyyyyy;yyy;yyyyyy)>xj;WZJ[[x'yyyyyyyy5 -< KKy)*5y)*5 K  JJsO		#	#	%XXlB/
 
&M "::h'3&~((*#&t9??#4L+;.lB  A  A  Al  A  A  A  A  A  A  A  A  A  A  A  A  A  A  Al  A  A  Al  A  A  A  AFWXgWhhuv~u  EA  A  A  A  A  A  A ,< "* 		")D$QR	N -dtAwDV{{3T{2Hzz#H ))$)7==?
 *IM1ooo9Moooooo9ooo9ooooooMoooMoooo5STZS[[\]`\aacdmcn3ooooooo *) -e 
&	%F  ~ ( 1 1$ 1 ? E E G'7O*-?}}}?-}}}}}}?}}}?}}}}}}-}}}-}}}}CTUdTeers{r|A}}}}}}} (8~s    =`D``Dd87d8)$__doc__builtinsr,   _pytest.assertion.rewrite	assertionrewriter*   pytestr%   randomr   hashlibhmacr   tempfilesqlite3r2   unittest.mockr   r  r   app_modules.dbr   r  r   marksecurityrJ   r   r   r   r  r6  rX  r  r  rA  rK   rI   <module>r     sp  6        	      ! 1 :\ :\z \y \y~ d@ d@N [s [s| L L^ of ofd Ko Ko\ eg egP Wp WprK   