0

I am doing a REST API in Java (although this question may apply to other languages) where I create several local files and directories, and they can be deleted based on input. I manage my files in a certain directory, then append the request subpath.

So, if user sends a request DELETE /data { path: "user23/mobile" }, then I would delete files under "/opt/my-app/user-data/user23/mobile/". However, It is easy to see that if the input was something like ".." I would start deleting files from other users, or even system files.

Is there a way to securize the path construction, and make sure the given String does not have access previous folders?

Thanks in advance.

5
  • 4
    Get the canonical path, and check if it starts with your "base path" that you don't want the user to be able to go above. geeksforgeeks.org/java/… Commented Jul 10 at 8:18
  • 1
    The user running the application should be restricted to only the necessary permissions for the required folders. Additionally, user inputs should be properly sanitized to prevent path traversal vulnerabilities. Commented Jul 10 at 8:45
  • Thanks for the comments, I will take all into account. Commented Jul 10 at 9:27
  • @C3roe The getCanonicalPath() path is only useful for the old File API. For detecting path-traversal attacks in new nio file API you should use normalize() see e.g. heise.de/en/background/… Commented Jul 10 at 13:38
  • @Robert The NIO equivalent is actually toRealPath. Commented Jul 10 at 13:59

1 Answer 1

0

You

Try following these steps and see if it fixes the problem.

  1. Always normalize paths using Path.normalize()

  2. Validate the resolved path stays within your base directory

  3. Use allowlists for characters rather than blocklists

  4. Consider using UUIDs or database IDs instead of user-provided paths

  5. Log security violations for monitoring

  6. Never trust user input - always validate server-side

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.