HIGH ssrfdjangocockroachdb

Ssrf in Django with Cockroachdb

Ssrf in Django with Cockroachdb — how this specific combination creates or exposes the vulnerability

Server-Side Request Forgery (SSRF) in a Django application that uses CockroachDB can arise when the app builds database queries or external requests using attacker-controlled data. Because CockroachDB is compatible with PostgreSQL wire protocol, Django typically interacts with it through database drivers such as psycopg or django-postgresql. An SSRF risk emerges not from CockroachDB itself, but from how the application uses user input to construct URLs or external HTTP calls while also storing or logging data in CockroachDB.

For example, consider a Django view that accepts a URL parameter to fetch external metadata and then saves that metadata into a CockroachDB table. If the URL is not validated, an attacker can supply an internal address such as http://169.254.169.254/latest/meta-data/iam/security-credentials/ on AWS, leading to SSRF. The metadata response might be parsed and stored in a CockroachDB-backed model, exposing internal infrastructure details. In another scenario, a developer might use raw SQL or an ORM query that incorporates user input into a host or port field, inadvertently allowing an attacker to influence network paths or trigger unintended external connections via the application’s network egress.

middleBrick detects such risks by scanning the unauthenticated attack surface of Django endpoints that interact with CockroachDB. It identifies inputs that reach external requests or are logged in database fields without proper validation. Because the scan runs 12 security checks in parallel, it surfaces issues in Input Validation, Data Exposure, and Unsafe Consumption within seconds. The scanner also cross-references any OpenAPI specification with runtime findings, ensuring that declared endpoints align with actual behavior. This is particularly useful when the API surface includes endpoints that store or retrieve data from CockroachDB, as misconfigured schemas or missing authorization checks can amplify SSRF impact.

Real-world attack patterns relevant to this combination include attempts to read internal service metadata, pivot to other internal databases, or exfiltrate data via DNS or outbound HTTP callbacks. Since CockroachDB often serves as a distributed backend for sensitive workloads, any SSRF that allows an attacker to influence query routing or data logging can lead to broader compromise. The presence of an OpenAPI spec does not mitigate these issues; without strict input validation and network egress controls, SSRF remains a viable threat vector.

Cockroachdb-Specific Remediation in Django — concrete code fixes

Remediation focuses on strict input validation, avoiding direct use of user input in network calls, and ensuring database interactions follow the principle of least privilege. Below are concrete Django models and views that demonstrate secure handling when working with CockroachDB.

Secure Django model for CockroachDB

from django.db import models

class ExternalMetadata(models.Model):
    name = models.CharField(max_length=255)
    source_url = models.URLField()
    fetched_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'external_metadata'

Validated view with no user-controlled network calls

from django.http import JsonResponse
from django.views import View
from urllib.parse import urlparse
from .models import ExternalMetadata
import requests

ALLOWED_DOMAINS = {'api.example.com', 'data.example.com'}

class FetchMetadataView(View):
    def post(self, request):
        url = request.POST.get('url', '').strip()
        parsed = urlparse(url)
        if parsed.scheme not in ('https',):
            return JsonResponse({'error': 'Only HTTPS URLs are allowed'}, status=400)
        if parsed.hostname not in ALLOWED_DOMAINS:
            return JsonResponse({'error': 'Hostname not allowed'}, status=400)

        try:
            resp = requests.get(url, timeout=5, verify=True)
            resp.raise_for_status()
        except requests.RequestException:
            return JsonResponse({'error': 'Failed to fetch URL'}, status=400)

        # Store only safe, validated data
        metadata = ExternalMetadata.objects.create(
            name=parsed.hostname,
            source_url=url
        )
        return JsonResponse({'id': metadata.id, 'name': metadata.name})

CockroachDB connection settings in settings.py

import os

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('COCKROACH_DB', 'mydb'),
        'USER': os.getenv('COCKROACH_USER', 'root'),
        'PASSWORD': os.getenv('COCKROACH_PASSWORD', ''),
        'HOST': os.getenv('COCKROACH_HOST', 'localhost'),
        'PORT': os.getenv('COCKROACH_PORT', '26257'),
        'OPTIONS': {
            'sslmode': 'require',
        },
    }
}

CI/CD integration

Using the middleBrick GitHub Action, you can add API security checks to your CI/CD pipeline and fail builds if risk scores drop below your threshold. This ensures that any new endpoints interacting with CockroachDB are validated before deployment.

CLI scanning

You can also scan from the terminal with the middlebrick CLI to get immediate feedback on SSRF and related issues: middlebrick scan https://api.example.com/openapi.json. The output includes prioritized findings with severity and remediation guidance.

Related CWEs: ssrf

CWE IDNameSeverity
CWE-918Server-Side Request Forgery (SSRF) CRITICAL
CWE-441Unintended Proxy or Intermediary (Confused Deputy) HIGH

Frequently Asked Questions

Can SSRF be detected by inspecting OpenAPI specs alone?
No. OpenAPI specs describe intended behavior but cannot reveal runtime issues such as missing input validation or unsafe external calls. middleBrick cross-references specs with runtime findings to highlight discrepancies.
Does using CockroachDB change the remediation steps for SSRF in Django?
No. SSRF remediation focuses on input validation, network controls, and safe handling of external data. CockroachDB compatibility with PostgreSQL means standard Django security practices apply.