HIGH ssrfchicockroachdb

Ssrf in Chi with Cockroachdb

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

Server-Side Request Forgery (SSRF) in a Chi application that uses CockroachDB can emerge when user-controlled input is used to form network requests or connection parameters, and the runtime environment can reach the CockroachDB node(s). Chi routes are typically defined with pattern matchers and handlers; if a handler constructs a URL or a database connection string from request data without strict validation, an attacker can steer the outbound request to internal services.

In a typical Chi setup, you might use a database/sql or pgx connection to CockroachDB. If a handler dynamically builds a connection string using parameters such as host, port, or database from the request, an SSRF vector can be introduced. For example, an attacker could supply a malicious hostname that resolves to CockroachDB’s internal RPC port (26257) or to the Admin UI (8080), probing internal network services that are not exposed publicly. Even though CockroachDB advertises a public SQL interface on port 26257, allowing the application to connect from any authenticated client, SSRF can bypass intended network segmentation by leveraging the application as a proxy to reach internal nodes, admin endpoints, or metadata services that should remain isolated.

middleBrick detects SSRF as one of its 12 parallel security checks during an unauthenticated scan. When scanning a Chi endpoint that interacts with CockroachDB, the tool attempts to coax the application into making outbound requests to internal addresses, such as http://169.254.169.254 (cloud metadata) or internal hostnames like cockroach-internal.default.svc.cluster.local. If the application follows these redirects or accepts injected parameters that change the target host/port, middleBrick surfaces a finding with severity and remediation guidance. Because Chi does not enforce a default outbound allowlist, developers must explicitly validate and restrict destinations, especially when the application uses dynamic inputs to form SQL connection parameters.

CockroachDB’s connection behavior can amplify the impact. For instance, if the application uses a connection pool and retries, an SSRF-triggered connection to an internal admin endpoint might disclose cluster state, node certificates, or configuration via the Admin API. Even if the SQL interface requires authentication, the SSRF may allow the attacker to map internal network topology or perform service discovery, which can aid further exploitation. middleBrick’s OpenAPI/Swagger analysis (supporting 2.0, 3.0, 3.1 with full $ref resolution) helps correlate runtime endpoints with spec-defined routes to highlight parameters that flow into network destinations without proper validation.

Cockroachdb-Specific Remediation in Chi — concrete code fixes

Remediation focuses on strict input validation, avoiding dynamic construction of connection parameters, and ensuring that outbound destinations are fixed and trusted. Below are concrete Chi + CockroachDB code examples that demonstrate secure practices.

  • Use a fixed, authenticated connection string for CockroachDB and avoid interpolating user input into host or port. Define the Data Source Name (DSN) as an environment variable or a sealed configuration value.
// secure_db.go
package main

import (
	"context"
	"database/sql"
	"log"
	"os"

	_ "github.com/lib/pq"
)

func main() {
	// Fixed DSN from environment; do not build from user input.
	dsn := os.Getenv("COCKROACH_DSN")
	if dsn == "" {
		log.Fatal("COCKROACH_DSN is required")
	}
	db, err := sql.Open("postgres", dsn)
	if err != nil {
		log.Fatalf("failed to open db: %v", err)
	}
	defer db.Close()

	// Use parameterized queries to avoid injection.
	var userID string
	err = db.QueryRowContext(context.Background(), "SELECT username FROM users WHERE id = $1", userID).Scan(&username)
	if err != nil {
		log.Printf("query error: %v", err)
	}
}
  • If you must accept a tenant identifier, validate it against a strict allowlist and use it only to select a predefined connection pool rather than altering the host or port.
// tenant_handler.go
package main

import (
	"net/http"

	"github.com/go-chi/chi/v5"
)

var tenantDB = map[string]*sql.DB{
	"tenantA": dbTenantA, // pre-initialized *sql.DB with fixed DSN
	"tenantB": dbTenantB,
}

func tenantMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tid := chi.URLParam(r, "tenant")
		db, ok := tenantDB[tid]
		if !ok {
			http.Error(w, "invalid tenant", http.StatusBadRequest)
			return
		}
		ctx := context.WithValue(r.Context(), "db", db)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
  • Ensure outbound HTTP client behavior does not follow redirects to internal addresses. Configure http.Client with a custom CheckRedirect function to prevent SSRF-assisted probing of internal CockroachDB Admin UI or metadata endpoints.
// http_client.go
package main

import (
	"context"
	"net/http"
	"time"
)

func secureHTTPClient() *http.Client {
	return &http.Client{
		Timeout: 10 * time.Second,
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse // prevent following redirects to internal hosts
		},
	}
}

func fetchExternal(ctx context.Context, url string) (*http.Response, error) {
	client := secureHTTPClient()
	req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
	return client.Do(req)
}
  • Apply network-level controls in your deployment (e.g., firewall rules or service mesh policies) to restrict outbound traffic from the application to known, necessary endpoints only, especially to prevent reaching CockroachDB’s Admin UI on port 8080 from user-influenced flows.

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 in Chi allow an attacker to reach CockroachDB's Admin UI?
Yes, if user input is used to construct outbound URLs or connection parameters without strict validation, an SSRF can redirect or connect the application to CockroachDB's Admin UI (e.g., :8080) or internal RPC ports, bypassing intended network exposure.
Does middleBrick fix SSRF findings in Chi apps?
middleBrick detects and reports SSRF with severity and remediation guidance; it does not fix the issue. Developers must validate inputs and restrict outbound destinations, and use fixed DSNs for CockroachDB.