HIGH prompt injectionbasic auth

Prompt Injection with Basic Auth

How Prompt Injection Manifests in Basic Auth

Prompt injection in Basic Auth contexts typically occurs when authentication prompts are dynamically generated or when user-controlled data flows into authentication mechanisms. Unlike traditional prompt injection in LLM contexts, Basic Auth prompt injection exploits the interaction between client-side authentication flows and server-side validation.

The most common manifestation involves credential stuffing attacks where malicious actors craft prompts that manipulate authentication libraries into accepting forged credentials. For example, when Basic Auth is implemented with client-side JavaScript that dynamically constructs authentication headers, an attacker can inject prompts that override the expected credential validation logic.

Consider this vulnerable pattern:

// Vulnerable: Dynamic prompt generation with user input
const username = getUsernameFromInput();
const password = getPasswordFromInput();
const authHeader = 'Basic ' + btoa(username + ':' + password);
fetch('/api/data', { headers: { Authorization: authHeader } });

An attacker could manipulate the input flow to inject prompts that cause the client to construct malformed authentication headers. This becomes particularly dangerous when combined with browser extensions or malicious scripts that intercept authentication prompts.

Another attack vector involves HTTP proxy manipulation. When Basic Auth credentials are stored in browser storage or passed through intermediate proxies, attackers can inject prompts that cause the client to reveal stored credentials or accept proxy authentication challenges that appear legitimate.

Server-side prompt injection can also occur when Basic Auth implementations use dynamic configuration that includes user-controlled parameters. For instance:

# Vulnerable: Dynamic realm construction
realm = request.headers.get('X-Realm', 'Default')  # User-controlled realm
realm = realm.replace('"', '\"')  # Basic sanitization
response.headers['WWW-Authenticate'] = f'Basic realm="{realm}"'

An attacker could manipulate the X-Realm header to inject prompts that cause authentication libraries to behave unexpectedly or reveal information through error messages.

Basic Auth-Specific Detection

Detecting prompt injection in Basic Auth systems requires examining both client-side and server-side authentication flows. The key is identifying where user-controlled data intersects with authentication logic.

Client-side detection focuses on JavaScript authentication implementations. Tools should scan for patterns where:

  • Authentication headers are constructed from dynamic user input
  • Credential storage mechanisms are accessible to third-party scripts
  • Authentication prompts are generated based on user-controlled parameters
  • Proxy authentication is accepted without strict validation

Server-side detection examines authentication middleware and configuration. Key indicators include:

  • Dynamic realm construction from request headers
  • Authentication logic that processes user-controlled parameters
  • Basic Auth implementations that don't validate credential format strictly
  • Authentication endpoints that reveal information through timing or error responses

middleBrick's scanner specifically tests for Basic Auth prompt injection by:

  • Submitting malformed authentication headers with injection payloads
  • Testing dynamic realm construction with crafted input
  • Examining client-side JavaScript for vulnerable authentication patterns
  • Checking for information disclosure through authentication failures

The scanner evaluates 12 security checks including Authentication, Input Validation, and Data Exposure specifically for Basic Auth implementations. It tests whether authentication prompts can be manipulated to bypass security controls or reveal sensitive information.

Network-level detection includes monitoring for:

  • Unexpected proxy authentication challenges
  • Malformed Basic Auth headers that could indicate injection attempts
  • Authentication failures that reveal implementation details

Basic Auth-Specific Remediation

Remediating prompt injection in Basic Auth systems requires both architectural changes and specific code fixes. The primary defense is eliminating dynamic authentication prompt generation.

Client-side remediation should focus on secure credential handling:

// Secure: Static authentication with server-side validation
const authHeader = 'Basic ' + btoa(`${process.env.API_USER}:${process.env.API_PASS}`);
fetch('/api/data', { headers: { Authorization: authHeader } });

Key principles:

  • Avoid client-side credential construction from user input
  • Use server-side authentication whenever possible
  • Store credentials securely using environment variables or secret management
  • Implement strict Content Security Policy to prevent script injection

Server-side remediation focuses on authentication middleware hardening:

# Secure: Static realm with strict validation
class BasicAuthMiddleware:
    REALM = 'Secure API'
    
    def authenticate(self, request):
        auth_header = request.headers.get('Authorization', '')
        if not auth_header.startswith('Basic '):
            return False
        
        try:
            credentials = base64.b64decode(auth_header[6:]).decode('utf-8')
            username, password = credentials.split(':', 1)
        except (ValueError, UnicodeDecodeError):
            return False
        
        # Strict validation against stored credentials
        return self.validate_credentials(username, password)

Additional remediation strategies:

  • Implement rate limiting on authentication endpoints
  • Use HTTP Strict Transport Security (HSTS) to prevent credential interception
  • Log and monitor authentication failures for injection patterns
  • Consider migrating to token-based authentication for API endpoints

For applications that must use Basic Auth, implement these security controls:

// Secure: Enhanced Basic Auth with additional protections
const authenticate = async (url, username, password) => {
    const controller = new AbortController();
    setTimeout(() => controller.abort(), 5000); // Timeout for slow responses
    
    const response = await fetch(url, {
        headers: { Authorization: 'Basic ' + btoa(`${username}:${password}`) },
        signal: controller.signal,
        credentials: 'omit' // Prevent credential leakage
    });
    
    if (!response.ok) {
        throw new Error('Authentication failed');
    }
    
    return response.json();
};

Related CWEs: llmSecurity

CWE IDNameSeverity
CWE-754Improper Check for Unusual or Exceptional Conditions MEDIUM

Frequently Asked Questions

How does prompt injection differ in Basic Auth versus API token authentication?
Basic Auth prompt injection exploits credential construction and dynamic authentication flows, while API token injection typically targets token generation, validation, and transmission. Basic Auth is more vulnerable to client-side injection because credentials are constructed and transmitted with each request, whereas API tokens can be validated server-side without exposing credential construction logic.
Can middleBrick detect Basic Auth prompt injection vulnerabilities?
Yes, middleBrick's scanner tests for Basic Auth prompt injection by submitting crafted authentication headers, testing dynamic realm construction, and examining client-side JavaScript for vulnerable authentication patterns. The scanner evaluates 12 security checks including Authentication and Input Validation specifically for Basic Auth implementations.