Broken Authentication in Koa with Mutual Tls
Broken Authentication in Koa with Mutual Tls — how this specific combination creates or exposes the vulnerability
Mutual Transport Layer Security (mTLS) requires both the client and the server to present and validate digital certificates. In Koa, enabling mTLS typically involves configuring an HTTPS server with requestCert: true and rejectUnauthorized: true. While mTLS strengthens authentication by binding identity to certificates, Broken Authentication can still occur when implementation details are misaligned with authentication expectations.
One common pattern is using mTLS for transport-layer authentication while neglecting application-layer identity checks. For example, a Koa app might verify that a client certificate is trusted, but then treat the presence of a certificate as sufficient authentication without validating authorization claims (e.g., certificate common name or extended key usage) or binding the certificate to a user or role in the application. This creates a Broken Authentication gap where an attacker who possesses a valid client certificate can authenticate but may exceed intended permissions.
Another vulnerability arises from improper certificate validation. If the server does not enforce a strict certificate chain verification or does not check certificate revocation (e.g., via CRL or OCSP), an attacker could use a compromised or revoked certificate to authenticate. In Koa, this can happen if the server's secure context is configured with weak options, such as omitting ca (Certificate Authority list) or not handling verification errors correctly.
Additionally, session management on top of mTLS can introduce Broken Authentication issues. After mTLS client authentication, some Koa applications establish a session or issue a token but fail to apply appropriate expiration, rotation, or revocation mechanisms. If session identifiers or tokens are predictable, transmitted insecurely, or not invalidated upon logout, an attacker can hijack authenticated sessions even when mTLS is correctly configured.
The interplay of mTLS and application logic also means that developers might mistakenly assume mTLS alone fulfills all authentication and authorization requirements. For example, an endpoint might check that a client certificate exists but skip checking scopes or roles encoded in certificate extensions or mapped to application permissions. This misalignment means the attack surface includes both certificate compromise (e.g., stolen private key) and application-level privilege escalation, aligning with BOLA/IDOR and authentication failures highlighted in OWASP API Top 10.
middleBrick scans such configurations by running authentication checks in parallel with other security tests, validating that mTLS is not treated as a universal gate. It inspects unauthentinated attack surfaces and verifies that authentication mechanisms are consistently enforced across endpoints, reducing the risk of Broken Authentication in Koa services that rely on mTLS.
Mutual Tls-Specific Remediation in Koa — concrete code fixes
To remediate Broken Authentication when using mTLS in Koa, enforce strict certificate validation, bind certificates to application identities, and integrate mTLS checks with your authentication and authorization layers.
Below is a concrete Koa HTTPS server example with robust mTLS configuration:
const fs = require('fs');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
const serverOptions = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
ca: fs.readFileSync('ca-chain.pem'), // Trusted CA bundle
requestCert: true,
rejectUnauthorized: true, // Enforce client certificate validation
checkServerIdentity: (servername, cert) => {
// Optional: enforce hostname or SAN checks
if (cert.subjectaltname && !cert.subjectaltname.includes(servername)) {
return new Error('Certificate hostname mismatch');
}
return undefined;
}
};
const server = https.createServer(serverOptions, app.callback());
// Middleware to extract and validate client certificate
app.use(async (ctx, next) => {
const cert = ctx.req.clientCertificate;
if (!cert) {
ctx.status = 401;
ctx.body = { error: 'Client certificate required' };
return;
}
// Validate certificate fields (example: map CN or SAN to application identity)
const subject = cert.subject;
const commonName = subject.CN;
if (!commonName) {
ctx.status = 403;
ctx.body = { error: 'Certificate missing CN' };
return;
}
// Bind certificate to application user/role (pseudo-lookup)
const user = await lookupUserByCertificate(commonName);
if (!user) {
ctx.status = 403;
ctx.body = { error: 'Certificate not mapped to user' };
return;
}
ctx.state.user = user; // Attach identity to context for downstream handlers
await next();
});
// Example route with authorization check
app.use('/api/admin', async (ctx, next) => {
if (!ctx.state.user || !ctx.state.user.roles.includes('admin')) {
ctx.status = 403;
ctx.body = { error: 'Insufficient scope/role' };
return;
}
await next();
});
server.listen(8443, () => {
console.log('mTLS-enabled Koa server running on port 8443');
});
async function lookupUserByCertificate(cn) {
// Replace with your identity store lookup
const users = {
'alice': { id: 1, roles: ['admin'] },
'bob': { id: 2, roles: ['user'] }
};
return users[cn] || null;
}
This example enforces rejectUnauthorized: true and provides a checkServerIdentity callback for hostname validation. It extracts the client certificate in middleware, verifies its subject CN, and maps it to an application identity with roles, addressing Broken Authentication by ensuring that possessing a certificate is not sufficient—authorization is checked per endpoint.
Additional remediation steps include:
- Maintain and rotate CA and certificate material securely.
- Implement certificate revocation checking (CRL/OCSP) at the TLS layer where supported.
- Avoid logging or exposing certificate private keys or full subject details in production.
- Apply consistent authentication and authorization checks across all routes, rather than relying on mTLS alone.
- Use short-lived certificates and automated renewal to limit the impact of compromised certificates.
middleBrick supports these practices by providing per-category breakdowns and prioritized findings with remediation guidance, helping you verify that mTLS is correctly integrated and that authentication is not broken at the application layer.
Related CWEs: authentication
| CWE ID | Name | Severity |
|---|---|---|
| CWE-287 | Improper Authentication | CRITICAL |
| CWE-306 | Missing Authentication for Critical Function | CRITICAL |
| CWE-307 | Brute Force | HIGH |
| CWE-308 | Single-Factor Authentication | MEDIUM |
| CWE-309 | Use of Password System for Primary Authentication | MEDIUM |
| CWE-347 | Improper Verification of Cryptographic Signature | HIGH |
| CWE-384 | Session Fixation | HIGH |
| CWE-521 | Weak Password Requirements | MEDIUM |
| CWE-613 | Insufficient Session Expiration | MEDIUM |
| CWE-640 | Weak Password Recovery | HIGH |