rennf93 / fastapi-guard

A security library for FastAPI that provides middleware to control IPs, log requests, and detect penetration attempts. It integrates seamlessly with FastAPI to offer robust protection against various security threats.
MIT License
2 stars 0 forks source link
api security

FastAPI Guard

PyPI version License: MIT CI Release CodeQL

fastapi-guard is a security library for FastAPI that provides middleware to control IPs, log requests, and detect penetration attempts. It integrates seamlessly with FastAPI to offer robust protection against various security threats.

Features

Installation

To install fastapi-guard, use pip:

pip install fastapi-guard

Usage

Basic Setup

To use fastapi-guard, you need to configure the middleware in your FastAPI application. Here's a basic example:

from fastapi import FastAPI
from guard.middleware import SecurityMiddleware
from guard.models import SecurityConfig

app = FastAPI()

# Define your security configuration
config = SecurityConfig(
    whitelist=["192.168.1.1"],
    blacklist=["10.0.0.1"],
    blocked_countries=["AR", "IT"],
    blocked_user_agents=["curl", "wget"],
    auto_ban_threshold=5,
    auto_ban_duration=86400,
    custom_log_file="security.log",
    rate_limit=100,
    use_ip2location=True,
    ip2location_db_path="./IP2LOCATION-LITE-DB1.IPV6.BIN",
    ip2location_auto_download=True,
    ip2location_auto_update=True,
    ip2location_update_interval=24,
    use_ipinfo_fallback=True,
    enforce_https=True,
    enable_cors=True,
    cors_allow_origins=["*"],
    cors_allow_methods=["GET", "POST"],
    cors_allow_headers=["*"],
    cors_allow_credentials=True,
    cors_expose_headers=["X-Custom-Header"],
    cors_max_age=600,
    block_cloud_providers={"AWS", "GCP", "Azure"},
)

# Add the security middleware
app.add_middleware(SecurityMiddleware, config=config)

@app.get("/")
async def read_root():
    return {"message": "Hello, World!"}

IP Whitelisting and Blacklisting

You can control access based on IP addresses using the whitelist and blacklist options in the SecurityConfig.

config = SecurityConfig(
    whitelist=["192.168.1.1"],
    blacklist=["10.0.0.1"],
)

User Agent Filtering

Block requests from specific user agents by adding patterns to the blocked_user_agents list.

config = SecurityConfig(
    blocked_user_agents=["curl", "wget"],
)

Rate Limiting

Limit the number of requests from a single IP using the rate_limit option.

config = SecurityConfig(
    rate_limit=100,  # Maximum 100 requests per minute
)

Automatic IP Banning

Automatically ban IPs after a certain number of suspicious requests using the auto_ban_threshold and auto_ban_duration options.

config = SecurityConfig(
    auto_ban_threshold=5,  # Ban IP after 5 suspicious requests
    auto_ban_duration=86400,  # Ban duration in seconds (1 day)
)

Penetration Attempt Detection

Detect and log potential penetration attempts using the detect_penetration_attempt function.

from fastapi import Request
from guard.utils import detect_penetration_attempt

@app.post("/submit")
async def submit_data(request: Request):
    if await detect_penetration_attempt(request):
        return {"error": "Potential attack detected"}
    return {"message": "Data submitted successfully"}

Custom Logging

Log security events to a custom file using the custom_log_file option.

config = SecurityConfig(
    custom_log_file="security.log",
)

CORS Configuration

Configure CORS settings for your FastAPI application using the enable_cors and related options.

config = SecurityConfig(
    enable_cors=True,
    cors_allow_origins=["*"],
    cors_allow_methods=["GET", "POST"],
    cors_allow_headers=["*"],
    cors_allow_credentials=True,
    cors_expose_headers=["X-Custom-Header"],
    cors_max_age=600,
)

Cloud Provider IP Blocking

Block requests from cloud provider IPs (AWS, GCP, Azure) using the block_cloud_providers option.

config = SecurityConfig(
    block_cloud_providers={"AWS", "GCP", "Azure"},
)

IP Geolocation

Use IP2Location or ipinfo.io to determine the country of an IP address using the use_ip2location and use_ipinfo_fallback options.

config = SecurityConfig(
    use_ip2location=True,
    ip2location_db_path="./IP2LOCATION-LITE-DB1.IPV6.BIN",
    ip2location_auto_download=True,
    ip2location_auto_update=True,
    ip2location_update_interval=24,
    use_ipinfo_fallback=True,
)

Advanced Usage

Custom Request Check

You can define a custom function to perform additional checks on the request using the custom_request_check option.

from fastapi import Request, Response

async def custom_check(request: Request) -> Optional[Response]:
    if "X-Custom-Header" not in request.headers:
        return Response("Missing custom header", status_code=400)
    return None

config = SecurityConfig(
    custom_request_check=custom_check,
)

Custom Response Modifier

You can define a custom function to modify the response before it's sent using the custom_response_modifier option.

from fastapi import Response

async def custom_modifier(response: Response) -> Response:
    response.headers["X-Custom-Header"] = "CustomValue"
    return response

config = SecurityConfig(
    custom_response_modifier=custom_modifier,
)

Detailed Configuration Options

SecurityConfig

The SecurityConfig class defines the structure for security configuration, including IP whitelists and blacklists, blocked countries, blocked user agents, rate limiting, automatic IP banning, IP2Location settings, HTTPS enforcement, custom hooks, CORS settings, and blocking of cloud provider IPs.

Attributes

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Author

Renzo Franceschini - rennf93@gmail.com

Acknowledgements