I have a view which fetches a file and serves it to the user. The view is as follows:
@login_required
def file(request, mid_id, file_name):
user = request.user
authorized_mids = user.profile.authorized_mids(True)
mid = get_object_or_404(Mid, id=mid_id)
try:
authorized_mids[mid.id]
except KeyError:
raise Http404
mid_file_path = settings.PATH_TO_REPORTS + ('/%s/' % mid.pk) + file_name
to_return = open(mid_file_path, 'r')
mimetype = mimetypes.guess_type(mid_file_path)
response = HttpResponse(to_return, mimetype=mimetype)
response['Content-Disposition'] = 'attachment; filename=%s' % file_name;
return response
My URL looks like:
url(r'^mid/(?P<mid_id>\d+)/file/(?P<file_name>.*?)/$', 'mid.views.file', name='fetch_report')
Are there any security concerns with having the .* in the URL? Will a (malicious) user be able to hack in such a way that they will be able to access files which they should not be able to?
You should probably replace the
.*?with[^#?]*?to avoid matching the query or fragment portions of the URL or useurllib.parseto separate out the path portion.Also, be aware of
..sequences in URLs.matches
which is outside the
mid/1/filesubdirectory tree.You could do
before running the regex which should reject the above because
is
but you will have to remove the
/before$andnormpathmight behave differently on Windows machines than on *nix. I don’t know of any equivalent tonormpathin theurllibmodule.