HIGH cors wildcardexpress

Cors Wildcard in Express

How Cors Wildcard Manifests in Express

CORS wildcard vulnerabilities in Express applications typically occur when developers use overly permissive CORS configurations, often through the popular cors middleware. The most common manifestation is using the wildcard (*) origin without proper restrictions, which allows any website to make cross-origin requests to your API.

A typical vulnerable Express setup looks like this:

const express = require('express');
const cors = require('cors');

const app = express();

// Vulnerable: allows ANY origin
app.use(cors({
  origin: '*',
  credentials: true // Dangerous combination
}));

app.listen(3000);

This configuration is particularly dangerous because when credentials: true is combined with origin: '*', browsers will reject the request entirely due to CORS security requirements. However, many developers attempt to work around this by implementing custom logic that inadvertently creates security gaps.

Another common Express-specific pattern involves dynamic origin checking that fails to properly validate:

app.use(cors({
  origin: function(origin, callback) {
    // Vulnerable: accepts any origin that passes basic checks
    if (origin && origin.includes('example.com')) {
      callback(null, true);
    } else {
      callback(null, true); // Should reject but doesn't
    }
  },
  credentials: true
}));

In production Express applications, CORS wildcard issues often appear alongside authentication bypasses. Consider this pattern:

app.use(cors()); // Defaults to origin: '*'

app.post('/api/login', (req, res) => {
  // Authentication logic
});

app.get('/api/user/:id', authenticate, (req, res) => {
  // User data endpoint
});

Here, the unauthenticated login endpoint becomes vulnerable to credential phishing attacks. An attacker can host a malicious site that submits login forms to your API, capturing credentials through network inspection or CSRF techniques, since the CORS policy allows any origin to interact with the endpoint.

Express applications frequently expose administrative endpoints that become accessible to any origin due to wildcard CORS:

app.use(cors()); // Wildcard enabled

app.post('/admin/shutdown', adminOnly, (req, res) => {
  // Critical admin function
});

If the adminOnly middleware has flaws or if authentication is bypassed through other means, the wildcard CORS policy means any website can attempt to trigger these administrative actions, potentially causing denial of service or data manipulation.

Express-Specific Detection

Detecting CORS wildcard vulnerabilities in Express requires examining both the configuration code and runtime behavior. Start by auditing your Express application's middleware setup:

# Search for CORS configuration patterns
grep -r "cors(" routes/ middleware/ app.js

Look for these specific patterns that indicate vulnerability:

// Direct wildcard usage
app.use(cors({ origin: '*' }));

// Default wildcard (most dangerous)
app.use(cors());

// Dynamic origin with insufficient validation
app.use(cors({
  origin: function(origin, callback) {
    // Missing proper validation
    callback(null, true);
  }
}));

Runtime detection involves testing actual API responses. Using curl or a browser, check for these indicators:

# Test wildcard CORS response headers
curl -I https://yourapi.com/endpoint

Look for these response headers that indicate CORS wildcard configuration:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization

The middleBrick scanner automatically detects CORS wildcard vulnerabilities by making cross-origin requests from different domains and analyzing the response headers. It specifically tests for:

  • Wildcard origin headers (*)
  • Credentials allowed with wildcard origins
  • Missing or overly permissive CORS configurations
  • Exposed sensitive headers in CORS responses

middleBrick's Express-specific detection includes scanning for common Express middleware patterns and identifying when CORS is applied globally versus to specific routes, which affects the attack surface.

Express-Specific Remediation

Remediating CORS wildcard vulnerabilities in Express requires a defense-in-depth approach. The primary fix is implementing strict origin validation:

const whitelist = ['https://yourapp.com', 'https://yourapp.net'];

app.use(cors({
  origin: function(origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: false // Never use credentials with dynamic origins
}));

For applications that need to support multiple environments, use environment-specific configurations:

const corsOptions = {
  origin: process.env.ALLOWED_ORIGINS ? 
    process.env.ALLOWED_ORIGINS.split(',') : 
    ['https://production.com'],
  credentials: false,
  optionsSuccessStatus: 200
};

app.use(cors(corsOptions));

Apply CORS at the route level rather than globally to limit exposure:

const corsWithOptions = cors({
  origin: ['https://yourapp.com'],
  credentials: false
});

app.get('/api/data', corsWithOptions, (req, res) => {
  res.json({ data: 'protected' });
});

// Public endpoint can have different CORS policy
const corsPublic = cors({
  origin: ['https://partner.com'],
  credentials: false
});

app.post('/api/public', corsPublic, (req, res) => {
  res.json({ status: 'public access' });
});

For Express applications using TypeScript, add type safety to CORS configurations:

import cors, { CorsOptionsDelegate } from 'cors';

const originCheck: CorsOptionsDelegate = (origin, callback) => {
  const whitelist = ['https://app.com', 'https://admin.app.com'];
  
  if (!origin || whitelist.includes(origin)) {
    return callback(null, true);
  }
  
  const err = new Error('CORS policy violation');
  return callback(err, false);
};

app.use(cors({ origin: originCheck, credentials: false }));

Integrate CORS security scanning into your Express development workflow using middleBrick's CLI:

# Scan your Express API before deployment
middlebrick scan https://yourapi.com --output report.json

# Check for CORS-specific vulnerabilities
middlebrick scan https://yourapi.com --category cors

For CI/CD integration with Express applications, add middleBrick to your GitHub Actions workflow:

- name: Run middleBrick CORS Scan
  uses: middlebrick/middlebrick-action@v1
  with:
    target: https://staging-api.yourcompany.com
    fail-threshold: 80
    categories: 'cors'

This ensures CORS wildcard vulnerabilities are caught before deployment to production environments.

Related CWEs: dataExposure

CWE IDNameSeverity
CWE-200Exposure of Sensitive Information HIGH
CWE-209Error Information Disclosure MEDIUM
CWE-213Exposure of Sensitive Information Due to Incompatible Policies HIGH
CWE-215Insertion of Sensitive Information Into Debugging Code MEDIUM
CWE-312Cleartext Storage of Sensitive Information HIGH
CWE-359Exposure of Private Personal Information (PII) HIGH
CWE-522Insufficiently Protected Credentials CRITICAL
CWE-532Insertion of Sensitive Information into Log File MEDIUM
CWE-538Insertion of Sensitive Information into Externally-Accessible File HIGH
CWE-540Inclusion of Sensitive Information in Source Code HIGH

Frequently Asked Questions

Why is CORS wildcard with credentials: true so dangerous in Express?
This combination is fundamentally broken because browsers will reject the request entirely. However, developers often try to work around this by implementing custom logic that creates security gaps. The wildcard allows any origin to discover your API endpoints, and if authentication is bypassed through other means, attackers can interact with authenticated endpoints from malicious websites.
How does middleBrick detect CORS wildcard vulnerabilities in Express applications?