Token Leakage in Cockroachdb
How Token Leakage Manifests in Cockroachdb
Token leakage in Cockroachdb environments occurs when authentication tokens, API keys, or session identifiers are inadvertently exposed through database queries, error messages, or logging mechanisms. This vulnerability is particularly dangerous in Cockroachdb because of its distributed architecture and how it handles query execution across nodes.
The most common manifestation appears in SQL injection scenarios where Cockroachdb's error messages reveal sensitive information. When an attacker crafts malicious queries, the database may return stack traces or query plans that include authentication tokens embedded in application code. For example, if an application uses prepared statements with hardcoded tokens, a malformed query could expose these values in the error response.
Cockroachdb's distributed nature creates additional attack surfaces. When queries span multiple nodes, intermediate results might be logged on different nodes, potentially exposing tokens in distributed query logs. The database's automatic retry logic can also inadvertently log tokens during transaction retries, creating multiple exposure points.
Another specific pattern involves Cockroachdb's JSON and array handling functions. When applications use functions like jsonb_extract_path or array operations on data containing tokens, malformed queries can cause the database to return partial JSON structures that include sensitive authentication information. This is especially problematic when dealing with API responses stored in JSONB columns.
Connection pooling in Cockroachdb applications often leads to token leakage through connection strings. If connection strings containing tokens are logged during pool initialization or connection failures, these credentials can be exposed in application logs, monitoring systems, or even error tracking services.
The issue becomes more severe when Cockroachdb's built-in observability features are enabled. Query traces and execution plans, while useful for debugging, can inadvertently capture and expose tokens used in application queries. This is particularly problematic in production environments where comprehensive logging is enabled for performance monitoring.
Cockroachdb-Specific Detection
Detecting token leakage in Cockroachdb requires a multi-layered approach that combines database-level monitoring with application-layer scanning. The first step is enabling Cockroachdb's audit logging with specific filters to detect when tokens appear in query results or error messages.
Here's a Cockroachdb-specific detection query that searches for common token patterns in query results:
SELECT node_id, query, error_message, execution_time
FROM crdb_internal.executed_statements
WHERE (error_message LIKE '%Bearer %' OR error_message LIKE '%token%' OR error_message LIKE '%api_key%')
AND execution_time > '2023-01-01'
AND application_name != 'middleBrickScanner';
This query leverages Cockroachdb's crdb_internal.executed_statements table to identify queries that returned error messages containing authentication tokens. The application_name filter excludes the middleBrick scanner itself from the results.
For runtime detection, middleBrick's API security scanner includes specific checks for Cockroachdb environments. The scanner tests for token exposure through SQL injection payloads that target Cockroachdb's specific error message formats and query plan structures. It also checks for token leakage in JSON responses that might be generated by Cockroachdb's JSON functions.
Application-level detection should include monitoring Cockroachdb's slow query logs and distributed execution traces. These logs can reveal when tokens are being inadvertently logged during query execution. Setting up alerts for any log entries containing authentication patterns can help catch token leakage early.
Network-level detection is also important. Monitoring database traffic for patterns that suggest token exfiltration, such as unusual query volumes or queries containing authentication patterns, can help identify active exploitation attempts.
middleBrick's CLI tool provides a dedicated Cockroachdb scan mode that specifically tests for token leakage vulnerabilities. The command middlebrick scan --cockroachdb https://api.example.com runs a series of Cockroachdb-specific tests including SQL injection attempts designed to trigger token exposure in error messages.
Cockroachdb-Specific Remediation
Remediating token leakage in Cockroachdb environments requires both database configuration changes and application-level code improvements. The first priority is implementing proper error handling that never exposes tokens in error messages or logs.
Here's a Cockroachdb-specific remediation pattern for Go applications using the official Cockroachdb driver:
package main
import (
"database/sql"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"context"
)
func safeQuery(ctx context.Context, db *sql.DB, query string, args ...interface{}) ([]map[string]interface{}, error) {
var results []map[string]interface{}
// Use prepared statements to prevent SQL injection
stmt, err := db.PrepareContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("query preparation failed")
}
defer stmt.Close()
// Execute with proper error handling
rows, err := stmt.QueryContext(ctx, args...)
if err != nil {
// Log generic error without exposing details
log.Printf("Query execution failed: %v", err)
return nil, fmt.Errorf("query execution failed")
}
defer rows.Close()
// Process results safely
columns, _ := rows.Columns()
for rows.Next() {
row := make(map[string]interface{})
// Use Cockroachdb's specific row scanning
rowValues := make([]interface{}, len(columns))
rowPointers := make([]interface{}, len(columns))
for i := range rowValues {
rowPointers[i] = &rowValues[i]
}
rows.Scan(rowPointers...)
for i, colName := range columns {
row[colName] = rowValues[i]
}
results = append(results, row)
}
return results, nil
}
This pattern ensures that even if SQL injection occurs, the error handling doesn't expose sensitive information. The use of prepared statements and proper context management prevents token exposure through query plan leakage.
For Cockroachdb's JSON handling, implement strict validation before processing any JSON data that might contain tokens:
func validateJSONInput(input string) (string, error) {
// Check for common token patterns in JSON keys or values
if strings.Contains(input, "Bearer") || strings.Contains(input, "token") || strings.Contains(input, "api_key") {
return "", errors.New("potential token exposure detected in JSON input")
}
// Validate JSON structure
var data interface{}
if err := json.Unmarshal([]byte(input), &data); err != nil {
return "", errors.New("invalid JSON structure")
}
return input, nil
}
Database-level remediation includes configuring Cockroachdb's logging to exclude sensitive information:
ALTER SYSTEM SET trace.log_statement = 'none';
ALTER SYSTEM SET trace.txn = 'off';
ALTER SYSTEM SET server.error_log_enabled = 'false';
-- Create a restricted audit log that excludes sensitive data
CREATE CHANGEFEED FOR TABLE sensitive_data
INTO 'kafka://kafka-broker:9092/sensitive_audit'
CONFIGURED WITH {
conf_key='value',
filter='NOT (message LIKE '%token%' OR message LIKE '%Bearer%')'
};
Application-level remediation should include comprehensive input validation and output encoding. Use Cockroachdb's built-in validation functions where possible:
CREATE FUNCTION validate_token_input(input TEXT) RETURNS BOOLEAN AS $$
BEGIN
-- Check for common token patterns
IF input ~* 'Bearer [A-Za-z0-9\-\._~\+\/]+=*' THEN
RETURN FALSE;
END IF;
IF input ~* 'token [A-Za-z0-9\-\._~\+\/]+=*' THEN
RETURN FALSE;
END IF;
RETURN TRUE;
END;
$$ LANGUAGE plpgsql SECURITY INVOKER;
Finally, implement continuous monitoring using middleBrick's Pro plan features to automatically scan your Cockroachdb-backed APIs for token leakage. The continuous monitoring can alert you when new vulnerabilities are detected, allowing for rapid remediation before exploitation occurs.