Crlf Injection in Cockroachdb
How CRLF Injection Manifests in CockroachDB
Carriage Return Line Feed (CRLF) injection in CockroachDB APIs occurs when an attacker injects %0d%0a (URL-encoded CRLF) into HTTP request parameters or headers that are later reflected in HTTP responses or logs without proper sanitization. CockroachDB's HTTP API (used by its sql CLI, web UI, and programmatic clients) and custom applications built on top of it are vulnerable if user-supplied data flows unsanitized into response headers, bodies, or server logs.
CockroachDB-Specific Attack Patterns:
- HTTP Response Splitting via SQL Error Messages: When a malformed SQL query is executed via CockroachDB's HTTP endpoint (e.g.,
/api/v1/sql), the database may return an error message containing the raw query. If an attacker controls part of the query (e.g., via asearchparameter in an application layer), they can inject CRLF sequences to split the HTTP response, injecting malicious headers or HTML. Example vulnerable pattern:
IfPOST /api/v1/sql HTTP/1.1 Host: db.example.com Content-Type: application/json { "sql": "SELECT * FROM users WHERE name = '" + userInput + "'" }userInputis'%0d%0aSet-Cookie: malicious=1%0d%0a, the response could be split, setting a cookie. - Log Injection via
pg_catalog.pg_read_fileor Error Logs: CockroachDB supports PostgreSQL-compatible functions likepg_read_file(with restricted permissions). If an application inadvertently logs user input to a file that is later read via SQL and echoed in an HTTP response, CRLF in the input can corrupt log files or inject fake log entries. More commonly, SQL errors generated from user input are logged by the database or application server. Injecting CRLF into these logs can forge log entries or, if logs are viewed in a web interface, lead to XSS. - Header Injection in Custom Proxies/API Gateways: Applications that proxy requests to CockroachDB and set HTTP headers based on database values (e.g.,
X-User-ID: [value from query]) are vulnerable if the value contains CRLF. CockroachDB's distributed SQL engine may return multi-line error messages or data containing newlines (e.g.,COPYoutput), which if copied into headers, enable header injection.
CockroachDB's compatibility with PostgreSQL means many attack vectors mirror those in PostgreSQL-based applications, but its HTTP API and distributed error formatting create unique exposure points. The core issue is the mishandling of control characters in data that crosses trust boundaries between the database layer and HTTP layer.
CockroachDB-Specific Detection
Detecting CRLF injection in CockroachDB-backed APIs requires testing both the application layer (which queries CockroachDB) and, where accessible, CockroachDB's own HTTP endpoints. The attack surface includes any endpoint that reflects database content or errors in HTTP responses.
Manual Testing Approach:
- Identify parameters that influence SQL queries or are stored and later displayed (e.g., search filters, user profile fields).
- Inject CRLF payloads like
%0d%0aX-Attack: true%0d%0aor%0d%0aSet-Cookie: test=1%0d%0a. - Observe response headers and body for split responses, injected headers, or altered content. Tools like Burp Suite can automate this.
- Test CockroachDB's HTTP API directly if exposed (e.g.,
/api/v1/sql). Send a payload in thesqlparameter that triggers an error containing CRLF:SELECT 1%0d%0aX-Header: injected. Check if the response includes the injected header.
Automated Scanning with middleBrick:
middleBrick's Input Validation and Data Exposure checks are designed to detect CRLF injection. When scanning a URL that proxies to CockroachDB or exposes its HTTP API directly, middleBrick:
- Sends payloads containing CRLF sequences in query parameters, POST bodies, and headers.
- Analyzes the HTTP response for evidence of response splitting (e.g., duplicate headers, malformed status lines) or reflected CRLF in the body.
- Checks if database error messages are leaked and contain unsanitized user input.
For example, scanning a CockroachDB-backed REST API endpoint with middleBrick would test paths like:
middlebrick scan https://api.example.com/users?search=test%0d%0aX-Header:%20injectedThe scanner evaluates the response headers and body. If the response includes X-Header: injected as a separate header, it flags a CRLF vulnerability with high severity. The report will categorize it under Input Validation or Data Exposure, providing the exact request/response evidence and a severity score impact.
Integration into CI/CD: Using middleBrick's GitHub Action, you can automatically scan staging environments where CockroachDB is integrated:
name: API Security Scan
on: [push]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: middlebrick/github-action@v1
with:
url: ${{ secrets.STAGING_API_URL }}
threshold: 'B'This fails the build if a CRLF or other high-risk issue is detected, preventing deployment of vulnerable code that interacts with CockroachDB.
CockroachDB-Specific Remediation
Remediation focuses on sanitizing any data that originates from user input or database queries before it enters HTTP response contexts. CockroachDB itself does not automatically sanitize output; this is the application's responsibility.
1. Use Parameterized Queries (Prevent Injection at Source):
Never concatenate user input into SQL strings. Use prepared statements via CockroachDB's drivers (e.g., pgx for Go, psycopg2 for Python). This prevents attackers from altering query structure to inject CRLF through SQL syntax.
// Go example using pgx (CockroachDB compatible)
import "github.com/jackc/pgx/v4"
func getUserByName(db *pgx.Conn, name string) (string, error) {
var username string
// Parameterized query prevents SQL injection, including CRLF in query
err := db.QueryRow(context.Background(),
"SELECT username FROM users WHERE name = $1", name).Scan(&username)
return username, err
}2. Sanitize Data for HTTP Contexts:
Before setting HTTP headers or writing response bodies, strip or encode CRLF characters (\r, \n) from any data that originated from the database or user input. In Go's standard library:
import "net/http"
func safeHeaderValue(s string) string {
// Remove CR and LF per RFC 7230
return strings.ReplaceAll(strings.ReplaceAll(s, "\r", ""), "\n", "")
}
func handler(w http.ResponseWriter, r *http.Request) {
username := getUserFromDB() // Could contain CRLF if stored maliciously
w.Header().Set("X-User-Name", safeHeaderValue(username))
fmt.Fprintf(w, "Hello, %s", html.EscapeString(username)) // Escape for HTML body
}3. Configure CockroachDB Error Logging:
Ensure detailed SQL error messages are not leaked to clients in production. In CockroachDB, set the sql.statement_diagnostic_request and application-level error handling to return generic messages. In your application code, catch database errors and log them server-side with full details, but send only a sanitized message to the client:
// Python example with psycopg2
import psycopg2
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/user')
def get_user():
try:
# ... execute query ...
pass
except psycopg2.Error as e:
# Log full error internally
app.logger.error(f"DB error: {e}")
# Return generic message to client
return jsonify(error="An internal error occurred"), 5004. Validate and Encode Output in Web UIs:
If CockroachDB data is displayed in a web interface (e.g., admin panel), always HTML-encode before rendering. Use framework-specific escaping (e.g., html/template in Go, jinja2 autoescaping in Python). This prevents stored CRLF from becoming XSS when combined with response splitting.
5. Review pg_catalog Usage:
Audit any use of CockroachDB's pg_catalog functions (e.g., pg_read_file, pg_ls_dir) that read server files. Ensure the results are never directly included in HTTP responses without sanitization. Restrict permissions on these functions to superusers only.
By implementing these layers—parameterized queries, output sanitization, and proper error handling—you can eliminate CRLF injection risks in CockroachDB-integrated applications. middleBrick's scans will confirm remediation by no longer detecting CRLF payloads in responses.
Understanding the Risk: CRLF in API Security
CRLF injection is classified under A05:2021 – Security Misconfiguration and A03:2021 – Injection in the OWASP API Top 10. While often considered a lower-severity issue, in API contexts it can lead to:
- HTTP Response Splitting: Allows cache poisoning, XSS, or session hijacking by injecting arbitrary headers.
- Log Injection: Falsifies application or database logs, hiding attacks or creating false audit trails.
- Web Cache Deception: Splitting responses to poison CDN caches with malicious content.
CockroachDB's role as a distributed SQL database means its error messages and data outputs can contain multi-line strings (e.g., COPY data, stack traces). If an application layer does not treat these as untrusted, CRLF becomes a practical attack vector. The vulnerability is not in CockroachDB itself but in how applications handle its output.
Compliance frameworks like PCI-DSS (requirement 6.5.1) and HIPAA (security rule) mandate input validation to prevent injection. A CRLF flaw could be cited as a failure of these controls. middleBrick maps such findings to these frameworks in its Pro and Enterprise reports.