简体   繁体   English

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

[英]How do I safely get the user's real IP address in Flask (using mod_wsgi)?

I have a flask app setup on mod_wsgi/Apache and need to log the IP Address of the user.我在 mod_wsgi/Apache 上设置了一个 Flask 应用程序,需要记录用户的 IP 地址。 request.remote_addr returns "127.0.0.1" and this fix attempts to correct that but I've found that Django removed similar code for security reasons. request.remote_addr 返回“127.0.0.1”,此修复尝试更正该问题,但我发现 Django 出于安全原因删除了类似的代码。

Is there a better way to safely get the user's real IP address?有没有更好的方法来安全地获取用户的真实IP地址?

EDIT: Maybe I'm missing something obvious.编辑:也许我错过了一些明显的东西。 I applied werkzeug's/Flask's fix but it doesn't seem to make a difference when I try a request with altered headers:我应用了werkzeug/Flask 的修复程序,但是当我尝试更改标头的请求时,它似乎没有什么区别:

run.py:运行.py:

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

view.py:视图.py:

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

This same result happens if I have the ProxyFix enabled or not.如果我启用了 ProxyFix,也会发生同样的结果。 I feel like I'm missing something completely obvious我觉得我错过了一些完全明显的东西

You can use the request.access_route attribute only if you define a list of trusted proxies. 仅当您定义可信代理列表时,才能使用request.access_route属性

The access_route attribute uses the X-Forwarded-For header , falling back to the REMOTE_ADDR WSGI variable; access_route属性使用X-Forwarded-For标头 ,回退到REMOTE_ADDR WSGI变量; the latter is fine as your server determines this; 后者很好,因为你的服务器决定这一点; the X-Forwarded-For could have been set by just about anyone, but if you trust a proxy to set the value correctly, then use the first one (from the end) that is not trusted: 几乎任何人都可以设置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)

That way, even if someone spoofs the X-Forwarded-For header with fake_ip1,fake_ip2 , the proxy server will add ,spoof_machine_ip to the end, and the above code will set the remote_addr to spoof_machine_ip , no matter how many trusted proxies there are in addition to your outermost proxy. 这样,即使有人使用fake_ip1,fake_ip2欺骗X-Forwarded-For标头,代理服务器也会添加,spoof_machine_ip到最后,上面的代码会将remote_addr设置为spoof_machine_ip ,无论有多少可信代理。除了你最外面的代理。

This is the whitelist approach your linked article talks about (briefly, in that Rails uses it), and what Zope implemented over 11 years ago . 这是你的链接文章谈到的白名单方法(简单地说,Rails使用它),以及Zope在11年前实现的内容

Your ProxyFix approach works just fine, but you misunderstood what it does. 你的ProxyFix方法工作正常,但你误解了它的作用。 It only sets request.remote_addr ; 它只设置request.remote_addr ; the request.access_route attribute is unchanged (the X-Forwarded-For header is not adjusted by the middleware). request.access_route属性未更改(中间件调整X-Forwarded-For标头)。 However , I'd be very wary of blindly counting off proxies. 但是 ,我会非常警惕盲目地计算代理。

Applying the same whitelist approach to the middleware would look like: 对中间件应用相同的白名单方法如下所示:

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)

To be explicit: this middleware too, only sets request.remote_addr ; 要明确:这个中间件也设置request.remote_addr ; request.access_route remains unaffected. request.access_route保持不受影响。

From that article, it sounds like the security issue is trusting the first value of the X-Forwarding-For header. 从那篇文章中可以看出,安全问题是信任X-Forwarding-For标头的第一个值。 You can implement what the article suggests in the "my Attempt at a better solution" section to overcome this potential security issue. 您可以在“我尝试更好的解决方案”部分中实现本文所述的内容,以克服这一潜在的安全问题。 A library I've used in django with success is django-ipware . 我在django中成功使用的库是django-ipware Trace through its implementation to roll your own for flask (you can see that it's similar to what that article suggests): 通过它的实现跟踪你自己的烧瓶(你可以看到它与那篇文章建议的类似):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM