Container Escape in Django (Python)
Python-Specific Remediation in Django — concrete code fixes
Mitigating container escape risks in Django applications requires securing both the application code and the container deployment configuration. Since middleBrick identifies the risk but does not fix it, developers must apply remediation based on its findings.
First, eliminate the use of pickle for untrusted data. Replace it with safe serialization formats like JSON. For example, instead of:
import pickle
def get_user_data(request):
token = request.GET.get('token')
data = pickle.loads(base64.b64decode(token)) # UNSAFE
return JsonResponse(data)
Use JSON:
import json
import base64
def get_user_data(request):
token = request.GET.get('token')
try:
data = json.loads(base64.b64decode(token))
return JsonResponse(data)
except (json.JSONDecodeError, UnicodeDecodeError):
return JsonResponse({'error': 'Invalid token'}, status=400)
Second, never mount /var/run/docker.sock into Django containers in production. If internal tooling requires Docker access, use a separate, minimal sidecar container with dropped capabilities and read-only root filesystem, communicating via secured APIs—not direct socket access.
Third, run Django as a non-root user in the container. Update your Dockerfile:
FROM python:3.11-slim
# Create non-root user
RUN useradd --create-home appuser
WORKDIR /home/appuser
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Switch to non-root user
USER appuser
# Run Django (example using gunicorn)
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "myproject.wsgi"]
Fourth, disable Django debug toolbar and detailed error pages in production by ensuring DEBUG = False in settings.py and restricting internal IPs:
# settings.py
DEBUG = False
INTERNAL_IPS = [
# Only allow specific IPs if needed for debugging
# '127.0.0.1',
]
# Disable debug toolbar in production
if DEBUG:
INSTALLED_APPS += ['debug_toolbar']
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware'] + MIDDLEWARE
Finally, apply Linux capabilities and seccomp profiles via container orchestration (e.g., Kubernetes or Docker run) to drop all unnecessary capabilities (--cap-drop ALL) and enforce least privilege. middleBrick’s scan will flag if the container runs with privileged flags or dangerous mounts, guiding these hardening steps.