HIGH sql injection union

Sql Injection Union Attack

How Sql Injection Union Works

SQL Injection Union attacks exploit a fundamental vulnerability in database query construction where user input is concatenated directly into SQL statements without proper sanitization. The Union operator in SQL allows combining results from multiple SELECT statements into a single result set, making it a powerful tool for data extraction.

The attack typically follows this pattern:

  1. Identify vulnerable parameters - Test API endpoints with single quotes, double quotes, or SQL keywords to trigger database errors
  2. Determine table structure - Use ORDER BY clauses to discover the number of columns in the target query
  3. Craft Union payload - Construct a second SELECT statement that returns the same number of columns
  4. Extract data - Use UNION to combine legitimate results with sensitive data from other tables

Here's a classic example of a vulnerable API endpoint:

GET /api/users?id=1

If the backend code looks like this:

const query = `SELECT * FROM users WHERE id = ${req.query.id}`;

An attacker could inject:

GET /api/users?id=1 UNION SELECT username, password, email, 'extra', 'data' FROM users

This returns all user credentials alongside legitimate data, effectively bypassing authentication and extracting sensitive information.

Sql Injection Union Against APIs

API endpoints are particularly vulnerable to SQL Injection Union attacks because they often expose database-driven functionality through URL parameters, headers, or JSON payloads. Unlike traditional web forms, APIs frequently lack the same level of input validation and error handling.

Common API attack vectors include:

  • RESTful resource identifiers - /api/products/{id}, /api/users/{userId}
  • Query parameters - ?search=, ?filter=, ?sort=
  • JSON request bodies - POST/PUT requests with user-controlled fields
  • HTTP headers - Authorization tokens, custom headers
  • Consider this vulnerable API endpoint:

    POST /api/orders
    Content-Type: application/json
    
    {
      "productId": 123,
      "userId": 456
    }
    

    If the backend processes this without sanitization:

    const query = `SELECT * FROM orders WHERE product_id = ${req.body.productId} AND user_id = ${req.body.userId}`;
    

    An attacker could inject:

    POST /api/orders
    
    {
      "productId": "123 AND 1=1 UNION SELECT id, username, password, email, created_at FROM users",
      "userId": "456"
    }
    

    This technique becomes even more powerful when combined with error-based SQL injection to enumerate database structure, or time-based techniques to bypass blind injection scenarios.

Detection & Prevention

Detecting SQL Injection Union attacks requires both runtime monitoring and static analysis. Look for these indicators:

  • Unexpected SQL keywords in API parameters (UNION, SELECT, FROM, WHERE)
  • Database error messages in API responses
  • Unusual response sizes or data patterns
  • Timing anomalies in database queries

Prevention strategies should be implemented at multiple layers:

Input Validation

// Whitelist approach for numeric IDs
const userId = parseInt(req.query.userId);
if (isNaN(userId) || userId <= 0) {
  return res.status(400).json({ error: 'Invalid user ID' });
}

Parameterized Queries

// Safe approach using prepared statements
const query = 'SELECT * FROM users WHERE id = ?';
connection.execute(query, [req.query.id], (err, results) => {
  // Results are safe
});

WAF and API Security Scanning

Web Application Firewalls can detect and block SQL injection attempts, but they're not foolproof. Automated API security scanning tools like middleBrick can identify SQL injection vulnerabilities by testing endpoints with malicious payloads and analyzing responses for injection indicators.

middleBrick's black-box scanning approach tests APIs without requiring credentials or access to source code. It sends Union-based payloads to API endpoints and evaluates whether the application is vulnerable by analyzing response patterns, error messages, and data leakage.

For production environments, implement comprehensive logging and monitoring to detect SQL injection attempts in real-time. Set up alerts for suspicious patterns like repeated failed authentication attempts, unusual query patterns, or database errors from API endpoints.

Frequently Asked Questions

How can I test my API for SQL Injection Union vulnerabilities?
You can use automated security scanning tools like middleBrick to test your API endpoints. middleBrick's black-box scanning approach sends Union-based payloads to your API endpoints and analyzes responses for injection indicators. Simply provide your API URL and middleBrick will test for SQL injection vulnerabilities along with 11 other security checks in 5-15 seconds. The tool provides a security risk score (A-F) and specific findings with remediation guidance.
What's the difference between SQL Injection Union and other SQL injection techniques?
SQL Injection Union specifically uses the UNION operator to combine results from multiple SELECT statements, allowing attackers to extract data from different tables than the original query intended. Other techniques include error-based injection (extracting data from error messages), blind injection (using conditional logic and timing), and stacked queries (executing multiple statements). Union attacks are particularly effective when you need to extract structured data that matches the original query's column count and data types.