gpt4 book ai didi

python - 为什么在 Django 中使用线程局部变量不好?

转载 作者:IT老高 更新时间:2023-10-28 20:35:28 27 4
gpt4 key购买 nike

我使用线程本地来存储当前用户和请求对象。这样我就可以轻松地从程序中的任何位置(例如动态表单)访问请求,而无需传递它们。

为了在中间件中实现线程本地存储,我遵循了 Django 网站上的教程: https://web.archive.org/web/20091128195932/http://code.djangoproject.com:80/wiki/CookBookThreadlocalsAndUser

此文档已被修改以建议避免使用此技术: https://web.archive.org/web/20110504132459/http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

来自文章:

From a design point of view, threadlocals are essentially global variables, and are subject to all the usual problems of portability and predictability that global variables usually entail.

More importantly, from a security point of view, threadlocals pose a huge risk. By providing an data store that exposes the state of other threads, you provide a way for one thread in your web server to potentially modify the state of another thread in the system. If the threadlocal data contains descriptions of users or other authentication-related data, that data could be used as the basis for an attack that grants access to an unauthorized user, or exposes private details of a user. While it is possible to build a threadlocal system that is safe from this sort of attack, it's a lot easier to be defensive and build a system that isn't subject to any such vulnerability in the first place.

我明白为什么全局变量可能不好,但在这种情况下,我在自己的服务器上运行自己的代码,所以我看不到两个全局变量会带来什么危险。

有人可以解释所涉及的安全问题吗?我问过很多人,如果他们阅读了这篇文章并且知道我正在使用线程本地,他们将如何破解我的应用程序,但没有人能够告诉我。我开始怀疑这是喜欢明确传递对象的纯粹主义者的观点。

最佳答案

我完全不同意。 TLS 非常有用。它应该小心使用,就像全局变量应该小心使用一样;但是说根本不应该使用它就像说永远不应该使用全局变量一样荒谬。

例如,我将当前事件的请求存储在 TLS 中。这使得它可以从我的日志类访问,而不必通过每个接口(interface)传递请求——包括许多根本不关心 Django 的接口(interface)。它让我可以从代码中的任何地方创建日志条目;记录器输出到数据库表,如果在生成日志时请求恰好处于事件状态,它会记录事件用户和所请求的内容等内容。

如果您不希望一个线程具有修改另一个线程的 TLS 数据的能力,则将您的 TLS 设置为禁止此操作,这可能需要使用 native TLS 类。不过,我觉得这个论点没有说服力。如果攻击者可以执行任意 Python 代码作为您的后端,那么您的系统已经受到了致命的威胁——例如,他可以修补任何东西,以便以后以不同的用户身份运行。

显然,您需要在请求结束时清除所有 TLS;在 Django 中,这意味着在中间件类的 process_response 和 process_exception 中清除它。

关于python - 为什么在 Django 中使用线程局部变量不好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3227180/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com