只有在您定义了受信任的代理列表时,您才能使用request.access_route attribute。
access_route 属性使用X-Forwarded-For header,回退到REMOTE_ADDR WSGI 变量;后者很好,因为您的服务器确定了这一点; X-Forwarded-For 几乎可以由任何人设置,但如果您信任代理来正确设置值,则使用第一个(从最后开始)不受信任的代理:
trusted_proxies = {'127.0.0.1'} # define your own set
route = request.access_route + [request.remote_addr]
remote_addr = next((addr for addr in reversed(route)
if addr not in trusted_proxies), request.remote_addr)
这样,即使有人用fake_ip1,fake_ip2欺骗了X-Forwarded-For标头,代理服务器也会在末尾添加,spoof_machine_ip,上面的代码无论如何都会将remote_addr设置为spoof_machine_ip除了最外层的代理之外,还有许多受信任的代理。
这是您的链接文章谈到的白名单方法(简而言之,Rails 使用它),以及 Zope implemented over 11 years ago 的内容。
您的 ProxyFix 方法运行良好,但您误解了它的作用。它只设置request.remote_addr; request.access_route 属性不变(X-Forwarded-For 标头没有由中间件调整)。 但是,我会非常警惕盲目地计算代理。
对中间件应用相同的白名单方法如下所示:
class WhitelistRemoteAddrFix(object):
"""This middleware can be applied to add HTTP proxy support to an
application that was not designed with HTTP proxies in mind. It
only sets `REMOTE_ADDR` from `X-Forwarded` headers.
Tests proxies against a set of trusted proxies.
The original value of `REMOTE_ADDR` is stored in the WSGI environment
as `werkzeug.whitelist_remoteaddr_fix.orig_remote_addr`.
:param app: the WSGI application
:param trusted_proxies: a set or sequence of proxy ip addresses that can be trusted.
"""
def __init__(self, app, trusted_proxies=()):
self.app = app
self.trusted_proxies = frozenset(trusted_proxies)
def get_remote_addr(self, remote_addr, forwarded_for):
"""Selects the new remote addr from the given list of ips in
X-Forwarded-For. Picks first non-trusted ip address.
"""
if remote_addr in self.trusted_proxies:
return next((ip for ip in reversed(forwarded_for)
if ip not in self.trusted_proxies),
remote_addr)
def __call__(self, environ, start_response):
getter = environ.get
remote_addr = getter('REMOTE_ADDR')
forwarded_for = getter('HTTP_X_FORWARDED_FOR', '').split(',')
environ.update({
'werkzeug.whitelist_remoteaddr_fix.orig_remote_addr': remote_addr,
})
forwarded_for = [x for x in [x.strip() for x in forwarded_for] if x]
remote_addr = self.get_remote_addr(remote_addr, forwarded_for)
if remote_addr is not None:
environ['REMOTE_ADDR'] = remote_addr
return self.app(environ, start_response)
明确地说:这个中间件也是,只有设置request.remote_addr; request.access_route 不受影响。