Path Traversal with Mutual Tls
How Path Traversal Manifests in Mutual Tls
Path traversal vulnerabilities in Mutual Tls environments exploit the trust established between client and server certificates to access files outside intended directories. Unlike basic HTTP path traversal, Mutual Tls adds complexity through certificate-based authentication and encrypted channels.
In Mutual Tls implementations, path traversal often occurs when certificate validation logic intersects with file path construction. Consider a service that uses the client's Common Name (CN) from the certificate to construct file paths:
const cert = tlsSocket.getPeerCertificate();
const clientName = cert.subject.CN;
const filePath = `/secure/data/${clientName}/config.json`;
An attacker with a crafted certificate containing CN=../admin could traverse to /secure/data/../admin/config.json, accessing unauthorized directories. The Mutual Tls handshake itself doesn't prevent path manipulation—it only authenticates the certificate holder.
Another pattern emerges in Mutual Tls API endpoints that use certificate attributes for dynamic file loading:
app.get('/api/config/:filename', (req, res) => {
const cert = req.socket.getPeerCertificate();
const orgId = cert.subject.O;
const filePath = path.join('/configs', orgId, req.params.filename);
// Vulnerable: no path normalization
fs.readFile(filePath, (err, data) => {
if (err) return res.status(500).send('Error');
res.json(JSON.parse(data));
});
});
Here, an attacker with a certificate containing CN=evil and requesting filename=../../../../../etc/passwd could read system files. The Mutual Tls authentication ensures the requestor is a valid certificate holder, but doesn't validate the file path logic.
Mutual Tls also introduces path traversal risks in certificate revocation checking. Some implementations construct file paths based on certificate serial numbers:
const serial = cert.serialNumber;
const crlPath = `/crl/${serial}.crl`;
If serial numbers contain path traversal sequences (like 123/../), attackers could manipulate CRL file locations.
Mutual Tls-Specific Detection
Detecting path traversal in Mutual Tls requires examining both certificate validation and file path construction. Start by analyzing certificate attribute usage patterns:
const fs = require('fs');
const path = require('path');
function analyzePathTraversalRisk(cert) {
const riskyAttrs = ['CN', 'O', 'OU', 'serialNumber'];
let riskScore = 0;
riskyAttrs.forEach(attr => {
if (cert.subject[attr]) {
const value = cert.subject[attr];
// Check for traversal patterns
if (value.includes('..') || value.includes('/') || value.includes('\')) {
riskScore += 5;
}
// Check for null bytes (Windows-specific)
if (value.includes(' ')) {
riskScore += 10;
}
}
});
return riskScore;
}
Runtime detection should normalize and validate all constructed paths:
function securePathJoin(base, ...segments) {
const normalized = path.normalize(path.join(base, ...segments));
// Ensure path stays within base directory
if (!normalized.startsWith(base + path.sep)) {
throw new Error('Path traversal detected');
}
return normalized;
}
// Usage in Mutual Tls context
app.get('/secure/:file', (req, res) => {
const cert = req.socket.getPeerCertificate();
const baseDir = `/secure/${cert.subject.CN}`;
try {
const safePath = securePathJoin(baseDir, req.params.file);
const content = fs.readFileSync(safePath, 'utf8');
res.json({ content });
} catch (err) {
res.status(400).json({ error: 'Invalid path' });
}
});
For automated scanning, tools like middleBrick can detect path traversal patterns by analyzing runtime behavior. The scanner tests certificate attribute injection by submitting certificates with crafted CNs containing traversal sequences and monitoring file access responses.
middleBrick's path traversal detection for Mutual Tls specifically examines:
- Certificate attribute extraction and usage in file paths
- Dynamic path construction based on certificate properties
- Response behavior when traversal sequences are injected
- Access control enforcement across certificate-based directories
The scanner attempts path traversal using black-box techniques—submitting requests with crafted certificate attributes and analyzing whether the server exposes files outside intended directories.
Mutual Tls-Specific Remediation
Remediation in Mutual Tls environments requires defense-in-depth combining certificate validation, path sanitization, and strict access controls. Start with certificate attribute validation:
function validateCertificateAttributes(cert) {
const { subject } = cert;
const allowedChars = /^[a-zA-Z0-9_.-]+$/;
// Validate all subject attributes
Object.keys(subject).forEach(attr => {
if (!allowedChars.test(subject[attr])) {
throw new Error(`Invalid characters in ${attr}: ${subject[attr]}`);
}
// Block traversal patterns
if (subject[attr].includes('..')) {
throw new Error('Traversal sequence detected in certificate');
}
});
return true;
}
// Apply validation during TLS handshake
const tlsOptions = {
requestCert: true,
rejectUnauthorized: true,
checkServerIdentity: (host, cert) => {
validateCertificateAttributes(cert);
return undefined; // No error
}
};
Implement strict path construction with normalization and base directory enforcement:
const crypto = require('crypto');
// Map certificate to safe directory ID
function getSafeDirectory(cert) {
// Use hash instead of raw attributes
const hash = crypto.createHash('sha256');
hash.update(JSON.stringify(cert.subject));
return hash.digest('hex').substring(0, 12);
}
function secureReadFile(cert, filename) {
const baseDir = `/secure/data/${getSafeDirectory(cert)}`;
const safePath = path.normalize(path.join(baseDir, filename));
// Verify path is within base directory
if (safePath.indexOf(baseDir) !== 0) {
throw new Error('Path traversal attempt detected');
}
return fs.readFileSync(safePath, 'utf8');
}
// Usage
app.get('/api/data/:file', (req, res) => {
try {
const content = secureReadFile(req.socket.getPeerCertificate(), req.params.file);
res.json({ content });
} catch (err) {
res.status(403).json({ error: 'Access denied' });
}
});
Implement comprehensive logging and monitoring for path traversal attempts:
const fs = require('fs');
const path = require('path');
const winston = require('winston');
const logger = winston.createLogger({
transports: [new winston.transports.File({ filename: 'security.log' })]
});
function monitoredSecureRead(cert, filename) {
const baseDir = `/secure/${cert.subject.CN}`;
const fullPath = path.join(baseDir, filename);
// Log suspicious patterns before access
if (filename.includes('..') || filename.includes('~')) {
logger.warn({
type: 'path_traversal_attempt',
certificate: cert.serialNumber,
attempted_path: fullPath,
timestamp: new Date().toISOString()
});
throw new Error('Suspicious path');
}
return fs.readFileSync(fullPath, 'utf8');
}
For enterprise deployments, integrate middleBrick's continuous monitoring to scan Mutual Tls endpoints regularly. The Pro plan's scheduled scanning can detect path traversal regressions introduced during deployments.
Related CWEs: inputValidation
| CWE ID | Name | Severity |
|---|---|---|
| CWE-20 | Improper Input Validation | HIGH |
| CWE-22 | Path Traversal | HIGH |
| CWE-74 | Injection | CRITICAL |
| CWE-77 | Command Injection | CRITICAL |
| CWE-78 | OS Command Injection | CRITICAL |
| CWE-79 | Cross-site Scripting (XSS) | HIGH |
| CWE-89 | SQL Injection | CRITICAL |
| CWE-90 | LDAP Injection | HIGH |
| CWE-91 | XML Injection | HIGH |
| CWE-94 | Code Injection | CRITICAL |
Frequently Asked Questions
How does path traversal in Mutual Tls differ from regular HTTP path traversal?
Mutual Tls path traversal exploits the trust established by certificate authentication. While regular HTTP traversal only needs to manipulate URL paths, Mutual Tls traversal combines certificate attribute injection with path manipulation. The attacker must first obtain a valid certificate, then craft certificate attributes (like CN or O) containing traversal sequences. This adds a layer of complexity but also a false sense of security—developers often assume certificate authentication prevents file access attacks, when it actually only authenticates the certificate holder.
Can middleBrick detect path traversal in Mutual Tls APIs?
Yes, middleBrick's black-box scanning methodology specifically tests for path traversal in Mutual Tls environments. The scanner submits requests with crafted certificate attributes containing traversal sequences and analyzes the server's response behavior. It examines whether the API exposes files outside intended directories, attempts to access sensitive system files, and checks if path normalization is properly implemented. The scanner provides severity ratings and specific remediation guidance for detected path traversal vulnerabilities, helping teams prioritize fixes based on exploitability and impact.