HIGH prototype pollutioncockroachdb

Prototype Pollution in Cockroachdb

How Prototype Pollution Manifests in Cockroachdb

Prototype pollution in Cockroachdb environments typically occurs when user-controlled data flows through JavaScript-based components that interact with Cockroachdb databases. The vulnerability arises when malicious input modifies JavaScript object prototypes, potentially affecting how data is processed before database operations.

In Cockroachdb contexts, prototype pollution often appears in Node.js applications using the node-cockroachdb driver. Consider this vulnerable pattern:

const { Client } = require('@cockroachdb/cockroachdb').pg;

app.post('/api/users', async (req, res) => {
const userData = req.body;
// Malicious input: { __proto__: { admin: true } }
const query = 'INSERT INTO users (username, email, admin) VALUES ($1, $2, $3)';
await client.query(query, [userData.username, userData.email, userData.admin]);
res.json({ success: true });

The vulnerability here is that userData.admin could be set through prototype pollution rather than user input. An attacker sending { "__proto__": { "admin": true } } would pollute the prototype chain, causing all subsequent objects to have admin: true unless explicitly overridden.

Cockroachdb-specific manifestations include:

  • JSONB column manipulation: When storing JSONB data in Cockroachdb, prototype pollution can alter how JSON objects are constructed before insertion, potentially adding privileged fields
  • ORM layer bypasses: Libraries like sequelize-cockroachdb or prisma-cockroachdb may not properly validate nested properties, allowing prototype pollution to modify query building logic
  • Migration scripts: Cockroachdb migration tools written in JavaScript can be vulnerable if they process user input when constructing schema changes

Another Cockroachdb-specific scenario involves JSON.parse() operations on database query results:

const result = await client.query('SELECT config FROM settings WHERE id = $1', [id]);
const config = JSON.parse(result.rows[0].config);
// If config contains __proto__ pollution, it affects subsequent operations

This is particularly dangerous in Cockroachdb because JSONB columns are commonly used for flexible schema designs, increasing the attack surface for prototype pollution.

Cockroachdb-Specific Detection

Detecting prototype pollution in Cockroachdb applications requires both static analysis and runtime monitoring. middleBrick's scanning capabilities include specific checks for this vulnerability pattern in database-connected applications.

middleBrick's prototype pollution detection for Cockroachdb environments includes:

  • Property traversal analysis: Scanning for unsafe property access patterns like obj[userInput] where userInput could contain __proto__, constructor, or prototype
  • JSONB column inspection: Identifying queries that insert or update JSONB columns with unvalidated user input
  • ORM query building analysis: Detecting where user input flows into query construction without proper sanitization

Runtime detection in Cockroachdb applications should include:

// Prototype pollution detection middleware
const isPrototypePolluted = (obj) => {
const pollutedKeys = ['__proto__', 'constructor', 'prototype'];
const check = (obj) => {
for (const key of pollutedKeys) {
if (key in obj) return true;
}
return false;
};

return check(obj);
};

// Use before database operations
if (isPrototypePolluted(userData)) {
throw new Error('Prototype pollution detected');
}

For Cockroachdb specifically, monitor for:

Detection PatternRisk LevelMonitoring Approach
JSONB inserts with user inputHighQuery logging + input validation
Dynamic column accessMediumStatic code analysis
ORM model populationHighRuntime property checking

middleBrick's API scanning specifically tests for prototype pollution by sending crafted payloads like:

{
"__proto__": {
"admin": true,
"isVerified": true,
"permissions": ["read", "write", "delete"]
}

The scanner then observes whether these properties appear in database responses or affect application behavior, which would indicate a successful prototype pollution attack.

Cockroachdb-Specific Remediation

Remediating prototype pollution in Cockroachdb applications requires a defense-in-depth approach combining input validation, safe object handling, and database-specific safeguards.

Primary remediation strategies:

// 1. Input sanitization before database operations
const sanitizeInput = (obj) => {
const pollutedKeys = ['__proto__', 'constructor', 'prototype'];

const sanitized = Array.isArray(obj) ? [] : {};

for (const [key, value] of Object.entries(obj)) {
if (pollutedKeys.includes(key)) continue;

if (typeof value === 'object' && value !== null) {
sanitized[key] = sanitizeInput(value);
} else {
sanitized[key] = value;
}
}

return sanitized;
};

// 2. Safe object creation for database operations
const safeCreateUser = async (userData) => {
const cleanData = sanitizeInput(userData);

const query = 'INSERT INTO users (username, email, admin) VALUES ($1, $2, $3)';
await client.query(query, [
cleanData.username,
cleanData.email,
cleanData.admin || false // Default to false, don't trust input
]);
};

// 3. Cockroachdb-specific JSONB handling
const safeInsertJSONB = async (table, jsonData) => {
const cleanData = sanitizeInput(jsonData);
const query = `INSERT INTO ${table} (data) VALUES ($1)`;
await client.query(query, [JSON.stringify(cleanData)]);
};

For Cockroachdb applications, implement these database-specific protections:

// Use parameterized queries with explicit field mapping
const createUser = async (userData) => {
const query = 'INSERT INTO users (username, email, admin) VALUES ($1, $2, $3)';
await client.query(query, [
userData.username || 'default',
userData.email || '[email protected]',
false // Never trust user input for boolean flags
]);
};

// Cockroachdb JSONB with schema validation
const validateJSONSchema = (data, schema) => {
const { valid, errors } = validate(data, schema);
if (!valid) {
throw new Error(`JSON validation failed: ${errors}`);
}

return sanitizeInput(data);
};

Additional Cockroachdb-specific recommendations:

  • Column-level permissions: Use Cockroachdb's role-based access control to limit which columns can be modified by different application roles
  • Computed columns: For sensitive fields like admin, use computed columns that default to false rather than accepting user input
  • Check constraints: Add constraints that prevent unexpected values in critical columns

middleBrick's remediation guidance for prototype pollution in Cockroachdb applications includes specific code patterns and configuration examples tailored to the database's query syntax and JSONB handling capabilities.

Frequently Asked Questions

How does prototype pollution in Cockroachdb differ from traditional SQL injection?
Prototype pollution targets JavaScript object manipulation before data reaches the database, while SQL injection attacks the query syntax itself. In Cockroachdb applications, prototype pollution can modify how data is structured or which properties are included in JSONB columns, potentially bypassing application logic that checks for privilege escalation. SQL injection directly manipulates the SQL query sent to Cockroachdb.
Can middleBrick detect prototype pollution in Cockroachdb applications without source code access?
Yes. middleBrick performs black-box scanning by sending crafted payloads containing prototype pollution patterns to your API endpoints. It analyzes responses to detect if the pollution was successful by checking for unexpected properties, privilege escalation indicators, or altered JSON structures in database responses. No source code or credentials are required.