To complete the Immersive Labs Java Path Traversal exercise, follow these step-by-step instructions.Step 1: Walk Through the Demo ExploitSwitch to the Preview tab or click Demo Exploit Vulnerability on the preview/testing UI.Observe how providing a path like ../../../../etc/passwd allows reading files outside the designated avatar directory.Step 2: Understand the Vulnerability in AvatarServlet.javaIn lines 33–38:JavaString basePath = req.getServletContext().getRealPath("avatar");
Path path = Paths.get(basePath, filename);
File file = path.toAbsolutePath().toFile();
Paths.get(basePath, filename) resolves relative path sequences like ../. Without canonicalization checks, an attacker can traverse outside basePath.Step 3: Remediate the VulnerabilityTo fix path traversal, verify that the normalized/canonical target path still starts with the base path prefix before serving the file.Open Code Editor $\rightarrow$ src/main/java/com/immersivelabs/fitness/servlet/AvatarServlet.java.Locate the doGet method around line 33.Replace lines 33–45 with the following secure path validation logic:Java// Get the base path where all avatars live
String basePath = req.getServletContext().getRealPath("avatar");
Path baseDirPath = Paths.get(basePath).toAbsolutePath().normalize();
// Join with the provided filename and normalize path traversal sequences
Path targetPath = Paths.get(basePath, filename).toAbsolutePath().normalize();
// Verify target path remains inside baseDirPath
if (!targetPath.startsWith(baseDirPath)) {
resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
File file = targetPath.toFile();
if (!file.exists() || file.isDirectory()) {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
Top comments (0)