I have a system where user can upload file. I want to throw an exception in case the filename is contains sensitive characters like "../", etc. (to avoid Path Traversal vulnerability: "file/../../file.txt").
I have the code String originalFilename = multipartFile.getOriginalFilename();
There's an option to use StringUtils.cleanPath(originalFilename)
but it's not exactly what I need (I want to validate the file, not to normalize it).
The only option I see is to compare the normalized filename (the result of the StringUtils.cleanPath(...)
method) with the original String, but I'd like to know if there's something easier. For example something like: StringUtils.isPathValid(originalFilename)
.
In addition, I'd prefer to use a method that is already developed (open source) and commonly used instead of creating my own solution with regex.
Asked
Active
Viewed 705 times
0

rons1
- 21
- 2
-
what do you want to happen if the file name were, say, x/../x and x exists? It's a silly thing to type but it's meaningful and valid. Are you wanting to prevent the user entering anything other than a simple path with no relative traversals? I'm thinking that of the normalised path leads to a file may normalisation is actually the most useful behaviour. – djna Feb 21 '22 at 17:26
-
I want to throw an exception in case the filename contains sesative characters, not to normalize it. – rons1 Feb 21 '22 at 17:48
-
1Hi @rons1, as invalid path characters are very less in number, you can do a hard check on the input string, using `contains` as in when required. I think that code will be simple and easy to read instead of using some library. – Agnibha Feb 21 '22 at 18:17