Common Path Traversal in Stock Trading Apps: Causes and Fixes
Path traversal, also known as directory traversal, occurs when an application improperly validates user‑supplied file paths. In a stock trading app the risk surface includes:
What causes path traversal in stock trading apps (technical root causes)
Path traversal, also known as directory traversal, occurs when an application improperly validates user‑supplied file paths. In a stock trading app the risk surface includes:
- File download endpoints – users may request market data files, historical price CSVs, or PDF statements via a URL parameter like
?file=earnings_2023.pdf. If the app concatenates the parameter directly to a base directory without sanitisation, an attacker can prefix../to escape the intended folder. - Avatar or document upload – many trading platforms allow users to upload profile pictures or KYC documents. The upload handler often stores files under
uploads/{userId}/. A missing check onuserIdor a manipulatedfilenamecan lead to writes outside the sandbox. - Configuration or API key storage – some apps fetch configuration from the device’s file system (e.g.,
config.json). A vulnerableloadConfig(String path)method may read../../etc/passwdwhen supplied with a maliciouspathquery parameter. - Log file access – debug endpoints expose logs for support teams. If the log retrieval uses
FileReader(filePath + request.getParameter("log"))and the parameter is not normalized, an attacker can read sensitive logs containing API keys or session tokens. - Cached market data – offline caching stores JSON or binary snapshots in a predictable location (
cache/market/{symbol}.cache). A malicious request forcache/market/../app/build.gradlecan leak source code or build scripts.
All of these scenarios stem from the same root cause: trusting user input to construct a filesystem path without validation, canonicalisation, or permission checks.
Real-world impact (user complaints, store ratings, revenue loss)
When path traversal is exploitable, the fallout is immediate and measurable:
- User data breach – leaked personal IDs, bank details, or API keys trigger panic. Affected users flood support channels and leave negative reviews, dropping the app’s store rating by 1–2 stars within days.
- Regulatory penalties – financial apps are subject to strict data‑protection laws (GDPR, CCPA). A disclosed leak can result in fines up to millions of dollars.
- Revenue erosion – disrupted trading functionality (e.g., inability to fetch price data) leads to lost commissions. A single outage can cost a broker $50k–$200k per hour during peak market hours.
- Brand damage – media coverage of “security hole in trading app” harms investor confidence, prompting a exodus of high‑net‑worth users.
- Increased operational cost – incident response, forensic analysis, and emergency patches consume engineering resources that could otherwise be spent on feature development.
5‑7 specific examples of how path traversal manifests in stock trading apps
1. Statement PDF Download
A user requests a monthly statement via GET /statements?file=statement_2023.pdf. The backend does new File(baseDir, request.getParameter("file")). An attacker can request /statements?file=../../../etc/passwd and read system files.
2. Avatar Upload Bypass
The avatar upload endpoint accepts multipart/form-data with a filename field. The code saves to uploads/{userId}/avatar.jpg. If the attacker sets userId to ../admin via a manipulated session token, the file lands outside the user‑specific directory.
3. Market Data Cache Poisoning
The app caches price snapshots in cache/market/{symbol}.json. A malicious request to GET /cache?symbol=..%2F..%2Fapp%2Fconfig.json can overwrite the configuration file, allowing an attacker to inject false price feeds.
4. Debug Log Exposure
A hidden debug endpoint /debug/logs?file=error.log reads logs from logs/. By supplying file=../../secrets/api_keys.txt, an attacker extracts encrypted API keys used for exchange connectivity.
5. KYC Document Retrieval
After uploading a scanned ID, the app serves the file via /kyc/{userId}/{docName}. If docName is URL‑decoded after being concatenated, ..%2F bypasses the directory restriction and returns another user’s document.
6. Historical Data Export
The export feature builds a ZIP archive containing historical trades. It uses ZipOutputStream with entries built from user‑provided period parameter. An attacker can embed paths like ../../../tmp/evil.sh inside the ZIP, leading to arbitrary file write on the device.
7. Third‑Party SDK Configuration
A third‑party payment SDK reads its configuration from data/data/com.trading.app/files/sdk_config.xml. The trading app passes user‑controlled configId to the SDK without validation, allowing traversal to overwrite the SDK’s certificate store.
How to detect path traversal (tools, techniques, what to look for)
- Static Application Security Testing (SAST) – Scan the Java/Kotlin and JavaScript codebases for
File,Path,openFileInput,getExternalStoragePublicDirectory, andnew File(...)patterns where user input is concatenated directly. Tools such as SonarQube, Checkmarx, or Fortify can flag these patterns. - Dynamic Application Security Testing (DAST) – Use Burp Suite, OWASP ZAP, or SUSA’s autonomous crawler. Feed malicious payloads (
../,..%2F,..\\) into file‑related parameters and observe whether the server returns files outside the intended directory. - Fuzzing – Run a fuzzer like AFL++ or libFuzzer on the file‑handling methods. SUSA can automatically generate regression scripts that replay a series of traversal attempts across multiple app versions.
- Manual penetration testing – Leverage the adversarial persona in SUSA to simulate an attacker trying to read
/etc/passwd, overwrite configuration files, or steal API keys. The tool’s cross‑session learning retains successful payloads for future runs. - Log analysis – Enable detailed logging on the server side and search for
FileNotFoundExceptionorSecurityExceptionwith paths containing../. SUSA’s coverage analytics can highlight “untested” endpoints that are likely to be vulnerable.
How to fix each example (code-level guidance where applicable)
1. Statement PDF Download
String requested = request.getParameter("file");
Path base = Paths.get(STMT_DIR).toAbsolutePath();
Path target = base.resolve(requested).normalize();
if (!target.startsWith(base)) {
throw new SecurityException("Invalid file request");
}
Files.copy(target, response.getOutputStream());
Use Path.resolve and normalize. Ensure the resolved path starts with the base directory.
2. Avatar Upload Bypass
String userId = session.getUserId(); // server‑side only
Path uploadDir = Paths.get(UPLOAD_ROOT, userId).toAbsolutePath();
String filename = Paths.get(originalFilename).getFileName().toString(); // strip directory
Path target = uploadDir.resolve(filename).normalize();
if (!target.startsWith(uploadDir)) {
rejectUpload();
}
Files.copy(inputStream, target);
Never trust the filename; extract only the basename.
3. Market Data Cache Poisoning
String symbol = request.getParameter("symbol");
if (!symbol.matches("[A-Z0-9_-]+")) {
rejectRequest();
}
Path cacheDir = Paths.get(CACHE_DIR).toAbsolutePath();
Path target = cacheDir.resolve(symbol + ".json").normalize();
if (!target.startsWith(cacheDir)) {
rejectRequest();
}
Apply strict whitelist validation on symbols.
4. Debug Log Exposure
Remove debug endpoints from production builds. If required, enforce role‑based access control and validate the file parameter against a allow‑list of known log files:
List<String> allowed = List.of("error.log","access.log");
if (!allowed.contains(request.getParameter("file"))) {
throw new IllegalArgumentException("Log file not allowed");
}
5. KYC Document Retrieval
Use a mapping table that stores the relationship between user IDs and document IDs in a database. Serve files via a random UUID name stored server‑side; never expose the original filename:
String docId = request.getParameter("docId");
String storedPath = docStore.getPath(userId, docId); // internal mapping
Path target = Paths.get(storedPath).toAbsolutePath();
Test Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free