Description
A week ago I stumbled across this project on Hackernews and had a brief look at the code. I particular I noticed the spartan API which provides direct config file access:
@api.route('/config/<name>', methods=['GET'])
def get_config(name: str):
nginx_path = flask.current_app.config['NGINX_PATH']
with io.open(os.path.join(nginx_path, name), 'r') as f:
_file = f.read()
return flask.render_template('config.html', name=name, file=_file), 200
The Problem
This code basically relies on the Flask router to filter out possibly malicious name
values. The Flask router is obviously not designed for that, but it incidentally works fine for name
values such as ../../../../etc/passwd
as the route fails to match in this case. However, this is not always the case and more importantly it is dangerous to rely on this. I don't know if you officially support Windows as a platform but I want to use Windows paths as an example for this:
Imagine the NGINX_PATH
is set to C:\\path\to\config\
and someone could do the following request:
curl 'http://localhost/api/config/D:\\some\unrelated\file'
Then the os.path.join
call would work as follows:
os.path.join("C:\\\\path\\to\\config\\", "D:\\\\some\\unrelated\\file")
# 'D:\\\\some\\unrelated\\file'
This is a Path Traversal vulnerability which means your API would allow users to read and write arbitrary files. Even if you do not support Windows, the only protection in place on Linux is the router which is meant to be a protection. If someone clever would be able to get the name
../../../../etc/passwd
passed through the router to this API endpoint you end in the same situation.
Possible Solution
As a solution I would suggest using os.path.basename
on name
first or if you want to support subdirectories of NGINX_PATH
you could use os.path.join
, then normalize the path with os.path.normpath
or os.path.realpath
and then check if the resulting path still starts with NGINX_PATH
. For more information about path traversal vulnerabilities, see https://owasp.org/www-community/attacks/Path_Traversal.