The source code can be obtained by exploiting the path traversal vulnerability. To view the source of the web application, browse the URL http://127.0.0.1:5000/employee?filename=../app.py.
The above source code is a python based flask application. Let’s try to identify where the bug exists which leads path traversal vulnerability in our source code.
The below code maps the URL path ’/’ to the index function which returns/renders the index.html, which seems like does not contain path traversal vulnerability.
The quickest way to detect a path traversal vulnerability to spot the source code using file operations
Now, let’s analyse the view_file function’s definition mounted at endpoint /employee (this function seems like our candidate, as our vulnerability existed on /employee).
In the above function, the developer is using os.path.join construct to create the absolute path from the user-input filename, but the developer failed to check that the file being requested is in current context or not.
Mitigation
The following code snippet fixes the same by using the os.path.commonpath function to check whether the path is in common between our current working directory and the file requested.
After, making the appropriate change, you can navigate to our vulnerable URL endpoint for accessing /etc/passwd file i.e. http://127.0.0.1:5000/employee?filename=../../../../etc/passwd, you will be encountered with 404 Not Found error.