Django NIS2 Shield
The "Security-First" Middleware for NIS2 Compliance.
Companies subject to NIS2 Directive need demonstrable compliance. This middleware provides:
- Forensic logging with HMAC-SHA256 integrity and PII encryption (Art. 21.2.h)
- Rate limiting to prevent DoS/Brute Force attacks (Art. 21.2.e)
- Session Guard to detect hijacking via IP/User-Agent validation (Art. 21.2.a)
- MFA Gatekeeper for sensitive routes (Art. 21.2.j)
- Multi-SIEM Presets: Ready-to-use configs for Splunk, Datadog, QRadar.
Part of the NIS2 Shield Ecosystem: Use with
@nis2shield/react-guard,@nis2shield/angular-guard, or@nis2shield/vue-guardfor client-side protection andnis2shield/infrastructurefor a full-stack implementation.
┌─────────────────────────────────────────────────────────────┐
│ Frontend │
│ @nis2shield/{react,angular,vue}-guard │
│ ├── SessionWatchdog (idle detection) │
│ ├── AuditBoundary (crash reports) │
│ └── → POST /api/nis2/telemetry/ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Backend (NIS2 Adapter) │
│ Supported: Django, Express, Spring Boot, .NET │
│ ├── ForensicLogger (HMAC signed logs) │
│ ├── RateLimiter, SessionGuard, TorBlocker │
│ └── → SIEM (Elasticsearch, Splunk, QRadar, etc.) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Infrastructure │
│ nis2shield/infrastructure │
│ ├── Centralized Logging (ELK/Splunk) │
│ └── Audited Deployment (Terraform/Helm) │
└─────────────────────────────────────────────────────────────┘
✨ Key Features
🔒 Forensic Logger
- Standardized logs (
NIS2-JSON-SCHEMA v1.0) signed with HMAC-SHA256 - Automatic PII field encryption (GDPR compliant)
- Configurable IP anonymization
🛡️ Active Defense
- Rate Limiting: Protection against application-level DoS attacks (sliding window algorithm)
- Session Guard: Session hijacking prevention with mobile network tolerance
- Tor Blocker: Automatic blocking of Tor exit nodes
- MFA Gatekeeper: 2FA redirect for sensitive paths
📊 Compliance & Reporting
check_nis2command for configuration auditing- Incident report generation for CSIRT (24h deadline)
- SIEM presets for Elasticsearch, Splunk, QRadar, Graylog, Sumo Logic, and Datadog
🔔 Real-time Alerting (v0.3.0+)
- Webhook notifications for security events
- Supports Slack, Microsoft Teams, Discord, and generic HTTP
📦 Installation
pip install django-nis2-shield
For development:
pip install django-nis2-shield[dev]
⚙️ Configuration
settings.py
INSTALLED_APPS = [
...,
'django_nis2_shield',
]
MIDDLEWARE = [
...,
# Add after SessionMiddleware and before CommonMiddleware
'django_nis2_shield.middleware.Nis2GuardMiddleware',
...,
]
# NIS2 Shield Configuration
NIS2_SHIELD = {
# Security Keys
'INTEGRITY_KEY': 'change-me-to-a-secure-secret',
'ENCRYPTION_KEY': b'your-32-byte-fernet-key-here=', # Fernet.generate_key()
# Privacy (GDPR)
'ANONYMIZE_IPS': True,
'ENCRYPT_PII': True,
'PII_FIELDS': ['user_id', 'email', 'ip', 'user_agent'],
# Active Defense
'ENABLE_RATE_LIMIT': True,
'RATE_LIMIT_THRESHOLD': 100, # requests per window
'RATE_LIMIT_WINDOW': 60, # seconds
'RATE_LIMIT_ALGORITHM': 'sliding_window', # or 'fixed_window'
'ENABLE_SESSION_GUARD': True,
'SESSION_IP_TOLERANCE': 'subnet', # 'exact', 'subnet', 'none'
'BLOCK_TOR_EXIT_NODES': True,
# MFA
'ENFORCE_MFA_ROUTES': ['/admin/', '/finance/'],
'MFA_SESSION_FLAG': 'is_verified_mfa',
'MFA_REDIRECT_URL': '/accounts/login/mfa/',
# Webhooks (v0.3.0+)
'ENABLE_WEBHOOKS': True,
'WEBHOOKS': [
{'url': 'https://hooks.slack.com/...', 'format': 'slack'},
]
}
Log Format: CEF (Enterprise SIEM)
For CEF output instead of JSON:
from django_nis2_shield.cef_formatter import get_cef_logging_config
LOGGING = get_cef_logging_config('/var/log/django_nis2.cef')
🚀 Usage
Configuration Audit
python manage.py check_nis2
Threat Intelligence Update
python manage.py update_threat_list
Incident Report Generation
python manage.py generate_incident_report --hours=24 --output=incident.json
📈 Dashboard Monitoring
The project includes a Docker stack for log visualization:
cd dashboard
docker compose up -d
# Access:
# - Kibana: http://localhost:5601
# - Grafana: http://localhost:3000 (admin/admin)
See dashboard/README.md for details.
🧪 Testing
# With pytest
pip install pytest pytest-django
PYTHONPATH=. pytest tests/ -v
📖 Recipes
Banking App with MFA & Rate Limiting
# settings.py
NIS2_SHIELD = {
'INTEGRITY_KEY': os.environ['NIS2_HMAC_KEY'],
'ENCRYPTION_KEY': os.environ['NIS2_AES_KEY'],
# Rate Limit: 50 requests per minute
'ENABLE_RATE_LIMIT': True,
'RATE_LIMIT_THRESHOLD': 50,
'RATE_LIMIT_WINDOW': 60,
# MFA for admin and finance
'ENFORCE_MFA_ROUTES': ['/admin/', '/finance/', '/transfers/'],
'MFA_REDIRECT_URL': '/accounts/mfa/verify/',
}
E-commerce with Splunk SIEM
# settings.py
import os
NIS2_SHIELD = {
'INTEGRITY_KEY': os.environ['NIS2_HMAC_KEY'],
'ANONYMIZE_IPS': True,
'ENCRYPT_PII': True,
# Webhooks for real-time alerts
'ENABLE_WEBHOOKS': True,
'WEBHOOKS': [
{'url': 'https://hooks.slack.com/...', 'format': 'slack'},
]
}
# Splunk SIEM Output
from django_nis2_shield.siem import get_splunk_logging_config
LOGGING = get_splunk_logging_config(
splunk_url='https://splunk.example.com:8088',
token=os.environ['SPLUNK_HEC_TOKEN']
)
Healthcare API with Session Guard
# Block session hijacking attempts with IP tolerance for mobile networks
NIS2_SHIELD = {
'ENABLE_SESSION_GUARD': True,
'SESSION_IP_TOLERANCE': 'subnet', # 'exact', 'subnet', or 'none'
'BLOCK_TOR_EXIT_NODES': True,
}
📄 License
MIT License - see LICENSE for details.
🛡️ Security & Updates
Subscribe to our Security Mailing List to receive immediate alerts about:
- Critical vulnerabilities (CVEs)
- NIS2/DORA regulatory logic updates
- Major breaking changes
For reporting vulnerabilities, see SECURITY.md.
🤝 Contributing
Contributions are welcome! Open an issue or PR on GitHub.
Release files for django-nis2-shield 1.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| django_nis2_shield-1.1.1.tar.gz | 29.2 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| django_nis2_shield-1.1.1-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 53.4 kB
Release files / django_nis2_shield-1.1.1.tar.gz
| Download URL | django_nis2_shield-1.1.1.tar.gz |
|---|---|
| Size | 29.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
74cadf208749c47db7e004124b8955e00682b9e10fa760c9e051fea947fa7ad2
|
|
BLAKE2b-256 checksum How to use checksums |
3281279c6f98c92cb5deac9c35ac03aac543445e6046d19d86b81e6f872693cb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jan 3, 2026.
Transparency logRelease files / django_nis2_shield-1.1.1-py3-none-any.whl
| Download URL | django_nis2_shield-1.1.1-py3-none-any.whl |
|---|---|
| Size | 24.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f94c574506ddd3a33e13158acb9edd9bc52630fffb7a2076b53f2a0bfa9e92aa
|
|
BLAKE2b-256 checksum How to use checksums |
3ef6d068becffd8b6606a5ba9ff60f004e89cd79b18270ccf1231e03e2d8110e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.7
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jan 3, 2026.
Transparency log