Ssrf Server Side in Grape with Cockroachdb
Ssrf Server Side in Grape with Cockroachdb — how this specific combination creates or exposes the vulnerability
Server-side request forgery (SSRF) in a Grape API backed by CockroachDB can arise when an endpoint accepts a user-supplied URL and uses it to make outbound HTTP requests before interacting with the database. If the request logic does not validate or restrict destinations, an attacker can coerce the service into reading internal metadata services or arbitrary internal hosts. Because CockroachDB is often reachable only from the application network, SSRF can become a pivot point: the compromised Grape process may be used to scan internal SQL ports or configuration endpoints that would otherwise be unreachable. The vulnerability is not in CockroachDB itself but in how the Grape service uses HTTP clients and database connections after fetching user-controlled input.
Consider a Grape endpoint that fetches a remote configuration by URL and stores settings into CockroachDB. If the URL is not constrained, an attacker can point the request to http://localhost:26257 (the default CockroachDB SQL port) or to cloud metadata endpoints such as http://169.254.169.254. The database driver may follow redirects or use the same network namespace, allowing SSRF to leak cluster internal information or trigger unintended SQL queries via injected HTTP responses. MiddleBrick’s unauthenticated scan would flag such endpoints under SSRF and Data Exposure checks, highlighting risk patterns like missing destination allowlists or unsafe HTTP client configurations.
OpenAPI specifications can inadvertently encourage risky designs. If a path parameter such as source_url is defined without format or enum constraints, and the spec is resolved with full $ref expansion, the schema may appear permissive while runtime behavior remains dangerous. MiddleBrick’s OpenAPI/Swagger analysis resolves cross-references and compares spec definitions with runtime findings to detect mismatches that could enable SSRF. Because Grape apps often compose database clients and HTTP clients in the same request lifecycle, an SSRF vector can chain into database reconnaissance or credential leakage if CockroachDB connection strings or debug endpoints are exposed internally.
Specific attack patterns include forcing the Grape service to perform HTTP requests to internal Kubernetes services, DNS rebinding against CockroachDB nodes, or using response smuggling to inject headers that alter connection behavior. The database may log connection attempts from unexpected sources, and those logs can be exfiltrated if SSRF also reaches logging or observability endpoints. Mitigation requires strict destination allowlists, disabling unnecessary protocols, and ensuring that database drivers do not follow redirects to internal addresses. MiddleBrick’s findings map to OWASP API Top 10 A05:2023 (SSRF) and include remediation guidance tailored to language-specific HTTP clients and database drivers used with Grape and CockroachDB.
Cockroachdb-Specific Remediation in Grape — concrete code fixes
Remediation centers on validating and restricting outbound requests and hardening database connectivity. For Grape endpoints that accept URLs, enforce a strict allowlist of permitted hosts and reject non-HTTP(S) schemes. Use a URI parser to separate host, port, and scheme, and compare against a whitelist that excludes internal RFC 1918 ranges, localhost, and CockroachDB default ports. Avoid passing user input directly to database connection strings or HTTP client redirects.
Example: a secure Grape endpoint that fetches a remote configuration and stores it in CockroachDB using a preconfigured, trusted connection.
require 'grape'
require 'net/http'
require 'uri'
require 'pg' # assuming cockroachdb via the pg driver
class SecureAPI < Grape::API
format :json
# Whitelist of allowed hosts for outbound requests
ALLOWED_HOSTS = ['api.example.com', 'config.example.com']
helpers do
def safe_fetch(url)
uri = URI.parse(url)
unless uri.respond_to?(:host) && ALLOWED_HOSTS.include?(uri.host)
raise Grape::Exceptions::Validation, { message: { url: ['destination not allowed'] } }
end
# Disable redirects and enforce timeouts
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 5, read_timeout: 10) do |http|
request = Net::HTTP::Get.new(uri)
request['User-Agent'] = 'middleBrick-secure-client'
http.request(request)
end
case response
when Net::HTTPSuccess
response.body
else
raise "Unexpected response: #{response.code}"
end
rescue URI::InvalidURIError, SocketError => e
raise Grape::Exceptions::Validation, { message: { url: ['invalid or unreachable'] } }
end
end
post do
source_url = params[:source_url]
config_body = safe_fetch(source_url)
# Use a trusted, prevalidated connection string; never inject user input
conn = PG.connect(
host: 'cockroachdb-internal.default.svc.cluster.local',
port: 26257,
dbname: 'settings',
user: 'appuser',
password: ENV['COCKROACHDB_PASSWORD'],
sslmode: 'require'
)
conn.exec_params('INSERT INTO configs (name, value) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET value = $2', ['remote_config', config_body])
{ status: 'saved' }
end
end
In this example, the outbound request is constrained by a host allowlist and validated with URI parsing, preventing SSRF pivots to localhost or metadata services. The CockroachDB connection uses a fixed internal host with SSL enforcement and parameterized queries, avoiding any concatenation of user input. MiddleBrick can verify that such patterns are present by scanning the deployed API and comparing runtime behavior against the OpenAPI spec, highlighting insecure client configurations or overly permissive routing rules.
Additional hardening includes disabling HTTP redirect following, using a dedicated service account with minimal privileges in CockroachDB, and ensuring that database credentials are injected via secure secret management rather than configuration files. If the API must accept arbitrary destination URLs for integration purposes, consider using an outbound proxy with strict network policies that block internal addresses. MiddleBrick’s Pro plan supports continuous monitoring and CI/CD integration to ensure that future changes do not reintroduce SSRF or weaken database connectivity controls.