DEV Community

Query Filter
Query Filter

Posted on

gradle-83

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 3338: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 3345 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;
}
Step 4: Test and VerifyClick the blue Test my code button in the top right header.The platform will recompile AvatarServlet.java and execute security checks. Both Working and Secure indicators should turn green to complete the lab.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)