Is it possible to exploit this code?
How can an attacker exploit this?
Path Traversal Vulnerabilities allow an attacker to choose a file that is not intended by the developer.
For example, your program has the path
"C:\\Users\\kutrivedi\\Desktop\\Ref\\" + input + ".txt" hardcoded. If I entered
foo as input, then the resulting file would be
Of course, I could add more than just one word, such as
foo\\bar, which would result in the following file being read instead:
So just by adding
\\, I can traverse deeper into the file structure.
Can an attacker traverse the file system up?
I can do that too, with the pseudo-directory
... Every directory has a pseudo-entry called
.., which points to the parent. As such, if I enter
..\\foo, then the following path is created
C:\\Users\\kutrivedi\\Desktop\\Ref\\..\\foo.txt, which will be resolved to
For example, if my payload is
..\\..\\..\\..\\foo, then I would now read
I could go further and print arbitrary files, as long as they had a
.txt extension. Since this code was presumably written in Java, and Java does not terminate strings with a
\0 character, there is no easy way to terminate the string earlier to skip the extension.
If, however, your programming language was built on null-terminating strings, my payload could read arbitrary files too, as long as the process had permission to read them:
..\\..\\..\\..\\Windows\\System32\\config\\SAM\0 will result in
How can this be fixed?
The easiest way is to use a library or built-in framework, which deals with paths. Most libraries have checks to see if something is inside or outside a directory structure, so you can use those checks to see if the payload you are getting is trying to access a file it shouldn't.