如何在Flask中安全地获取用户的真实IP地址(使用mod_wsgi)?

问题描述 投票:10回答:3

我在mod_wsgi / Apache上设置了一个烧瓶应用程序,需要记录用户的IP地址。 request.remote_addr返回“127.0.0.1”,this fix尝试纠正,但我发现Django出于安全原因删除了类似的代码。

有没有更好的方法来安全地获取用户的真实IP地址?

编辑:也许我错过了一些明显的东西。我应用了werkzeug's/Flask's fix但是当我尝试使用带有更改标题的请求时它似乎没有什么区别:

润.朋友:

    from werkzeug.contrib.fixers import ProxyFix
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.run()

view.朋友:

for ip in request.access_route:
        print ip # prints "1.2.3.4" and "my.ip.address"

如果我启用了ProxyFix,则会出现相同的结果。我觉得我错过了一些完全明显的东西

python flask werkzeug
3个回答
25
投票

仅当您定义可信代理列表时,才能使用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)

这样,即使有人用X-Forwarded-For欺骗fake_ip1,fake_ip2标头,代理服务器也会将,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不受影响。


1
投票

从那篇文章中,听起来安全问题是信任X-Forwarding-For标题的第一个值。您可以在“我尝试更好的解决方案”部分中实现本文所述的内容,以克服这一潜在的安全问题。我在django中成功使用的库是django-ipware。通过它的实现跟踪你自己的烧瓶(你可以看到它与那篇文章建议的类似):

https://github.com/un33k/django-ipware/blob/master/ipware/ip.py#L7


-3
投票

你无法安全地做到这一点,因为你不能信任http(或tcp)连接中的所有部分

© www.soinside.com 2019 - 2024. All rights reserved.