Files
project-work/sources/security-audit.md

8.2 KiB

Security Audit Report - NearBeach

Based on my review of the NearBeach codebase, here are the security issues I found, organized by severity and category.


🔴 CRITICAL Issues

1. Hardcoded SECRET_KEY in Repository (local/settings.py:23)

SECRET_KEY = 'jz0k8%ecl#k!z+(9+5(^do1w!11ysus21m41m@i9c#u)*vk($o'
  • Impact: This is committed to the repo. In production, this would allow session hijacking, CSRF token forgery, and signing key compromise.
  • Project Idea: Build a Secret Scanner/Detector that scans Django projects for hardcoded secrets and integrates with CI/CD pipelines.

2. DEBUG = True in Settings (local/settings.py:26)

DEBUG = True
  • Impact: Information disclosure (stack traces, env vars, SQL queries). Should never be True in production.
  • Project Idea: Django Security Configuration Validator - automated check for production-ready settings.

🟠 HIGH Issues

3. Missing File Type Validation on Upload (document_views.py, DocumentUploadForm)

  • Issue: No MIME type validation, no file extension allowlist/denylist. Only checks file size.
  • Risk: Attackers can upload .php, .jsp, .exe, .html with JavaScript, .svg with scripts, polyglot files.
  • Location: NearBeach/forms.py:441-456 (DocumentUploadForm), document_views.py:266-315
  • Project Idea: Secure File Upload Framework for Django - content-type sniffing, magic bytes validation, allowlist-based filtering, sandboxed storage.

4. Path Traversal Risk in File Storage (private_media.py, LocalFileHandler)

  • Issue: Document key is UUID but file path construction uses user-controlled filename:
    # document_views.py:293
    document_submit.document = f"private/{document_submit.document_key}/{file}"
    
    If file name contains ../, could escape private directory.
  • Project Idea: Path Traversal Scanner for Django FileField - static analysis tool detecting unsafe path construction.

5. No CSRF Protection on Some API Endpoints

  • Issue: REST Framework uses SessionAuthentication + BasicAuth but some views may lack CSRF enforcement for state-changing operations.
  • Check: REST_FRAMEWORK config has SessionAuthentication but no explicit CsrfViewMiddleware enforcement on API.

6. Insecure Direct Object Reference (IDOR) Potential

  • Issue: Public links (public_views.py) use UUID but API endpoints use numeric IDs directly in URLs without explicit ownership checks in all cases.
  • Example: urls_api_v0.py routes like project/(?P<project_id>[0-9]+)/... rely solely on permission decorators.
  • Project Idea: IDOR Detection Tool for Django REST Framework - automated testing for object-level authorization bypasses.

🟡 MEDIUM Issues

7. Weak Password Reset Implementation (forms.py:623-634)

class PasswordResetForm(forms.Form):
    password = forms.CharField(max_length=50, required=True)
    username = forms.ModelChoiceField(queryset=USER_MODEL.objects.all(), required=True)
  • Issues:
    • No token-based reset (just username + new password)
    • No rate limiting
    • max_length=50 on password is artificially limiting
    • Admin can reset any user's password without audit trail

8. Token Authentication with No Expiry (settings.py:104-117)

REST_KNOX = {
    'TOKEN_TTL': None,  # Tokens never expire!
    'TOKEN_LIMIT_PER_USER': None,  # Unlimited tokens per user
    'AUTO_REFRESH': False,
}
  • Impact: Stolen tokens provide permanent access. No rotation, no limit.

9. SQL Injection Vectors via Raw Query Construction (search_objects.py, search_views.py)

  • Issue: Dynamic field names constructed via f-strings in queryset filters:
    # search_objects.py:122
    results = results.filter(**{F"{data['title']}__icontains": split_row})
    
    While data['title'] comes from a hardcoded dict, the pattern is risky if extended.
  • Project Idea: Django ORM Safety Linter - detects dynamic queryset construction patterns.

10. Information Disclosure in Error Handling (middleware/HandleErrorPages.py)

  • Issue: In DEBUG mode, returns full Django error pages. Template middleware catches errors but could leak info in edge cases.

11. Missing Security Headers

  • Missing: SECURE_HSTS_SECONDS, SECURE_SSL_REDIRECT, SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE, X_FRAME_OPTIONS = 'DENY' (only middleware), SECURE_CONTENT_TYPE_NOSNIFF

🔵 LOW / DEFENSE-IN-DEPTH Issues

12. Permissive CORS/ALLOWED_HOSTS (settings.py:28)

ALLOWED_HOSTS = ['localhost', '0.0.0.0', '192.168.1.105']
  • Should be restricted to actual production domains.

13. No Rate Limiting on Auth Endpoints

  • Login, password reset, API token creation have no throttling.

14. User Enumeration via Login (authentication/login_view.py)

  • Different error messages for "invalid password" vs "user not in groups" allows username enumeration.

15. Insecure Default File Permissions (LocalFileHandler.py:101)

file_permissions = 0o755  # World-readable directories
  • Private media directories world-readable.

16. Missing Content Security Policy (CSP)

  • No CSP headers configured. TinyMCE usage increases XSS risk.
  • Uses uuid.uuid4() which is cryptographically random, but no rate limiting on public link access.

📋 Summary Table

# Issue Severity File(s)
1 Hardcoded SECRET_KEY CRITICAL local/settings.py
2 DEBUG=True in repo CRITICAL local/settings.py
3 Missing file type validation HIGH forms.py, document_views.py
4 Path traversal in file upload HIGH document_views.py, private_media.py
5 Missing CSRF on API HIGH settings.py, API views
6 IDOR potential HIGH urls_api_v0.py, permission decorators
7 Weak password reset MEDIUM forms.py
8 Non-expiring API tokens MEDIUM settings.py (REST_KNOX)
9 Dynamic queryset construction MEDIUM search_objects.py
10 Error info disclosure MEDIUM middleware/HandleErrorPages.py
11 Missing security headers MEDIUM settings.py
12 Permissive ALLOWED_HOSTS LOW settings.py
13 No rate limiting LOW Auth endpoints
14 User enumeration LOW login_view.py
15 Insecure file permissions LOW LocalFileHandler.py
16 Missing CSP LOW settings.py
17 Public link brute force LOW public_views.py

Based on these findings, here are security tooling projects you could build:

1. Django Security Configuration Auditor

Scans Django settings for production readiness (DEBUG, SECRET_KEY, security headers, password validators, token expiry, etc.)

2. Secure File Upload Middleware for Django

Drop-in replacement for FileField handling with:

  • Magic byte detection (python-magic)
  • MIME type allowlisting
  • Filename sanitization
  • Virus scanning integration (ClamAV)
  • Path traversal prevention

3. IDOR/Authorization Testing Framework for DRF

Automated penetration testing tool that:

  • Enumerates all API endpoints
  • Tests object-level permissions with different user contexts
  • Reports bypasses

4. Django Secret Scanner

Pre-commit/CI tool that detects:

  • Hardcoded secrets (keys, passwords, tokens)
  • Insecure settings patterns
  • Debug configurations in production branches

5. API Token Security Manager

Enhances django-rest-knox with:

  • Mandatory token expiry
  • Token rotation policies
  • Per-user token limits
  • Suspicious activity detection (geo-velocity, concurrent sessions)

6. Django ORM Injection Linter

Static analysis for dangerous queryset patterns using dynamic field names.


📝 Next Steps for NearBeach Maintainers

  1. Immediate: Move SECRET_KEY to environment variable, set DEBUG=False for production
  2. High Priority: Implement file upload validation, add security headers, configure token expiry
  3. Medium: Add rate limiting, fix password reset flow, implement CSP
  4. Ongoing: Security code reviews, dependency scanning (bandit is already in dev deps - good!)