Ssrf Server Side in Chi with Cockroachdb
Ssrf Server Side 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 database connection parameters. Chi is a minimalistic HTTP router for Go, and SSRF often occurs when endpoints accept a URL or host and port supplied by the client, which the server subsequently uses to make outbound requests or to build connection strings. When the backend also relies on CockroachDB, an attacker may attempt to leverage SSRF to reach CockroachDB nodes or other internal services that are not exposed publicly.
In this combination, the risk typically arises if an endpoint in Chi reads a URL or host/port from query parameters or JSON payloads and uses it to initialize an HTTP client or a CockroachDB SQL connection. For example, if an endpoint accepts a host parameter and constructs a CockroachDB connection string dynamically, an attacker can supply an internal address such as localhost:26257 or a Cloud Internal IP, bypassing network exposure controls. Because CockroachDB often requires careful network segmentation, SSRF can unintentionally provide a pivot point to the database cluster, especially when the database listens on localhost or internal interfaces and relies on IP-based allowlists rather than strict authentication controls.
The vulnerability is not introduced by Chi or CockroachDB themselves, but by how they are wired together in application code. If input validation is weak and the application does not sanitize or restrict destinations, an attacker may probe internal services, enumerate cluster nodes, or attempt to trigger unauthorized SQL statements via SSRF-induced connections. This becomes particularly critical when the application uses the same network namespace as CockroachDB or when service discovery logic is driven by attacker-supplied data. Even without direct SQL injection, SSRF can expose metadata endpoints or be used in chained attacks, such as log poisoning or lateral movement within a secured environment.
middleBrick can help detect this class of issue by scanning the unauthenticated attack surface of a Chi endpoint, identifying whether user-controlled inputs influence network destinations or database connection parameters. While middleBrick does not fix code, its findings include remediation guidance to harden input validation and network segregation.
Cockroachdb-Specific Remediation in Chi — concrete code fixes
To mitigate SSRF in Chi applications that interact with CockroachDB, you should enforce strict allowlisting, avoid dynamic connection string assembly from user input, and isolate database credentials from request handling. The following practices and code examples demonstrate secure patterns.
1. Avoid user input in connection strings. Do not construct CockroachDB connection strings from request parameters. Instead, use a fixed, secure connection string defined via environment variables or configuration files. For example:
import (
"context"
"os"
"log"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/labstack/chi/v5"
)
func main() {
connStr := os.Getenv("COCKROACHDB_URL")
if connStr == "" {
log.Fatal("COCKROACHDB_URL environment variable is required")
}
pool, err := pgxpool.New(context.Background(), connStr)
if err != nil {
log.Fatalf("Unable to connect to CockroachDB: %v", err)
}
defer pool.Close()
r := chi.NewRouter()
r.Get("/safe-endpoint", func(w http.ResponseWriter, r *http.Request) {
// Use pool for queries; no dynamic host/port from request
var result string
if err := pool.QueryRow(r.Context(), "SELECT current_database()").Scan(&result); err != nil {
http.Error(w, "database error", http.StatusInternalServerError)
return
}
w.Write([]byte(result))
})
http.ListenAndServe(":8080", r)
}
This pattern ensures that the database endpoint is configured externally and cannot be overridden by an attacker through request data.
2. Validate and restrict outbound destinations. If your Chi application must make outbound HTTP requests based on user input, validate the target host against a strict allowlist and reject private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) and localhost. Example validation helper:
import (
"net"
"net/url"
"errors"
)
func isValidDestination(rawURL string) error {
parsed, err := url.Parse(rawURL)
if err != nil {
return errors.New("invalid URL")
}
host := parsed.Hostname()
ip := net.ParseIP(host)
if ip != nil {
if ip.IsLoopback() || ip.IsPrivate() {
return errors.New("destination not allowed")
}
}
// Optionally enforce allowlist of approved domains
return nil
}
Use this validator before initiating any HTTP client call or constructing external queries, ensuring that SSRF cannot be used to reach CockroachDB on internal interfaces.
3. Use least-privilege database roles. Even if SSRF is mitigated, configure CockroachDB roles used by the Chi application with minimal privileges. For instance, create a dedicated role with read-only access for endpoints that only need to query data:
-- CockroachDB SQL example
CREATE USER chi_app WITH PASSWORD 'strong-password';
GRANT SELECT ON TABLE public.widgets TO chi_app;
REVOKE ALL ON DATABASE cluster_db FROM chi_app;
By combining strict input validation, fixed connection strings, and least-privilege database permissions, you reduce the attack surface presented by SSRF in Chi applications interfacing with CockroachDB.