
    h<                     t   d 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mZm	Z	m
Z
 ddlmZ ddlmZ dededee	   d	efd
Zde
de
d	eeee   eeeef      f   fdZddeded	efdZded	eeee   f   fdZd ded	efdZdededed	efdZd!deded	efdZde	ee
f   de	ee	f   d	eeee   e	ee
f   f   fdZd Zy)"a;  
security_enhancements.py

Purpose:
  Advanced security enhancement functions that implement protection against sophisticated
  attack vectors identified during red-team security auditing. This module provides
  timing attack protection, input validation hardening, and security-focused error
  handling to maintain the highest security standards across the application.

Security Enhancements:
  - Timing attack resistant authentication checks (username enumeration prevention)
  - Geographic coordinate validation with proper bounds checking
  - Security-focused error message sanitization to prevent information disclosure
  - Enhanced input validation for all user-controllable parameters
  - Cryptographic helper functions for secure token generation and validation

Implementation Philosophy:
  All functions follow defense-in-depth principles with multiple validation layers.
  Error handling is designed to prevent information leakage while maintaining
  system functionality. Security measures are transparent to legitimate users
  but effectively block malicious attempts.
    N)TupleOptionalDictAny)wraps)current_appusernamepassworduser_rowreturnc                     d}|r@|d   r;|d   j                  d      }t        j                  |j                  d      |      }|S t        j                  |j                  d      |j                  d             d}|S )a  
    Timing-attack resistant password verification.
    
    Prevents username enumeration by ensuring consistent timing regardless of whether
    the username exists in the database. Always performs bcrypt operation to maintain
    constant time complexity.
    
    Args:
        username: Username being authenticated
        password: Password to verify
        user_row: User database row (None if user doesn't exist)
    
    Returns:
        bool: True if authentication successful, False otherwise
    
    Security Features:
        - Constant time execution regardless of username validity
        - Secure password hashing verification
        - No information leakage through timing differences
    z<$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewiyTuTpbsEf.ug.password_hashutf-8F)encodebcryptcheckpw)r	   r
   r   
dummy_hashtarget_hashresults         TC:\Users\algun\Documents\ceba web\Ceba - Github\app_modules\security_enhancements.pysecure_password_checkr   "   sw    . PJH_-/66w? 8+F M 	xw/1B1B71KLM    latlngc                     	 t        |       }t        |      }d|cxk  rdk  sy yd|cxk  rdk  sy y||k7  s||k7  rydd	||ffS # t        t        t        f$ r Y yw xY w)
a_  
    Validate geographic coordinates with proper bounds checking.
    
    Prevents injection of invalid coordinate data that could pollute the database
    or cause application errors. Enforces strict geographic bounds and type validation.
    
    Args:
        lat: Latitude value (any type, will be validated)
        lng: Longitude value (any type, will be validated)
    
    Returns:
        Tuple[bool, Optional[str], Optional[Tuple[float, float]]]:
            - success: Whether validation passed
            - error_message: Error description if validation failed
            - coordinates: Validated (lat, lng) tuple if successful
    
    Security Features:
        - Strict type validation prevents injection attacks
        - Geographic bounds enforcement prevents invalid data
        - Sanitized error messages prevent information disclosure
    g     Vg     V@)Fu   Neispravna geografska širina.Ng     fg     f@)Fu   Neispravna geografska dužina.N)FzNeispravne koordinate.NTN)float
ValueError	TypeErrorOverflowError)r   r   	lat_float	lng_floats       r   validate_geographic_coordinatesr"   G   s    ,5#J	#J	 *d*@ +@),u,@ -@ 	!Y)%;8TIy111	=1 545s*   !A A A A 
A A AAerrorcontextc                     t        |       j                         t        fddD              ryt        fddD              ryt        fddD              ry	t        fd
dD              ryy)a  
    Sanitize error messages to prevent information disclosure.
    
    Converts detailed system errors into generic user-friendly messages that don't
    reveal sensitive system information or internal application structure.
    
    Args:
        error: The original exception
        context: Context of the operation for logging purposes
    
    Returns:
        str: Sanitized error message safe for user display
    
    Security Features:
        - Removes database-specific error details
        - Hides file system paths and internal structure
        - Prevents stack trace information leakage
        - Maintains user experience with helpful generic messages
    c              3   &   K   | ]  }|v  
 y wN .0keyword	error_strs     r   	<genexpr>z)sanitize_error_message.<locals>.<genexpr>   s     
g/fG7i/f   )sqlitedatabasetablecolumn
constraintu   Greška pri obradi podataka.c              3   &   K   | ]  }|v  
 y wr'   r(   r)   s     r   r-   z)sanitize_error_message.<locals>.<genexpr>   s     
e/dG7i/dr.   )
permissionaccessfile	directorypathu   Greška pri pristupu datoteci.c              3   &   K   | ]  }|v  
 y wr'   r(   r)   s     r   r-   z)sanitize_error_message.<locals>.<genexpr>        
^/]G7i/]r.   )
connectiontimeoutnetworksocketu   Greška mreže.c              3   &   K   | ]  }|v  
 y wr'   r(   r)   s     r   r-   z)sanitize_error_message.<locals>.<genexpr>   r;   r.   )unauthorized	forbiddenzaccess deniedz Nemate dozvolu za ovu operaciju.u0   Došlo je do greške. Molimo pokušajte ponovno.)strlowerany)r#   r$   r,   s     @r   sanitize_error_messagerF   s   sl    ( E
  "I 
g/f
gg- 
e/d
ee/ 
^/]
^^  
^/]
^^1 >r   filenamec                     | rt        | t              syt        |       dkD  ryg d}|D ]  }|| v s y g d}| j                         }|D ]  }|j	                  |      s y d| v ryy	)
a  
    Validate filename for security issues including path traversal and malicious extensions.
    
    Prevents path traversal attacks, executable file uploads, and other filename-based
    security vulnerabilities.
    
    Args:
        filename: Filename to validate
    
    Returns:
        Tuple[bool, Optional[str]]: (is_valid, error_message)
    
    Security Features:
        - Path traversal prevention (../, ..\, etc.)
        - Malicious extension detection
        - Special character filtering
        - Length validation
    )FzNedostaje ime datoteke.   )Fu   Ime datoteke je predugačko.)
z../\:|<>*?")FzNeispravno ime datoteke.)z.phpz.php3z.php4z.php5z.phtmlz.aspz.aspxz.jspz.jspxz.pyz.plz.rbz.shz.batz.cmdz.exez.scrz.comz.pifz	.htaccessz	.htpasswdz.configz.iniz.cfg)FzNedozvoljena vrsta datoteke. )TN)
isinstancerC   lenrD   endswith)rG   dangerous_patternspatterndangerous_extensionsfilename_lowerexts         r   validate_filename_securityr\      s    & :h4/ 8}s4 &h4 &
 ^^%N#""3'8 $
 0r   lengthc                 ,    t        j                  |       S )a  
    Generate cryptographically secure random token.
    
    Creates tokens with high entropy suitable for CSRF protection, session tokens,
    and other security-critical applications.
    
    Args:
        length: Desired token length in bytes (default 32)
    
    Returns:
        str: URL-safe base64 encoded secure token
    
    Security Features:
        - Cryptographically secure random number generation
        - High entropy output suitable for security tokens
        - URL-safe encoding for web application compatibility
    )secretstoken_urlsafe)r]   s    r   generate_secure_tokenra      s    $   ((r   datatoken
secret_keyc                     	 t        j                  |j                  d      | j                  d      t        j                        j                         }t        j                  ||      S # t        $ r Y yw xY w)a<  
    Verify HMAC-based token for integrity and authenticity.
    
    Provides secure verification of tokens used in media URLs, API authentication,
    and other security-sensitive contexts.
    
    Args:
        data: Original data that was signed
        token: HMAC token to verify
        secret_key: Secret key used for signing
    
    Returns:
        bool: True if token is valid, False otherwise
    
    Security Features:
        - Timing-attack resistant comparison
        - Strong HMAC-SHA256 verification
        - Prevents token manipulation attacks
    r   F)hmacnewr   hashlibsha256	hexdigestcompare_digest	Exception)rb   rc   rd   expected_tokens       r   verify_hmac_tokenrn      si    (g&KK NN
 )+	 	 ""5.99 s   A&A) )	A54A5attempt_count
base_delayc                 <    | dk  ryt        |d| dz
  z  z  d      }|S )a|  
    Calculate exponential backoff delay for rate limiting.
    
    Implements increasingly longer delays for repeated failed attempts,
    making brute force attacks impractical while allowing legitimate users
    to retry after reasonable delays.
    
    Args:
        attempt_count: Number of failed attempts
        base_delay: Base delay in seconds (default 5)
    
    Returns:
        int: Delay in seconds before next attempt allowed
    
    Security Features:
        - Exponential increase in delay times
        - Maximum cap to prevent excessive delays
        - Transparent to legitimate users with minimal attempts
    r         i  )min)ro   rp   delays      r   #rate_limit_with_exponential_backoffrv     s1    (  
aMA$567>ELr   schemac                    t        | t              sddi fS i }|j                         D ]   \  }}| j                  |      }|j                  dd      r||dk(  rdd| di fc S |?|j                  dt              }t        ||      s		  ||      }t        |t              r|j                  dd      }|j                  dd      }t        |      |k  rdd| di fc S t        |      |kD  rdd| di fc S g d}	|j                         }
|	D ]  }||
v sdd	| d
i fc c S  |||<    dd|fS # t
        t        f$ r dd	| d
i fcY c S w xY w)a  
    Validate API input against schema with security-focused validation.
    
    Provides comprehensive input validation with type checking, length limits,
    and security pattern detection to prevent injection attacks.
    
    Args:
        data: Input data to validate
        schema: Validation schema with field definitions
    
    Returns:
        Tuple[bool, Optional[str], Dict[str, Any]]: (is_valid, error_message, sanitized_data)
    
    Security Features:
        - SQL injection pattern detection
        - XSS prevention through input sanitization
        - Type and length validation
        - Required field enforcement
    FzNeispravni podaci.requiredN zPolje 'z' je obavezno.typezNeispravna vrijednost za 'z'.
min_lengthr   
max_lengthi'  'z' prekratak.u   ' predugačak.)script
javascriptvbscriptonloadonerroronclickselectuniondropinsertupdatedeletez--;T)	rT   dictitemsgetrC   r   r   rU   rD   )rb   rw   sanitized_data
field_namefield_schemavalueexpected_typer|   r}   rW   value_lowerrX   s               r   validate_api_inputr   2  s   ( dD!*B..N$*LLN 
L$ J.EMUb[GJ<~>BB(,,VS9Me]3R)%0E
 %%)--lA>
)--lEB
u:
* Aj\">BBu:
* Aj\"@"DD&"" $kkm1G+-$(B:,b&QSUUU  2 */N:&g %3j ~%%Q #I. R $>zl""MrQQRs   
D11EEc                    g d}dj                  |      | j                  d<   d| j                  d<   d| j                  d<   d| j                  d	<   d
| j                  d<   d| j                  d<   | j                  j                  dd       | S )a;  
    Add comprehensive security headers to HTTP responses.
    
    Implements defense-in-depth security headers to protect against various
    web application attacks including XSS, clickjacking, and data injection.
    
    Args:
        response: Flask response object
    
    Returns:
        Response object with security headers added
    
    Security Features:
        - Content Security Policy (CSP) enforcement
        - XSS protection headers
        - Clickjacking prevention
        - MIME type sniffing prevention
        - Referrer policy enforcement
    )	zdefault-src 'self'z3script-src 'self' 'unsafe-inline' https://unpkg.comzOstyle-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://unpkg.comzGimg-src 'self' data: https://*.tile.openstreetmap.org https://unpkg.comz/font-src 'self' https://fonts.gstatic.com data:zconnect-src 'self'zframe-ancestors 'none'zbase-uri 'self'zform-action 'self'z; zContent-Security-PolicyDENYzX-Frame-OptionsnosniffzX-Content-Type-Optionsz1; mode=blockzX-XSS-Protectionzstrict-origin-when-cross-originzReferrer-Policyz,geolocation=(self), microphone=(), camera=()zPermissions-PolicyServerN)joinheaderspop)responsecsp_directivess     r   security_headers_middlewarer     s    *
N 37))N2KH./ +1H&'1:H-.+:H'(*KH&'-[H)* 4(Or   )	operation)    )   )__doc__timer   r_   rh   rf   typingr   r   r   r   	functoolsr   flaskr   rC   boolr   r   r"   rl   rF   r\   intra   rn   rv   r   r   r(   r   r   <module>r      sn  .      - -  "C "3 "(4. "UY "J)5 )53 )55xPS}V^_dejlqeq_rVsAs;t )5X'>) '>c '>C '>T? ?tXc]7J1K ?D)# )s )*C    Ds  TW 8N&T#s(^ N&T#t)_ N&tU]^aUbdhilnqiqdrOrIs N&b-r   