开发者

Security Concerns When placing .* (dot star) in Django URL Conf Regex

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 use urllib.parse to separate out the path portion.

Also, be aware of .. sequences in URLs.

r'^mid/(?P<mid_id>\d+)/file/(?P<file_name>.*?)/$'

matches

mid/1/file/../../../../etc/

which is outside the mid/1/file subdirectory tree.

You could do

os.path.normpath(path)

before running the regex which should reject the above because

os.path.normpath('mid/1/file/../../../../etc/')

is

../etc

but you will have to remove the / before $ and normpath might behave differently on Windows machines than on *nix. I don't know of any equivalent to normpath in the urllib module.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜