簡體   English   中英

如何在 Flask 中安全地獲取用戶的真實 IP 地址(使用 mod_wsgi)?

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

我在 mod_wsgi/Apache 上設置了一個 Flask 應用程序,需要記錄用戶的 IP 地址。 request.remote_addr 返回“127.0.0.1”,此修復嘗試更正該問題,但我發現 Django 出於安全原因刪除了類似的代碼。

有沒有更好的方法來安全地獲取用戶的真實IP地址?

編輯:也許我錯過了一些明顯的東西。 我應用了werkzeug/Flask 的修復程序,但是當我嘗試更改標頭的請求時,它似乎沒有什么區別:

運行.py:

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

視圖.py:

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

如果我啟用了 ProxyFix,也會發生同樣的結果。 我覺得我錯過了一些完全明顯的東西

僅當您定義可信代理列表時,才能使用request.access_route屬性

access_route屬性使用X-Forwarded-For標頭 ,回退到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在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保持不受影響。

從那篇文章中可以看出,安全問題是信任X-Forwarding-For標頭的第一個值。 您可以在“我嘗試更好的解決方案”部分中實現本文所述的內容,以克服這一潛在的安全問題。 我在django中成功使用的庫是django-ipware 通過它的實現跟蹤你自己的燒瓶(你可以看到它與那篇文章建議的類似):

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