Skip to content

ThiagoMaria-SecurityIT/Django-Security-Checklist

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ Django Security Checklist

A comprehensive security checklist for Django developers before uploading or deploying projects

Django Security Contributors

πŸ“– Table of Contents

πŸš€ Why This Checklist?

Accidentally committing secrets or misconfiguring Django settings is one of the most common security pitfalls. This checklist helps you avoid:

  • API key exposure
  • Database credential leaks
  • Debug mode in production
  • Insecure settings configuration
  • Accidental secret commits

⚑ Quick Scan

Run these commands immediately before any commit:

# Scan for secrets
grep -r "SECRET_KEY" . --include="*.py"
grep -r "password" . --include="*.py" -i
grep -r "API_KEY" . --include="*.py" -i

# Check critical settings
grep -n "DEBUG" settings.py
grep -n "ALLOWED_HOSTS" settings.py

# Find sensitive files
find . -name "*.sqlite3" -o -name ".env" -o -name "*.pyc"

πŸ” Detailed Checklist

🚨 CRITICAL (Must Check Before Every Upload)

  • SECRET_KEY removed from settings.py
  • Database files (.sqlite3, .db) removed
  • Environment files (.env, .yml) deleted
  • DEBUG set to False
  • ALLOWED_HOSTS properly configured (not ['*'])
  • API keys, tokens, and passwords removed from code

πŸ“ Files to Remove

  • db.sqlite3 and any *.db files
  • .env and environment configuration files
  • *.pyc compiled Python files
  • __pycache__/ directories
  • IDE-specific files (.vscode/, .idea/)
  • Log files (*.log)

βš™οΈ Settings Security

  • DEBUG = False for production
  • ALLOWED_HOSTS = ['yourdomain.com'] (specific hosts, not ['*'])
  • CSRF_COOKIE_SECURE = True
  • SESSION_COOKIE_SECURE = True
  • SECURE_BROWSER_XSS_FILTER = True
  • SECURE_CONTENT_TYPE_NOSNIFF = True
  • X_FRAME_OPTIONS = 'DENY'

πŸ”§ Pre-Upload Tools

Installation

pip install bandit safety

Usage

# Scan Python code for security issues
bandit -r .

# Check for vulnerable packages
safety check

# Generate HTML report
bandit -r . -f html -o security_report.html

# Check for secrets
git secrets --scan  # If using git-secrets

🚨 Emergency Procedures

If you accidentally committed secrets:

# 1. ROTATE KEYS IMMEDIATELY (API keys, database passwords, etc.)
# 2. Rewrite git history
git filter-repo --force --invert-paths --path sensitive-file.txt

# 3. Force push
git push origin --force --all

# 4. Verify the secrets are gone
git log --oneline  # Check history

πŸ“‹ Safe settings.py Template

# settings.py (Safe Template - Use Environment Variables)
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# Environment variables for security - NEVER HARDCODE THESE!
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-key-only-for-development')
DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')

# Database configuration via environment variables
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
        # For production, use environment variables:
        # 'NAME': os.environ.get('DB_NAME'),
        # 'USER': os.environ.get('DB_USER'),
        # 'PASSWORD': os.environ.get('DB_PASSWORD'),
        # 'HOST': os.environ.get('DB_HOST'),
        # 'PORT': os.environ.get('DB_PORT'),
    }
}

# Security headers (auto-enable in production)
if not DEBUG:
    SECURE_BROWSER_XSS_FILTER = True
    SECURE_CONTENT_TYPE_NOSNIFF = True
    X_FRAME_OPTIONS = 'DENY'
    CSRF_COOKIE_SECURE = True
    SESSION_COOKIE_SECURE = True
    SECURE_SSL_REDIRECT = True
    SECURE_HSTS_SECONDS = 31536000  # 1 year
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True

πŸ”’ Manual Upload Security Guide

Critical Security Concerns for Manual Upload

When manually uploading Django projects, these are the most critical security concerns:

1. Secrets and Credentials 🚨

NEVER COMMIT THESE:

# Django Secret Key (in settings.py)
SECRET_KEY = 'your-super-secret-key-here'  # ← REMOVE BEFORE UPLOAD

# Database passwords
DATABASES = {
    'default': {
        'PASSWORD': 'your-database-password',  # ← REMOVE
    }
}

# API keys, tokens, and secrets
API_KEY = 'sk_live_1234567890'  # ← REMOVE
AWS_ACCESS_KEY = 'AKIA...'  # ← REMOVE
STRIPE_SECRET_KEY = 'sk_test_...'  # ← REMOVE

Solution: Always use environment variables:

# settings.py - SAFE APPROACH
import os
SECRET_KEY = os.environ.get('SECRET_KEY', 'fallback-for-dev-only')
DATABASE_PASSWORD = os.environ.get('DB_PASSWORD')
API_KEY = os.environ.get('API_KEY')

2. Database Files πŸ—„οΈ

Remove immediately:

  • db.sqlite3 (contains user data, emails, progress, potentially sensitive information)
  • Any .db files
  • Database backups (*.backup, *.bak)

3. Environment Files 🌐

Delete before upload:

  • .env files (often contain secrets)
  • environment.yml / .env.example (might contain template secrets)
  • Any file containing credentials or configuration secrets

4. Debug Mode πŸ›

Ensure this is FALSE:

# settings.py
DEBUG = False  # ← Must be False for production/public code

5. Allowed Hosts 🌍

Set properly (never use wildcard):

# settings.py - UNSAFE
ALLOWED_HOSTS = ['*']  # ← Dangerous! Allows any host

# settings.py - SAFE
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']  # ← Specific hosts only

Pre-Upload Security Scan

Manual Code Review Checklist:

# Search for secrets in your code
grep -r "SECRET_KEY" . --include="*.py"
grep -r "password" . --include="*.py" -i
grep -r "API_KEY" . --include="*.py" -i
grep -r "token" . --include="*.py" -i
grep -r "key" . --include="*.py" -i | grep -v "foreign" | grep -v "primary"

# Check for debug mode and settings
grep -n "DEBUG" settings.py
grep -n "ALLOWED_HOSTS" settings.py
grep -A 10 -B 5 "DATABASES" settings.py

# Find sensitive files
find . -name "*.sqlite3" -o -name "*.db" -o -name ".env" -o -name "*.pyc"

Files to Double-Check Before Upload:

  1. settings.py - Most critical file (contains most secrets)
  2. .env / .env.example - Environment files
  3. *.json config files - Might contain API keys
  4. requirements.txt - Check for vulnerable packages
  5. docker-compose.yml - Might contain hardcoded credentials

Security Tools to Run Before Upload

# Install security scanners
pip install bandit safety

# Scan for Python vulnerabilities and security issues
bandit -r .

# Check for vulnerable packages in requirements.txt
safety check

# Alternative: use git-secrets for pattern matching
git secrets --install
git secrets --register-aws
git secrets --scan

# Create a safe archive without sensitive files
zip -r project-safe.zip . -x "*.sqlite3" "venv/*" ".env" "__pycache__/*" "*.pyc" ".git/*"

πŸ“‹ Pre-Upload Checklist

βœ… MUST DO (Critical):

  • Remove SECRET_KEY from settings.py
  • Delete db.sqlite3 and any database files
  • Remove any .env files and environment configurations
  • Set DEBUG = False
  • Configure ALLOWED_HOSTS properly (not ['*'])
  • Check for hardcoded API keys and passwords
  • Remove any personal data, emails, or sensitive comments

βœ… RECOMMENDED (Best Practices):

  • Scan with bandit and safety check
  • Update packages in requirements.txt to latest secure versions
  • Remove unused imports and dead code
  • Check file permissions (no world-writable files)
  • Review error messages for information leakage
  • Validate all form inputs and use Django's security features

🚨 Emergency Steps if You Accidentally Upload Secrets

If you accidentally commit secrets, act immediately:

  1. ROTATE ALL EXPOSED KEYS - This is the most critical step!

    • Change database passwords
    • Rotate API keys
    • Generate new secret keys
    • Revoke and replace any exposed tokens
  2. Rewrite git history to remove the secrets:

# Install git-filter-repo if needed
pip install git-filter-repo

# Remove sensitive files from history
git filter-repo --force --invert-paths --path secrets.txt
git filter-repo --force --invert-paths --path settings.py  # If it contained secrets
  1. Force push to all branches:
git push origin --force --all
git push origin --force --tags
  1. Verify the cleanup:
git log --oneline  # Check that sensitive commits are gone
git grep "secret_key"  # Search for any remaining secrets
  1. Monitor for abuse - Watch for unauthorized access attempts on your services

🌐 Production Deployment Considerations

Even if just uploading to GitHub, assume someone might try to deploy your code:

  1. Use environment variables for all secrets and configurations
  2. Add clear deployment instructions in README.md
  3. Include security settings in your code
  4. Mention required environment variables
  5. Provide example environment files (without real secrets)

πŸ“ Final Verification

Before uploading, run this comprehensive check:

#!/bin/bash
echo "πŸ”’ Final Security Check"
echo "======================"

# Check for secrets
echo "1. Searching for secrets..."
grep -r "SECRET_KEY" . --include="*.py" | grep -v "os.environ.get" && echo "❌ Hardcoded secrets found!"

# Check settings
echo "2. Checking settings..."
grep -n "DEBUG" settings.py | grep "True" && echo "❌ DEBUG is True!"
grep -n "ALLOWED_HOSTS" settings.py | grep "\*" && echo "❌ ALLOWED_HOSTS contains wildcard!"

# Check for sensitive files
echo "3. Checking for sensitive files..."
find . -name "*.sqlite3" -o -name ".env" | xargs -I {} echo "❌ Found: {}"

echo "======================"
echo "βœ… Final check completed. Review any warnings above."

🀝 Contributing

Found a new security concern? Please contribute!

  1. Fork the repository
  2. Add your security tip or improvement
  3. Submit a pull request
  4. Help keep the Django community secure!

πŸ“„ License

MIT License - feel free to use this checklist for your projects! See LICENSE file for details.


πŸ”— Related Resources

🎯 Pro Tips

  • Automate scans with git pre-commit hooks
  • Use CI/CD to run security checks automatically
  • Regularly update your dependencies
  • Educate your team on security best practices
  • Assume breach - plan what you'll do if secrets are exposed

By following this comprehensive checklist, you'll ensure your Django projects are secure before they ever leave your development environment! πŸ›‘οΈ


Remember: Security is a process, not a product. Regular reviews and vigilance are key to maintaining secure applications.

About

A comprehensive security checklist for Django developers before uploading or deploying projects

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published