Cors Wildcard in Hapi
How Cors Wildcard Manifests in Hapi
Cors Wildcard vulnerabilities in Hapi applications occur when developers inadvertently allow any origin to access their API resources. In Hapi, this typically manifests through misconfigured CORS settings that use wildcard origins or overly permissive access controls.
The most common scenario involves setting the origin property to * in your CORS configuration:
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register(require('@hapi/cors'));
server.route({
method: 'GET',
path: '/api/data',
handler: (request, h) => {
return { message: 'Sensitive data' };
}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
init();
The critical issue occurs when developers add CORS without proper origin restrictions:
server.register(require('@hapi/cors'), {
cors: {
origin: ['*'], // WILDCARD VULNERABILITY
credentials: true
}
});
This configuration allows any website to make cross-origin requests to your Hapi API, potentially exposing sensitive data. The vulnerability becomes more severe when combined with authentication cookies or tokens stored in the browser.
Another Hapi-specific manifestation occurs when using dynamic origin validation with insufficient checks:
const validateOrigin = (origin, callback) => {
// INSECURE: accepts any origin without validation
callback(null, true);
};
server.register(require('@hapi/cors'), {
cors: {
origin: validateOrigin
}
});
Hapi's flexibility with route-level CORS configuration can also introduce vulnerabilities:
server.route({
method: 'GET',
path: '/api/admin',
config: {
cors: {
origin: ['*'], // Admin endpoint exposed to all origins
credentials: false
}
},
handler: (request, h) => {
return { adminData: 'Confidential information' };
}
});
Attackers exploit these configurations by hosting malicious websites that make requests to your API, stealing data through client-side JavaScript, or performing actions on behalf of authenticated users without their knowledge.
Hapi-Specific Detection
Detecting CORS Wildcard vulnerabilities in Hapi applications requires examining both configuration files and runtime behavior. The first step is reviewing your server setup code for wildcard origins.
Using middleBrick's API security scanner, you can identify CORS misconfigurations in seconds. Simply run:
middlebrick scan https://your-hapi-api.com
# Or integrate into your CI/CD pipeline:
# middlebrick scan --ci --fail-below B
middleBrick specifically tests for CORS vulnerabilities by attempting cross-origin requests and analyzing the Access-Control-Allow-Origin headers returned by your Hapi server. The scanner identifies when your API responds with wildcard origins or overly permissive CORS policies.
For manual detection in Hapi applications, examine your server initialization code:
grep -r "origin.*\*" . --include="*.js" --include="*.ts"
grep -r "@hapi/cors" . --include="*.js" --include="*.ts"
Look for patterns like:
// VULNERABLE PATTERNS
origin: ['*']
origin: "*"
origin: true
origin: validateOrigin // if validation is insufficient
Check your route configurations for per-route CORS settings that might override secure defaults:
grep -r "config.*cors" . --include="*.js" --include="*.ts"
middleBrick's scanning goes beyond simple pattern matching by actively testing CORS endpoints. The scanner sends requests from different origins and analyzes the CORS headers returned, identifying when your Hapi application accepts requests from unauthorized domains.
For comprehensive security assessment, middleBrick also checks related vulnerabilities that often accompany CORS issues:
- Authentication bypass through cross-origin requests
- Information disclosure via exposed API endpoints
- CSRF vulnerabilities in CORS-enabled endpoints
- Missing CORS preflight handling
The scanner provides a security score (A-F) with specific findings about CORS configuration, helping you prioritize remediation efforts based on severity and potential impact.
Hapi-Specific Remediation
Remediating CORS Wildcard vulnerabilities in Hapi requires implementing proper origin validation and restricting cross-origin access to only trusted domains. The most secure approach is to explicitly define allowed origins.
First, identify your legitimate origins. For a typical application, this might include:
const allowedOrigins = [
'https://yourapp.com',
'https://app.yourapp.com',
'https://admin.yourapp.com'
];
Then implement secure CORS configuration in Hapi:
const Hapi = require('@hapi/hapi');
const server = Hapi.server({ port: 3000 });
await server.register(require('@hapi/cors'));
server.ext('onRequest', (request, h) => {
const origin = request.headers.origin;
if (origin && allowedOrigins.includes(origin)) {
return h.continue;
}
// Block requests from unknown origins
return h.response('CORS policy violation').code(403).takeover();
});
For production applications, consider using environment variables for allowed origins:
const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || [];
if (!allowedOrigins.length) {
throw new Error('ALLOWED_ORIGINS environment variable must be set');
}
Implement route-level CORS with proper validation:
server.route({
method: 'GET',
path: '/api/data',
options: {
cors: {
origin: allowedOrigins,
credentials: true
}
},
handler: (request, h) => {
return { message: 'Secure data access' };
}
});
For applications requiring more dynamic origin validation, implement a proper validation function:
const validateOrigin = (origin, callback) => {
if (!origin) {
return callback(new Error('Origin header required'), false);
}
const parsedOrigin = new URL(origin);
const isAllowed = allowedOrigins.some(allowed => {
try {
const allowedUrl = new URL(allowed);
return allowedUrl.hostname === parsedOrigin.hostname;
} catch (err) {
return false;
}
});
callback(null, isAllowed);
};
server.register(require('@hapi/cors'), {
cors: {
origin: validateOrigin,
credentials: true
}
});
After implementing these fixes, verify your remediation using middleBrick:
middlebrick scan https://your-hapi-api.com --baseline
This creates a security baseline for your API. Run it again after changes to ensure the CORS Wildcard vulnerability has been resolved and your security score has improved.
Related CWEs: dataExposure
| CWE ID | Name | Severity |
|---|---|---|
| CWE-200 | Exposure of Sensitive Information | HIGH |
| CWE-209 | Error Information Disclosure | MEDIUM |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies | HIGH |
| CWE-215 | Insertion of Sensitive Information Into Debugging Code | MEDIUM |
| CWE-312 | Cleartext Storage of Sensitive Information | HIGH |
| CWE-359 | Exposure of Private Personal Information (PII) | HIGH |
| CWE-522 | Insufficiently Protected Credentials | CRITICAL |
| CWE-532 | Insertion of Sensitive Information into Log File | MEDIUM |
| CWE-538 | Insertion of Sensitive Information into Externally-Accessible File | HIGH |
| CWE-540 | Inclusion of Sensitive Information in Source Code | HIGH |