安全问题在Django URL Conf Regex中放置。*(点星)

时间:2022-04-19 14:52:39

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?

在URL中使用。*是否存在任何安全问题? (恶意)用户能否以能够访问他们无法访问的文件的方式进行攻击?

1 个解决方案

#1


1  

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.

你应该更换。*?用[^#?] *?避免匹配URL的查询或片段部分或使用urllib.parse分隔出路径部分。

Also, be aware of .. sequences in URLs.

另外,请注意URL中的..序列。

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

matches

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

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

它位于mid / 1 / file子目录树之外。

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.

但是你必须删除/之前的$和normpath可能在Windows机器上的行为与在* nix上的行为不同。我不知道urllib模块中有任何与normpath等效的东西。

#1


1  

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.

你应该更换。*?用[^#?] *?避免匹配URL的查询或片段部分或使用urllib.parse分隔出路径部分。

Also, be aware of .. sequences in URLs.

另外,请注意URL中的..序列。

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

matches

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

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

它位于mid / 1 / file子目录树之外。

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.

但是你必须删除/之前的$和normpath可能在Windows机器上的行为与在* nix上的行为不同。我不知道urllib模块中有任何与normpath等效的东西。