HIGH formula injectionbasic auth

Formula Injection with Basic Auth

How Formula Injection Manifests in Basic Auth

Formula Injection occurs when untrusted input is concatenated into a string that is later evaluated as code or a formula by an application or downstream system. In the context of Basic Authentication, the primary risk surface is not the Authorization header itself (which is base64-encoded and not directly evaluatable), but the handling of credentials on the server side. For example, a server might decode the Basic Auth header, split on :, and then construct an LDAP query or a SQL query using the username and password without proper escaping. If an attacker provides a username like admin' OR '1'='1 or ; system("id"), and the application interpolates these values into a query or shell command, the attacker can achieve unauthorized access or command execution.

Specific attack patterns against Basic Auth implementations include:

  • LDAP Injection: Many legacy systems use Basic Auth over LDAP. A username such as *)(uid=admin in the injection crafted to change the scope of the LDAP search, potentially bypassing authentication.
  • SQL Injection via Auth Headers: If the backend decodes Basic Auth and directly uses the credentials in SQL, a password like ' UNION SELECT credit_card FROM users-- can extract sensitive data.
  • Command Injection via Helper Utilities: Scripts that use the username or password to call system utilities (e.g., for validation or provisioning) are vulnerable if input is not sanitized. A password like $(rm -rf /) could be catastrophic if passed to a shell.
  • Header Smuggling via Newline Injection: Although less a formula issue and more a protocol issue, newline characters in credentials (if accepted) can inject additional headers, bypassing authentication logic.

Basic Auth-specific code paths that are prone to formula injection typically appear in legacy or custom authentication modules. For instance, a Node.js route that manually parses the Authorization header might do:

const auth = req.headers.authorization; // 'Basic dXNlcjpwYXNz'
const buffer = Buffer.from(auth.split(' ')[1], 'base64');
const [user, pass] = buffer.toString().split(':');
const query = `SELECT * FROM users WHERE username = '${user}' AND password = '${pass}';`;
// query is then passed to a database driver

In this path, if an attacker sends a password containing a single quote, the SQL string becomes malformed and injectable. Similarly, constructing an LDAP filter by string concatenation is risky:

const ldapFilter = `(&(objectClass=person)(uid=${username})(userPassword=${password}))`;
// If username is 'admin')(|(uid=*)(userPassword=*)(, the filter logic is altered.

These patterns show that formula injection in Basic Auth contexts is rooted in unsafe string assembly rather than the authentication scheme itself. The key is to treat decoded credentials as untrusted input and apply strict validation and parameterized handling.

Basic Auth-Specific Detection

Detecting formula injection in Basic Auth implementations requires both static analysis of the codebase and dynamic testing of the authentication flow. Static analysis should look for patterns where the Authorization header is decoded and used in string interpolation for SQL, LDAP, or shell commands. Dynamic scanning can identify whether crafted inputs alter the intended behavior of the authentication mechanism.

With middleBrick, you can scan an API endpoint to surface these risks without authentication. The scanner will exercise the unauthenticated attack surface and, where relevant, flag endpoints that accept Basic Auth and appear to construct queries using user-controlled data from headers. While middleBrick’s checks are generic at the network level, they can highlight endpoints where injection-like behavior is observable, such as inconsistent responses for special characters or signs of query parsing errors.

To specifically test for formula injection, you can manually or programmatically send crafted Basic Auth credentials and observe outcomes. For example, use a username such as admin'-- and a dummy password, and check whether authentication succeeds unexpectedly or SQL errors are returned. Similarly, send a password containing SQL meta-characters like ' OR 1=1-- and monitor for authentication bypass indicators. Automated tools can help by fuzzing the credential parsing logic with injection payloads and analyzing error messages or response discrepancies.

When using the middleBrick CLI, you might first run a broad scan to identify authentication mechanisms:

middlebrick scan https://api.example.com/endpoint

Review the report for findings related to authentication and input validation. Then, to probe deeper, you can craft manual requests with injected formulas in the credentials to confirm the presence of the vulnerability before applying remediation.

Basic Auth-Specific Remediation

Remediation focuses on avoiding string concatenation when using credentials from Basic Auth. Instead, use parameterized APIs provided by your database, LDAP library, or configuration layer. Below are concrete code examples for common stacks.

Secure SQL with parameterized queries (Node.js with mysql2):

const auth = req.headers.authorization;
const buffer = Buffer.from(auth.split(' ')[1], 'base64');
const [user, pass] = buffer.toString().split(':');

// Use parameterized query to avoid injection
const sql = 'SELECT * FROM users WHERE username = ? AND password = ?';
connection.execute(sql, [user, pass], (err, results) => {
  if (err) { /* handle */ }
  // process results
});

Secure LDAP with parameterized filter (Python using ldap3):

from ldap3 import Server, Connection, ALL
import base64

auth_header = request.headers.get('Authorization')
_, encoded = auth_header.split(' ')
decoded = base64.b64decode(encoded).decode()
username, password = decoded.split(':', 1)

server = Server('ldap.example.com', get_info=ALL)
conn = Connection(server, user=username, password=password)
if not conn.bind():
    # Use safe filter construction; avoid string interpolation
    conn.search('dc=example,dc=com', f'(uid={username})', attributes=['cn'])

Shell command safety (avoid entirely; use libraries):

If you must invoke external utilities, never concatenate credentials. Use language-native libraries instead. If unavoidable, rigorously validate and escape:

import shlex
import subprocess

username = validate_and_sanitize(username)
password = validate_and_sanitize(password)
# Prefer direct API calls over shell
cmd = ['somecommand', '--user', shlex.quote(username), '--password', shlex.quote(password)]
subprocess.run(cmd, check=True)

Additional hardening steps include:

  • Reject usernames or passwords containing special characters that are not strictly necessary (whitelist validation).
  • Ensure error messages are generic to avoid leaking parsing details.
  • Upgrade to token-based or modern authentication where possible to reduce reliance on Basic Auth.

By treating Basic Auth credentials as untrusted input and using safe APIs, you mitigate formula injection risks while preserving the simplicity of the protocol.

Frequently Asked Questions

Can middleBrick detect formula injection in Basic Auth endpoints?
middleBrick scans the unauthenticated attack surface and flags input validation and authentication issues. While it may not specifically label formula injection, its findings on authentication irregularities and input handling can indicate potential injection risks that you should investigate manually.
Is it safe to include credentials in automated scans?
middleBrick’s unauthenticated scans do not require credentials. If you choose to provide credentials to test authenticated flows, ensure they are scoped read-only test accounts and handled in accordance with your security policies.