仅当定义 受信任
代理的列表时,才可以使用该
request.access_route属性。
__
该
access_route属性使用
X-Forwarded-Forheader,回退到
REMOTE_ADDRWSGI变量;后者很好,因为您的服务器确定了这一点;在
X-Forwarded-For可能已被几乎任何人都设定,但如果你信任的代理正确设置值,然后使用第一个(从端)成为 不 信任:
trusted_proxies = {'127.0.0.1'} # define your own setroute = request.access_route + [request.remote_addr]remote_addr = next((addr for addr in reversed(route) if addr not in trusted_proxies), request.remote_addr)
这样,即使有人用欺骗了
X-Forwarded-For标头
fake_ip1,fake_ip2,代理服务器也会添加
,spoof_machine_ip到末尾,并且上面的代码会将设置
remote_addr为
spoof_machine_ip,无论最外面的代理服务器还有多少个受信任的代理。
这是您的链接文章所谈论的白名单方法(简短地说,就是Rails使用它),以及Zope在11年前实施的方法。
您的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仍然不受影响。