Skip to main content

Django Security Suite

PyPI version Python Support Django Support License: MIT Code style: black Coverage

Enterprise-grade security suite for Django applications providing comprehensive protection against OWASP Top 10 vulnerabilities with ISO 27001 compliance features.

🔒 Features

Core Security

  • 🛡️ Security Headers: Automatic CSP, HSTS, X-Frame-Options configuration
  • ⚡ Rate Limiting: Redis-backed rate limiting with sliding window algorithm
  • 🔍 Suspicious Pattern Detection: Real-time detection of SQL injection, XSS, and path traversal attempts
  • 📏 Request Size Limiting: DoS protection through request size enforcement

Authentication & Session Security

  • 🔐 Brute Force Protection: Account lockout with exponential backoff
  • ⏰ Session Security: Absolute timeout, inactivity timeout, IP binding
  • 🔑 Password Validators: HIBP integration, complexity requirements, history tracking
  • 📱 MFA Support: TOTP/HOTP through django-otp integration

Data Protection

  • 🔒 Searchable Encryption: Encrypted fields with substring search capability
  • 🔑 Field Encryption: Integration with django-crypto-fields
  • 📝 Key Management: Secure key rotation and versioning
  • 🔍 N-gram Indexing: Privacy-preserving search on encrypted data

Input Validation & Sanitization

  • ✨ Auto-sanitization: HTML, SQL, and script injection prevention
  • 📧 Strict Validators: Email, URL, phone number validation
  • 🧹 DRF Integration: Secure serializer fields with built-in validation
  • 🚫 Injection Prevention: Protection against XSS, SQL injection, command injection

Audit & Compliance

  • 📊 Tamper-evident Audit Logs: Hash-chained audit trail
  • 🔍 API Request Logging: Complete request/response capture
  • 😷 PII Masking: Automatic PII detection and redaction
  • 📋 Compliance Reports: ISO 27001 and OWASP Top 10 mapping

📦 Installation

pip install django-security-suite

For additional features:

# With MFA support
pip install "django-security-suite[mfa]"

# With PostgreSQL optimizations
pip install "django-security-suite[postgres]"

# All features
pip install "django-security-suite[all]"

🚀 Quick Start

1. Add to INSTALLED_APPS

INSTALLED_APPS = [
    # Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    # ...

    # Django Security Suite
    'django_security_suite',
    'django_security_suite.authentication',
    'django_security_suite.encryption',
    'django_security_suite.validation',
    'django_security_suite.audit',

    # Required dependencies
    'axes',
    'django_otp',
    'django_otp.plugins.otp_totp',
    'django_crypto_fields',
]

2. Apply Secure Defaults

# settings.py
from django_security_suite.conf import apply_secure_defaults

# Choose a risk profile: 'strict', 'moderate', or 'relaxed'
apply_secure_defaults(globals(), preset='moderate')

# Or customize specific settings
DJANGO_SEC = {
    'RISK_PROFILE': 'moderate',
    'ENABLE_RATE_LIMITING': True,
    'ENABLE_AUDIT_LOGGING': True,
    'AUTH_PROTECTION': {
        'MAX_LOGIN_ATTEMPTS': 5,
        'LOCKOUT_DURATION': 900,  # 15 minutes
    },
    'SESSION_SECURITY': {
        'ABSOLUTE_TIMEOUT': 28800,  # 8 hours
        'INACTIVITY_TIMEOUT': 3600,  # 1 hour
    },
}

3. Update Middleware

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',

    # Django Security Suite middleware
    'django_security_suite.core.middleware.SecurityHeadersMiddleware',
    'django_security_suite.core.middleware.RateLimitingMiddleware',
    'django_security_suite.authentication.middleware.SessionSecurityMiddleware',
    'django_security_suite.authentication.middleware.BruteForceProtectionMiddleware',
    'django_security_suite.audit.middleware.AuditLoggingMiddleware',

    # Rest of your middleware...
]

4. Run Migrations

python manage.py migrate

📚 Usage Examples

Encrypted Fields with Search

from django.contrib.auth.models import AbstractUser
from django_security_suite.encryption.fields import SearchableEncryptedTextField

class User(AbstractUser):
    # Searchable encrypted field
    phone_number = SearchableEncryptedTextField(max_length=20, blank=True)

    # Standard encrypted field (no search)
    ssn = models.CharField(max_length=11, blank=True)

# Query encrypted fields
users = User.objects.filter(phone_number__contains='555')  # Works!

Rate Limiting

from django_security_suite.core.decorators import rate_limit

@rate_limit(limit='10/m', key='user')
def api_endpoint(request):
    return JsonResponse({'status': 'ok'})

Input Validation

from django_security_suite.validation.serializers import SecureSerializer
from django_security_suite.validation.fields import SecureCharField, SecureEmailField

class UserSerializer(SecureSerializer):
    name = SecureCharField(max_length=100)
    email = SecureEmailField()
    bio = SecureCharField(max_length=500, sanitize_html=True)

Audit Logging

# Automatic model tracking
from django_security_suite.audit.decorators import audit_log

@audit_log(action='user.login', include_ip=True)
def login_view(request):
    # Login logic
    pass

# Query audit logs
from django_security_suite.audit.models import AuditLog

recent_logins = AuditLog.objects.filter(
    action='user.login',
    created_at__gte=timezone.now() - timedelta(hours=24)
)

🔧 Configuration

Risk Profiles

Django Security Suite provides three pre-configured risk profiles:

Profile Use Case Security Level Performance Impact
Strict Production systems with sensitive data Maximum Higher
Moderate Standard production systems Balanced Medium
Relaxed Development and testing Basic Minimal

Environment Variables

# .env file
SECRET_KEY=your-secret-key-minimum-50-characters
DEBUG=False
ALLOWED_HOSTS=yourdomain.com
REDIS_URL=redis://localhost:6379/0
DJANGO_CRYPTO_FIELDS_KEY_PATH=/secure/path/crypto_keys
SECURITY_RISK_PROFILE=moderate

🛠️ Advanced Features

Custom Password Validators

DJANGO_SEC = {
    'PASSWORD_VALIDATORS': [
        {
            'NAME': 'django_security_suite.authentication.validators.MinimumLengthValidator',
            'OPTIONS': {'min_length': 12}
        },
        {
            'NAME': 'django_security_suite.authentication.validators.BreachedPasswordValidator',
        },
        {
            'NAME': 'django_security_suite.authentication.validators.PasswordReuseValidator',
            'OPTIONS': {'history_limit': 5}
        },
    ],
}

Content Security Policy

from django_security_suite.core.decorators import csp_update

@csp_update(script_src=["'self'", "https://cdn.example.com"])
def view_with_external_scripts(request):
    return render(request, 'template.html')

Suspicious Pattern Actions

DJANGO_SEC = {
    'SUSPICIOUS_PATTERNS': {
        'ENABLED': True,
        'ACTIONS': ['log', 'block', 'notify'],
        'AUTO_BAN_AFTER': 10,  # Ban IP after 10 violations
        'PATTERNS': {
            'SQL_INJECTION': True,
            'XSS_ATTEMPT': True,
            'PATH_TRAVERSAL': True,
            'COMMAND_INJECTION': True,
        },
    },
}

📊 Monitoring & Reporting

Security Dashboard

python manage.py security_report

Output:

Django Security Suite - Security Report
=======================================
Risk Profile: MODERATE
Total Users: 1,234
Failed Login Attempts (24h): 45
Locked Accounts: 3
Suspicious Patterns Detected: 12
Active Sessions: 234
Encrypted Fields: 5
Audit Logs (7 days): 10,234

Compliance Check

python manage.py check_security --compliance=ISO27001

🧪 Testing

Run the test suite:

# Basic tests
pytest

# With coverage
pytest --cov=django_security_suite

# Security-specific tests
pytest -m security

📖 Documentation

Full documentation is available at https://django-security-suite.readthedocs.io

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone the repository
git clone https://github.com/django-security-suite/django-security-suite.git
cd django-security-suite

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
ruff check .
black --check .
mypy django_security_suite

🔐 Security

  • For security vulnerabilities, please email security@django-security-suite.org
  • We follow responsible disclosure practices
  • Security patches are released as soon as possible

📝 License

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

🙏 Acknowledgments

  • Django Software Foundation for the amazing Django framework
  • OWASP for security best practices and guidelines
  • All contributors and users of this project

📊 Stats

  • 11,000+ lines of production-tested code
  • 90%+ test coverage
  • 5 major security modules
  • ISO 27001 compliant
  • OWASP Top 10 protection

🚦 Project Status

Tests Security Documentation


Made with ❤️ for the Django community
DjangoOWASPISO 27001

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_security_suite-1.0.0.tar.gz (95.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_security_suite-1.0.0-py3-none-any.whl (106.2 kB view details)

Uploaded Python 3

File details

Details for the file django_security_suite-1.0.0.tar.gz.

File metadata

  • Download URL: django_security_suite-1.0.0.tar.gz
  • Upload date:
  • Size: 95.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.7

File hashes

Hashes for django_security_suite-1.0.0.tar.gz
Algorithm Hash digest
SHA256 63b45478591841cb5e7ec1b314cacdfb852c29750164cae6f460049742bfee27
MD5 54cf31267c2f830734570518fe1c1698
BLAKE2b-256 ab353aaaa98a4fd73fb27239526f9e9993b2112d31ccfc59f08088353f249b81

See more details on using hashes here.

File details

Details for the file django_security_suite-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_security_suite-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 91c1118dfda796136d94a6425f3506c43a2265059d1f59766947bbbfa6a11761
MD5 f193867e9f61894c5961af9101279fc9
BLAKE2b-256 54d4ed2b94d3b3135413905be4057799233587d54c46727476d67e10e57c50d5

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page