From 2c35a1b7c833920c71633dfb698966edf90569fd Mon Sep 17 00:00:00 2001 From: Mobb autofixer Date: Tue, 27 Aug 2024 16:16:11 +0000 Subject: [PATCH] mobb fix commit: 877f2934-0801-452f-9a32-c4661452cdf5 --- .../pathtraversal/ProfileUploadRetrieval.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/main/java/org/owasp/webgoat/lessons/pathtraversal/ProfileUploadRetrieval.java b/src/main/java/org/owasp/webgoat/lessons/pathtraversal/ProfileUploadRetrieval.java index 402945f122..f294506b76 100644 --- a/src/main/java/org/owasp/webgoat/lessons/pathtraversal/ProfileUploadRetrieval.java +++ b/src/main/java/org/owasp/webgoat/lessons/pathtraversal/ProfileUploadRetrieval.java @@ -88,6 +88,7 @@ public ResponseEntity getProfilePicture(HttpServletRequest request) { } try { var id = request.getParameter("id"); + ensurePathIsRelativeToDest(catPicturesDirectory, (id == null ? RandomUtils.nextInt(1, 11) : id) + ".jpg"); var catPicture = new File(catPicturesDirectory, (id == null ? RandomUtils.nextInt(1, 11) : id) + ".jpg"); @@ -113,4 +114,26 @@ public ResponseEntity getProfilePicture(HttpServletRequest request) { return ResponseEntity.badRequest().build(); } + + private static void ensurePathIsRelativeToDest(File dest, String path) { + File file = new File(dest, path); + String destCanonicalPath; + String fileCanonicalPath; + + try { + destCanonicalPath = dest.getCanonicalPath(); + fileCanonicalPath = file.getCanonicalPath(); + } catch (IOException e) { + throw new RuntimeException("Potential directory traversal attempt", e); + } + + if (!fileCanonicalPath.startsWith(destCanonicalPath + File.separator)) { + throw new RuntimeException("Potential directory traversal attempt"); + } + } + + + private static void ensurePathIsRelativeToDest(String dest, String path) { + ensurePathIsRelativeToDest(new File(dest), path); + } }