HIGH hallucination attacksbasic auth

Hallucination Attacks with Basic Auth

How Hallucination Attacks Manifests in Basic Auth

Hallucination attacks in Basic Auth contexts occur when authentication systems incorrectly validate or process credentials due to malformed or manipulated input. These attacks exploit the fact that Basic Auth relies on Base64-encoded strings that can be tampered with to create ambiguous parsing scenarios.

// Vulnerable Basic Auth parsing logic
const parseBasicAuth = (header) => {
  const [type, credentials] = header.split(' ');
  if (type.toLowerCase() !== 'basic') return null;
  
  const decoded = Buffer.from(credentials, 'base64').toString('utf8');
  const [username, password] = decoded.split(':');
  
  // Hallucination attack vectors:
  // 1. Missing colon creates single-element array
  // 2. Multiple colons create extra elements
  // 3. Empty strings create null/undefined values
  
  return { username, password };
};

The Base64 encoding itself is not encryption—it's merely an encoding scheme that can be manipulated. Attackers can craft headers that decode to unexpected values, causing the parser to "hallucinate" valid credentials where none exist.

// Hallucination attack examples
// Case 1: Missing colon - decodes to single username, empty password
// Base64: "dXNlcm5hbWU=" -> "username"
// Result: { username: "username", password: undefined }

// Case 2: Multiple colons - decodes to username with embedded colons
// Base64: "dXNlcm5hbWU6cGFzc3dvcmQ6aW5leHRlbmRlZA==" -> "username:password:extended"
// Result: { username: "username", password: "password:extended" }

// Case 3: Empty username - decodes to leading colon
// Base64: "OjEyMzQ1" -> ":12345"
// Result: { username: "", password: "12345" }

Authentication systems may have different validation rules for each field, creating opportunities for bypass. For example, a system might reject empty usernames but accept empty passwords, allowing attackers to exploit these inconsistencies.

// Authentication logic vulnerable to hallucination
const authenticate = (req) => {
  const authHeader = req.headers['authorization'];
  if (!authHeader) return false;
  
  const credentials = parseBasicAuth(authHeader);
  if (!credentials) return false;
  
  // Vulnerable: doesn't handle empty/undefined values properly
  if (credentials.username === 'admin' && credentials.password === 'admin123') {
    return true;
  }
  
  return false;
};

Another manifestation occurs when Basic Auth is used in conjunction with other authentication mechanisms. The system might incorrectly prioritize Basic Auth credentials over other factors, creating a "hallucination" where the Basic Auth credentials are given undue weight in the authentication decision.

Basic Auth-Specific Detection

Detecting hallucination attacks in Basic Auth requires both static analysis of authentication code and dynamic testing of the authentication endpoints. The key is to identify how the system handles edge cases in credential parsing.

// Detection patterns for hallucination vulnerabilities
const detectionPatterns = [
  // Pattern 1: Missing colon handling
  { test: (auth) => auth.includes('Basic ') && !auth.includes(':'), 
    description: 'Missing colon in Base64 payload' },
  
  // Pattern 2: Empty field handling
  { test: (auth) => auth.includes('Basic ') && auth.includes('::'), 
    description: 'Empty username or password' },
  
  // Pattern 3: Multiple colons
  { test: (auth) => auth.includes('Basic ') && (auth.match(/:/g) || []).length > 2, 
    description: 'Multiple colons in credentials' },
  
  // Pattern 4: Non-Base64 characters
  { test: (auth) => auth.includes('Basic ') && /[^A-Za-z0-9+/=]/g.test(auth), 
    description: 'Invalid Base64 characters' }
];

middleBrick's scanning approach for Basic Auth hallucination attacks includes these specific checks:

// middleBrick-style Basic Auth hallucination scan
const scanBasicAuthHallucinations = async (url) => {
  const testVectors = [
    // Missing colon vectors
    'Basic dXNlcm5hbWU=',           // "username"
    'Basic OmFkbWlu',               // ":admin"
    
    // Multiple colon vectors
    'Basic dXNlcm5hbWU6cGFzc3dvcmQ6aW5leHRlbmRlZA==', // "username:password:extended"
    
    // Empty fields
    'Basic OnBhc3N3b3Jk',           // ":password"
    'Basic dXNlcm5hbWU6',           // "username:"
  ];
  
  const results = [];
  
  for (const vector of testVectors) {
    const response = await makeRequest(url, vector);
    results.push({
      vector,
      status: response.status,
      body: response.body,
      success: response.status === 200 || response.status === 401
    });
  }
  
  return results;
};

Static analysis tools can detect vulnerable parsing patterns in source code:

// Vulnerable patterns to detect
const vulnerablePatterns = [
  // Direct Buffer.from without validation
  /Buffer\.from\(.*\s*,\s*['"]base64['"]\)/,
  
  // Split without checking array length
  /split\(['"]:\['"]\)/,
  
  // Destructuring without validation
  /const \[.*\] = .+\.split\(['"]:\['"]\)/,
  
  // Missing validation before authentication
  /if \(credentials\.username ===.*credentials\.password ===/,
];

middleBrick's Basic Auth hallucination detection specifically tests for these edge cases and provides detailed findings about how the authentication system handles malformed credentials, including whether it allows authentication with empty fields or improperly parsed credentials.

Basic Auth-Specific Remediation

Remediating Basic Auth hallucination attacks requires implementing strict validation and normalization of credentials before authentication. The key is to ensure that the parsing logic handles all edge cases predictably.

// Secure Basic Auth parsing implementation
const parseBasicAuthSecure = (header) => {
  if (!header || typeof header !== 'string') {
    return null;
  }
  
  const parts = header.split(' ');
  if (parts.length !== 2 || parts[0].toLowerCase() !== 'basic') {
    return null;
  }
  
  let credentials;
  try {
    credentials = Buffer.from(parts[1], 'base64').toString('utf8');
  } catch (e) {
    // Invalid Base64 encoding
    return null;
  }
  
  // Strict validation: must have exactly one colon
  if (!credentials.includes(':')) {
    return null;
  }
  
  const [username, password] = credentials.split(':', 2);
  
  // Validate field lengths
  if (username.length === 0 || password.length === 0) {
    return null;
  }
  
  // Validate for invalid characters if needed
  if (!/^[a-zA-Z0-9_.-]+$/.test(username)) {
    return null;
  }
  
  return { username, password };
};

The authentication function should include comprehensive validation:

// Secure authentication with hallucination protection
const authenticateSecure = (req) => {
  const authHeader = req.headers['authorization'];
  if (!authHeader) {
    return { success: false, reason: 'missing_header' };
  }
  
  const credentials = parseBasicAuthSecure(authHeader);
  if (!credentials) {
    return { success: false, reason: 'invalid_format' };
  }
  
  // Validate against user store
  const user = userStore.get(credentials.username);
  if (!user || user.password !== credentials.password) {
    return { success: false, reason: 'invalid_credentials' };
  }
  
  // Additional security: check account status, rate limiting, etc.
  if (!user.active) {
    return { success: false, reason: 'account_inactive' };
  }
  
  return { success: true, user: user };
};

For Node.js applications using Express, middleware provides a clean implementation:

// Express middleware for secure Basic Auth
const basicAuthMiddleware = (options = {}) => {
  const { userStore, onError } = options;
  
  return (req, res, next) => {
    const authHeader = req.headers['authorization'];
    
    if (!authHeader) {
      return sendUnauthorized(res, 'Missing Authorization header');
    }
    
    const credentials = parseBasicAuthSecure(authHeader);
    if (!credentials) {
      return sendUnauthorized(res, 'Invalid Basic Auth format');
    }
    
    const user = userStore.get(credentials.username);
    if (!user || user.password !== credentials.password) {
      return sendUnauthorized(res, 'Invalid username or password');
    }
    
    // Attach user to request
    req.user = user;
    next();
  };
};

const sendUnauthorized = (res, message) => {
  res.set('WWW-Authenticate', 'Basic realm="Secure Area"');
  res.status(401).json({ error: message });
};

For applications using JSON Web Tokens (JWT) alongside Basic Auth, ensure proper separation:

// JWT + Basic Auth secure implementation
const secureAuthMiddleware = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  
  if (authHeader && authHeader.startsWith('Basic ')) {
    const credentials = parseBasicAuthSecure(authHeader);
    if (!credentials) {
      return sendUnauthorized(res, 'Invalid Basic Auth');
    }
    
    const user = userStore.get(credentials.username);
    if (!user || user.password !== credentials.password) {
      return sendUnauthorized(res, 'Invalid credentials');
    }
    
    req.user = user;
    next();
  } else if (authHeader && authHeader.startsWith('Bearer ')) {
    const token = authHeader.substring(7);
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = decoded;
      next();
    } catch (err) {
      return sendUnauthorized(res, 'Invalid token');
    }
  } else {
    return sendUnauthorized(res, 'Missing Authorization header');
  }
};

middleBrick's remediation guidance for Basic Auth hallucination attacks includes these specific code patterns and emphasizes the importance of strict input validation before credential processing.

Related CWEs: llmSecurity

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

Frequently Asked Questions

What makes Basic Auth particularly vulnerable to hallucination attacks?
Basic Auth's reliance on Base64 encoding without inherent validation creates multiple attack vectors. The encoding can represent any string, including malformed credentials with missing colons, extra colons, or empty fields. Since Base64 is just encoding—not encryption—attackers can manipulate the encoded strings to create ambiguous parsing scenarios that confuse authentication logic.
How does middleBrick detect Basic Auth hallucination vulnerabilities?