o
    Fh<                     @   sn  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
dZde
de
d	eeee eeeef  f fddZd+deded	efddZded	eeee f fddZd,ded	efddZdededed	efdd Zd-d"ed#ed	efd$d%Zde	ee
f d&e	ee	f d	eeee e	ee
f f fd'd(Zd)d* ZdS ).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                 C   sT   d}|r|d r|d  d}t| d|}|S t| d| 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result r   2/var/www/html/app_modules/security_enhancements.pysecure_password_check"   s   r   latlngc              
   C   s   z;t | }t |}d|  krdksW dS  W dS d|  kr%dks)W dS  W dS ||ks1||kr4W dS dd	||ffW S  tttfyH   Y dS 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_floatr   r   r   validate_geographic_coordinatesG   s"   r   	operationerrorcontextc                    sx   t |   t fdddD rdS t fdddD r dS t fddd	D r-d
S t fdddD r:dS dS )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       | ]}| v V  qd S Nr   .0keyword	error_strr   r   	<genexpr>       z)sanitize_error_message.<locals>.<genexpr>)sqlitedatabasetablecolumn
constraintu   Greška pri obradi podataka.c                 3   r#   r$   r   r%   r(   r   r   r*      r+   )
permissionaccessfile	directorypathu   Greška pri pristupu datoteci.c                 3   r#   r$   r   r%   r(   r   r   r*      r+   )
connectiontimeoutnetworksocketu   Greška mreže.c                 3   r#   r$   r   r%   r(   r   r   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   r(   r   sanitize_error_messages   s   r?   filenamec                 C   s|   | rt | ts	dS t| dkrdS g d}|D ]	}|| v r  dS qg d}|  }|D ]
}||r5 dS q+d| v r<dS d	S )
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)
isinstancer<   lenr=   endswith)r@   dangerous_patternspatterndangerous_extensionsfilename_lowerextr   r   r   validate_filename_security   s$   	
rT       lengthc                 C   s
   t | 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)rV   r   r   r   generate_secure_token   s   
rY   datatoken
secret_keyc                 C   sD   zt |d| dtj }t ||W S  ty!   Y dS 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)rZ   r[   r\   expected_tokenr   r   r   verify_hmac_token   s   re      attempt_count
base_delayc                 C   s&   | dkrdS t |d| d   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)rg   rh   delayr   r   r   #rate_limit_with_exponential_backoff  s   rm   schemac              
   C   sr  t | ts
ddi fS i }| D ]\}}| |}|ddr2|du s'|dkr2dd| di f  S |dur|dt}t ||s^z||}W n ttfy]   dd	| d
i f Y   S w t |tr|dd}|dd}t||k rdd| di f  S t||krdd| di f  S g d}	| }
|	D ]}||
v rdd	| d
i f    S q|||< qdd|fS )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)	rL   dictitemsgetr<   r   r   rM   r=   )rZ   rn   sanitized_data
field_namefield_schemavalueexpected_typerr   rs   rO   value_lowerrP   r   r   r   validate_api_input2  s>   





r   c                 C   s\   g d}d || jd< d| jd< d| jd< d| jd	< d
| jd< d| jd< | 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_directivesr   r   r   security_headers_middleware  s   




r   )r    )rU   )rf   )__doc__timer   rW   r_   r]   typingr   r   r   r   	functoolsr   flaskr   r<   boolr   r   r   rc   r?   rT   intrY   re   rm   r   r   r   r   r   r   <module>   s$    0%,*B"<Q