2

我有一个非 ascii 字符的域,类似于http://blå.no该域使用其 punycode 等效项注册:

xn--bl-zia.no

这也在 Apache vhost 中设置:

<VirtualHost *:443>
    ServerName xn--bl-zia.no
    ...

我看到的问题来自包含以下内容的请求:

'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
'HTTP_HOST': 'xn--bl-zia.no',
'SERVER_NAME': 'xn--bl-zia.no',
'HTTP_REFERER': 'https://bl\xc3\xa5.no/login/ka/?next=/start-exam/participant-login/',
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',

IE。引用者以 utf-8 格式发送,而不是 punycode。我得到的例外是:

Traceback (most recent call last):

  File "/srv/cleanup-project/venv/dev/lib/python2.7/site-packages/django/core/handlers/base.py", line 153, in get_response
    response = callback(request, **param_dict)

  File "/srv/cleanup-project/venv/dev/lib/python2.7/site-packages/django/utils/decorators.py", line 87, in _wrapped_view
    result = middleware.process_view(request, view_func, args, kwargs)

  File "/srv/cleanup-project/venv/dev/lib/python2.7/site-packages/django/middleware/csrf.py", line 157, in process_view
    reason = REASON_BAD_REFERER % (referer, good_referer)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 10: ordinal not in range(128)

中的相关代码csrf.py为:

            good_referer = 'https://%s/' % request.get_host()
            if not same_origin(referer, good_referer):
                reason = REASON_BAD_REFERER % (referer, good_referer)

get_host()使用SERVER_NAME来自请求的)

是否有本机 Django 方法来处理这个问题,或者我是否需要编写一个中间件,将 utf-8 转换为引用标头的域部分中的 punycode?

4

1 回答 1

0

这是一个中间件解决方案..

import urlparse


class PunyCodeU8RefererFixerMiddleware(object):
    def process_request(self, request):
        servername = request.META['SERVER_NAME']
        if 'xn--' not in servername:
            return None

        referer = request.META.get("HTTP_REFERER")
        if not referer:
            return None

        url = urlparse.urlparse(referer)
        try:
            netloc = url.netloc.decode('u8')
        except UnicodeDecodeError:
            return None

        def isascii(txt):
            return all(ord(ch) < 128 for ch in txt)

        netloc = '.'.join([
            str(p) if isascii(p) else 'xn--' + p.encode('punycode')
            for p in netloc.split('.')
        ])
        url = url._replace(netloc=netloc)
        request.META['HTTP_REFERER'] = urlparse.urlunparse(url)
        return None

当它检测到它不能做任何有用的事情时,它会尽可能早地退出。当然必须在csrf中间件之前安装。

于 2015-04-28T21:43:51.853 回答