lback.security package

This file serves as the initialization point for the ‘lback_framework/lback/security’ package. It is designed to expose the core components necessary for implementing various security measures and protections within the Lback web framework. This package centralizes the definition and management of security-related functionalities, including firewall rules, HTTP security headers, rate limiting, and protection against SQL injection, ensuring the application’s robustness against common web vulnerabilities.

Key Components Exposed by this Package:

  1. AdvancedFirewall (from .firewall): A component that provides advanced firewall capabilities for the Lback application. This class is responsible for defining and enforcing security rules at the network or application level, controlling access to resources based on various criteria such as IP addresses, request patterns, or user roles. It helps in preventing unauthorized access and mitigating denial-of-service (DoS) attacks.

  2. SecurityHeadersConfigurator (from .headers): A utility or class for configuring and applying various HTTP security headers to outgoing responses. This component helps to protect the application against a range of client-side attacks (e.g., XSS, clickjacking) by instructing browsers on how to behave when interacting with the application’s content. Examples of headers include Content-Security-Policy (CSP), X-Frame-Options, and X-Content-Type-Options.

  3. RateLimiter (from .rate_limiter): A component that implements rate limiting functionality. This class is used to control the number of requests a client can make to the server within a given timeframe. It helps in preventing abuse, brute-force attacks, and resource exhaustion by limiting the frequency of requests from a single source.

  4. SQLInjectionProtection (from .sql_injection): A component dedicated to providing protection against SQL injection vulnerabilities. This class implements mechanisms (e.g., input sanitization, parameterized queries, or pattern detection) to prevent malicious SQL code from being injected into database queries through user input, thereby safeguarding the integrity and confidentiality of the application’s data.

Submodules

lback.security.firewall module

class lback.security.firewall.AdvancedFirewall(allowed_ips: List[str] | None = None, blocked_ips: List[str] | None = None, blocked_networks: List[str] | None = None, blocked_user_agents: List[str] | None = None, blocked_url_patterns: List[str] | None = None, ddos_max_requests: int = 100, ddos_window_seconds: int = 10, temp_block_seconds: int = 300)[source][source]

Bases: object

A robust and customizable firewall system for filtering incoming requests based on IP addresses, networks, user agents, URL patterns, and basic DDoS detection.

This class helps protect your application from malicious traffic by providing various blocking mechanisms and a rate-limiting system to mitigate distributed denial-of-service (DDoS) attacks.

It is designed to be integrated into the request/response cycle of a web framework, typically as a middleware or a pre-processing step.

__init__(allowed_ips: List[str] | None = None, blocked_ips: List[str] | None = None, blocked_networks: List[str] | None = None, blocked_user_agents: List[str] | None = None, blocked_url_patterns: List[str] | None = None, ddos_max_requests: int = 100, ddos_window_seconds: int = 10, temp_block_seconds: int = 300)[source][source]

Initializes the AdvancedFirewall with specified rules and DDoS detection parameters.

Parameters:
  • allowed_ips (Optional[List[str]]) – A list of IP addresses explicitly allowed to access the application. If provided, only IPs in this list are allowed.

  • blocked_ips (Optional[List[str]]) – A list of specific IP addresses to block.

  • blocked_networks (Optional[List[str]]) – A list of IP network strings (e.g., “192.168.1.0/24”) to block.

  • blocked_user_agents (Optional[List[str]]) – A list of User-Agent strings to block.

  • blocked_url_patterns (Optional[List[str]]) – A list of regular expression strings for URLs to block. Case-insensitive matching is applied.

  • ddos_max_requests (int) – The maximum number of requests allowed from a single IP within the ddos_window_seconds before temporary blocking.

  • ddos_window_seconds (int) – The time window (in seconds) for DDoS detection.

  • temp_block_seconds (int) – The duration (in seconds) for which an IP is temporarily blocked due to suspected DDoS activity.

add_blocked_url_pattern(pattern: str)[source][source]

Adds a URL regex pattern to the list of blocked URL patterns.

Parameters:

pattern (str) – The regular expression string for URLs to block.

add_blocked_user_agent(user_agent: str)[source][source]

Adds a User-Agent string to the list of blocked user agents.

Parameters:

user_agent (str) – The User-Agent string to block.

block_ip(ip: str, temp: bool = False)[source][source]

Adds an IP address to the blocked list.

Parameters:
  • ip (str) – The IP address to block.

  • temp (bool) – If True, the IP is temporarily blocked for temp_block_seconds. Otherwise, it’s added to the permanent blocked IPs list.

is_allowed(ip: str, user_agent: str = '', url: str = '') bool[source][source]

Determines if an incoming request is allowed based on configured firewall rules (IPs, networks, user agents, URL patterns) and DDoS detection.

The checks are performed in a specific order: 1. Temporary blocks (DDoS mitigation). 2. Explicitly blocked IPs. 3. IPs within blocked networks. 4. Explicitly allowed IPs (if allowed_ips list is not empty). 5. Blocked User-Agents. 6. Blocked URL patterns. 7. DDoS rate limiting check.

Parameters:
  • ip (str) – The IP address of the request origin.

  • user_agent (str) – The User-Agent string from the request header. Defaults to empty string.

  • url (str) – The full URL of the request. Defaults to empty string.

Returns:

True if the request is allowed, False otherwise.

Return type:

bool

unblock_ip(ip: str)[source][source]

Removes an IP address from both the permanent and temporary blocked lists.

Parameters:

ip (str) – The IP address to unblock.

lback.security.headers module

class lback.security.headers.SecurityHeadersConfigurator(config: Config)[source][source]

Bases: object

Manages the configuration and application of various HTTP security headers to enhance the web application’s defense against common web vulnerabilities.

This class reads security header settings from the application’s Config instance and prepares a dictionary of headers and their corresponding values. These headers are then typically applied to HTTP responses by a middleware.

__init__(config: Config)[source][source]

Initializes the SecurityHeadersConfigurator.

It loads security header settings from the provided Config instance and immediately prepares the headers to be applied.

Parameters:

config (Config) – The application Config instance containing all application settings, including the ‘SECURITY_HEADERS’ dictionary.

get_headers() Dict[str, str][source][source]

Returns the dictionary of HTTP security headers prepared by the configurator. These headers are ready to be added to an HTTP response.

Returns:

A dictionary of security headers (e.g., “Content-Security-Policy”: “value”).

Return type:

Dict[str, str]

lback.security.rate_limiter module

class lback.security.rate_limiter.RateLimiter(max_requests: int, window_seconds: int)[source][source]

Bases: object

Implements a generic rate limiting mechanism to control the frequency of operations or requests based on a specified key.

This class tracks the number of requests made within a defined time window and prevents further requests if a maximum limit is exceeded. It is thread-safe, making it suitable for use in multi-threaded environments like web servers.

__init__(max_requests: int, window_seconds: int)[source][source]

Initializes the RateLimiter with the maximum allowed requests and the time window.

Parameters:
  • max_requests (int) – The maximum number of requests allowed within the window_seconds.

  • window_seconds (int) – The time window (in seconds) during which max_requests are allowed.

is_allowed(key: str) bool[source][source]

Checks if a request identified by a unique key is allowed based on the rate limit.

This method logs the current request’s timestamp. If the number of requests for the given key within the defined window_seconds exceeds max_requests, the request is denied. Otherwise, it is allowed.

Parameters:

key (str) – A unique identifier for the request source (e.g., IP address, user ID, API key).

Returns:

True if the request is allowed by the rate limit, False otherwise.

Return type:

bool

lback.security.sql_injection module

class lback.security.sql_injection.SQLInjectionProtection[source][source]

Bases: object

Provides utility methods to detect and prevent potential SQL Injection attacks by scanning input strings and dictionaries for suspicious patterns.

This class offers a basic layer of protection by identifying common SQL keywords, operators, and attack signatures within user-provided data. It’s intended to be used as a preliminary check before interacting with a database, complementing the use of parameterized queries (which is the primary defense against SQL injection).

SUSPICIOUS_PATTERNS = ['(--|\\#|;|/\\*|\\*/|xp_)', '(\\b(OR|AND)\\b\\s+\\d+=\\d+)', '(\\bUNION\\b|\\bSELECT\\b|\\bINSERT\\b|\\bUPDATE\\b|\\bDELETE\\b)', '(\\bDROP\\b|\\bALTER\\b|\\bCREATE\\b|\\bEXEC\\b)', '([\'\\"]\\s*or\\s*[\'\\"]?\\d+[\'\\"]?\\s*=\\s*[\'\\"]?\\d+)']
classmethod is_safe(value: str) bool[source][source]

Checks if a given string value contains any suspicious patterns indicative of SQL Injection.

This method iterates through predefined regular expressions. If any pattern is found within the input string (case-insensitive), it logs a warning and returns False.

Parameters:

value (str) – The string to be checked for SQL Injection patterns.

Returns:

True if the string is considered safe (no suspicious patterns found), False otherwise.

Return type:

bool

classmethod validate_inputs(data: dict) bool[source][source]

Validates all string values within a dictionary for potential SQL Injection patterns.

This method is useful for checking incoming request data (e.g., form submissions, JSON payloads) before processing. It recursively checks string values, returning False immediately upon detection of any suspicious pattern.

Parameters:

data (dict) – A dictionary containing input data to be validated.

Returns:

True if all string values in the dictionary are safe, False if any suspicious SQL Injection pattern is found.

Return type:

bool