Crlf Injection in Cassandra
How Crlf Injection Manifests in Cassandra
CRLF injection in Cassandra environments typically occurs when user-controlled input is incorporated into CQL (Cassandra Query Language) statements or HTTP headers without proper sanitization. Unlike traditional web applications where CRLF injection often targets HTTP headers, Cassandra-specific implementations face unique risks due to how CQL handles newline characters.
In Cassandra, CRLF injection can manifest through multiple attack vectors. One common scenario involves dynamically constructed CQL queries where user input containing newline characters breaks the intended query structure. For example, consider a Java application using the DataStax driver:
String username = request.getParameter("username");
String query = "SELECT * FROM users WHERE username = '" + username + "' ALLOW FILTERING";
cqlSession.execute(query);If an attacker supplies a username like admin' ALLOW FILTERING
DELETE FROM users;, the resulting CQL statement becomes:
SELECT * FROM users WHERE username = 'admin' ALLOW FILTERING
DELETE FROM users;This creates two separate CQL statements, where the second one executes maliciously. Cassandra's CQL parser interprets the newline character as a statement terminator, enabling command injection.
Another Cassandra-specific manifestation occurs in batch operations. When constructing batch CQL statements with user input, CRLF characters can break out of the intended batch context:
String userId = request.getParameter("user_id");
String batchQuery = "BEGIN BATCH
INSERT INTO audit_log (user_id, action) VALUES ('" + userId + "', 'login');
APPLY BATCH";
cqlSession.execute(batchQuery);An attacker supplying 123456789', 'login');
DELETE FROM audit_log WHERE user_id = '123456789 would create:
BEGIN BATCH
INSERT INTO audit_log (user_id, action) VALUES ('123456789', 'login');
DELETE FROM audit_log WHERE user_id = '123456789
APPLY BATCHThe newline breaks the INSERT statement, allowing the DELETE to execute within the same batch context.
HTTP-based interfaces to Cassandra also face CRLF injection risks. When Cassandra's native protocol or Thrift interfaces are proxied through web services, attackers can exploit newline characters in headers or request bodies to manipulate protocol framing or inject additional requests.
Cassandra-Specific Detection
Detecting CRLF injection in Cassandra environments requires both static analysis and runtime scanning. For static analysis, code review should focus on CQL query construction patterns, particularly where string concatenation is used with user input.
Dynamic analysis tools like middleBrick can automatically scan Cassandra endpoints for CRLF injection vulnerabilities. The scanner tests for newline character injection by submitting payloads containing %0A (URL-encoded newline) and %0D (URL-encoded carriage return) in various API parameters. For Cassandra-specific endpoints, middleBrick checks:
- Whether newline characters in query parameters affect CQL execution
- If batch statements can be broken using CRLF injection
- Whether HTTP headers to Cassandra proxy services can be manipulated
- If authentication tokens or session data can be hijacked through header injection
middleBrick's LLM security module also detects if your Cassandra environment includes AI/ML components that might be vulnerable to prompt injection via newline characters in system prompts or training data.
For runtime detection, monitor your Cassandra logs for unusual query patterns. Look for:
- Multiple statements in what should be single queries
- Unexpected table access patterns
- Batch operations containing suspicious elements
Enable Cassandra's query audit logging to capture the exact CQL being executed, making it easier to spot injection attempts. The DataStax driver provides query tracing that can reveal when queries contain unexpected newline characters.
Automated testing should include fuzzing with various newline representations: \n, \r, \r\n, URL-encoded versions, and Unicode variants. Test both the application layer and any direct Cassandra connections.
Cassandra-Specific Remediation
Remediating CRLF injection in Cassandra requires a defense-in-depth approach. The most effective strategy is eliminating dynamic CQL construction entirely by using prepared statements:
// Vulnerable code
String username = request.getParameter("username");
String query = "SELECT * FROM users WHERE username = '" + username + "' ALLOW FILTERING";
cqlSession.execute(query);
// Secure code using prepared statements
String username = request.getParameter("username");
PreparedStatement stmt = cqlSession.prepare("SELECT * FROM users WHERE username = ? ALLOW FILTERING");
BoundStatement boundStmt = stmt.bind(username);
cqlSession.execute(boundStmt);Prepared statements automatically escape special characters, including newlines, preventing CRLF injection. They also provide performance benefits through query plan caching.
For scenarios where prepared statements aren't feasible, implement strict input validation. For Cassandra specifically, validate that user input doesn't contain newline characters before using it in CQL:
public static String sanitizeForCQL(String input) {
if (input == null) {
return null;
}
// Remove all newline and carriage return characters
return input.replaceAll("[
]", "");
}
// Usage
String username = sanitizeForCQL(request.getParameter("username"));
String query = "SELECT * FROM users WHERE username = '" + username + "' ALLOW FILTERING";
cqlSession.execute(query);For batch operations, validate the entire batch structure before execution:
public static boolean isValidBatch(String batchQuery) {
// Check for unexpected newlines in critical positions
String[] lines = batchQuery.split("\r?\n");
for (String line : lines) {
if (line.trim().toUpperCase().startsWith("DELETE") ||
line.trim().toUpperCase().startsWith("DROP") ||
line.trim().toUpperCase().startsWith("TRUNCATE")) {
return false; // Suspicious operation found
}
}
return true;
}
// Usage
String batchQuery = constructBatchQuery();
if (isValidBatch(batchQuery)) {
cqlSession.execute(batchQuery);
} else {
throw new SecurityException("Invalid batch query detected");
}When using HTTP interfaces to Cassandra, implement strict header validation. Reject any headers containing newline characters and use a whitelist approach for allowed headers. For JSON payloads, validate that no field contains newline characters when they shouldn't.
Consider implementing a Cassandra-specific Web Application Firewall (WAF) that inspects CQL queries for suspicious patterns, including multiple statements separated by newlines. The DataStax Enterprise (DSE) Advanced Security option includes query inspection capabilities that can help detect injection attempts.
For applications using Thrift or older protocols, upgrade to the native protocol with prepared statements. The native protocol includes additional security features and better handling of special characters.