I need to prevent from directory traversal attack
from my code using Python. My code is below:
JavaScript
x
9
1
if request.GET.get('param') is not None and request.GET.get('param') != '':
2
param = request.GET.get('param')
3
startdir = os.path.abspath(os.curdir)
4
requested_path = os.path.relpath(param, startdir)
5
requested_path = os.path.abspath(requested_path)
6
print(requested_path)
7
tfile = open(requested_path, 'rb')
8
return HttpResponse(content=tfile, content_type="text/plain")
9
Here I need user is running like http://127.0.0.1:8000/createfile/?param=../../../../../../../../etc/passwd
this it should prevent the directory traversal attack.
Advertisement
Answer
Suppose the user content is all located in
JavaScript
1
2
1
safe_dir = '/home/saya/server/content/'
2
Ending with /
is important as heinrichj mentions to ensure the check below matches against a specific directory.
You need to verify the final request is in there:
JavaScript
1
3
1
if os.path.commonprefix((os.path.realpath(requested_path),safe_dir)) != safe_dir:
2
#Bad user!
3
If the requested path is allowed to be the save_dir
itself, you would also need to allow entry if os.path.realpath(requested_path)+'/' == safe_dir
.
I encourage you to make sure all stuff you want accessible by the user in one place.