CRITICAL missing tlsdjangobasic auth

Missing Tls in Django with Basic Auth

Missing Tls in Django with Basic Auth — how this specific combination creates or exposes the vulnerability

Using HTTP Basic Authentication in a Django application without Transport Layer Security (TLS) exposes credentials and session context to network-level attackers. Basic Auth encodes the username and password with Base64, which is trivial to decode; without encryption, any intermediary on the network can recover the credentials. In Django, if settings.DEBUG = True or if the application is served over plain HTTP, the credentials are transmitted in the Authorization header in clear text. This becomes especially dangerous when combined with other attack surfaces such as insecure cookies, missing HTTP Strict Transport Security (HSTS), or unencrypted logging where headers may be persisted.

In a black-box scan, middleBrick tests unauthenticated endpoints and checks for the presence of TLS and secure transport headers. Without TLS, findings related to authentication mechanisms, data exposure, and insecure consumption are flagged with higher severity. Even if Django’s built-in protections (e.g., CSRF middleware, secure session cookies) are properly configured, the lack of TLS undermines the confidentiality of the Basic Auth credentials, enabling credential theft, session hijacking, and potential lateral movement in the network.

For context, many organizations use Basic Auth for integration with legacy systems or simple API clients, but it must always be paired with TLS. middleBrick’s checks include verifying response headers, inspecting whether redirects enforce HTTPS, and validating that endpoints using authentication are served only over encrypted channels. Without TLS, the authentication boundary is effectively absent, and findings from checks such as Data Exposure, Authentication, and Unsafe Consumption will reflect the risk of clear-text credential transmission.

Basic Auth-Specific Remediation in Django — concrete code fixes

Remediation centers on enforcing HTTPS and ensuring that Basic Auth is only used over encrypted connections. The first step is to configure Django to require secure connections for all views that handle authentication. Use django-sslserver only in development and rely on proper TLS termination at the load balancer or reverse proxy in production. Set SECURE_SSL_REDIRECT = True to ensure all HTTP requests are redirected to HTTPS, and SESSION_COOKIE_SECURE = True and CSRF_COOKIE_SECURE = True to prevent cookies from being sent over HTTP.

Below is a minimal, secure Django settings snippet for production use with Basic Auth:

# settings.py
import os

DEBUG = False
ALLOWED_HOSTS = ['api.example.com']

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

In your views, if you must use Basic Auth for integration, ensure the request is verified as secure before processing credentials. For example:

# views.py
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
import base64

@require_http_methods(["GET"])
def protected_view(request):
    auth = request.META.get('HTTP_AUTHORIZATION', '')
    if not auth.lower().startswith('basic '):
        response = HttpResponse(status=401)
        response['WWW-Authenticate'] = 'Basic realm="api"'
        return response

    # Enforce HTTPS before decoding credentials
    if not request.is_secure():
        return JsonResponse({'error': 'HTTPS required'}, status=403)

    try:
        encoded = auth.split(' ')[1]
        decoded = base64.b64decode(encoded).decode('utf-8')
        username, password = decoded.split(':', 1)
        # Validate credentials against Django user model or external source
        if username == 'admin' and password == 's3cret':  # replace with secure validation
            return JsonResponse({'status': 'ok'})
        return JsonResponse({'error': 'invalid credentials'}, status=401)
    except Exception:
        return JsonResponse({'error': 'bad request'}, status=400)

For production, avoid embedding credentials in code and use environment variables or a secrets manager. Consider replacing Basic Auth with token-based authentication (e.g., OAuth2, JWT) where possible. middleBrick’s scans will highlight missing TLS and weak authentication practices; the Pro plan’s continuous monitoring can alert you if any endpoint reverts to HTTP or if insecure authentication headers are detected.

When integrating into CI/CD, the GitHub Action can fail builds if a scan detects authentication endpoints without enforced HTTPS. The MCP Server allows you to run on-demand checks from your IDE to validate that changes do not introduce insecure authentication flows. These integrations ensure that TLS remains enforced alongside Basic Auth or any other authentication mechanism.

Related CWEs: encryption

CWE IDNameSeverity
CWE-319Cleartext Transmission of Sensitive Information HIGH
CWE-295Improper Certificate Validation HIGH
CWE-326Inadequate Encryption Strength HIGH
CWE-327Use of a Broken or Risky Cryptographic Algorithm HIGH
CWE-328Use of Weak Hash HIGH
CWE-330Use of Insufficiently Random Values HIGH
CWE-338Use of Cryptographically Weak PRNG MEDIUM
CWE-693Protection Mechanism Failure MEDIUM
CWE-757Selection of Less-Secure Algorithm During Negotiation HIGH
CWE-261Weak Encoding for Password HIGH

Frequently Asked Questions

Can Basic Auth be used securely without TLS in Django?
No. Basic Auth transmits credentials in a reversible format; without TLS, credentials are exposed in clear text on the network. Always use TLS with Basic Auth.
How does middleBrick detect missing TLS for authenticated endpoints?
middleBrick scans unauthenticated attack surfaces and checks for HTTPS enforcement, secure redirect headers, and the presence of TLS. Findings are mapped to relevant checks such as Data Exposure and Authentication.