gpt4 book ai didi

Python 文档文章 "Security considerations"关于 SSL 上下文与 `smtplib`

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:07 25 4
gpt4 key购买 nike

1。 smtplib.SMTP_SSL

在 Python 3 文档中 smtplib.SMTP_SSL它说:

class smtplib.SMTP_SSL(host='', port=0, local_hostname=None, keyfile=None, certfile=None, [timeout, ]context=None, source_address=None)

(...) context, also optional, can contain a SSLContext and allows configuring various aspects of the secure connection. Please read Security considerations for best practices.


2。安全注意事项文章

所以阅读上面提到的Security considerations它说:

(...) it is highly recommended that you use the create_default_context() function to create your SSL context.

(...) if you create the SSL context by calling the SSLContext constructor yourself, it will not have certificate validation nor hostname checking enabled by default.

所以看起来我肯定想要前者:create_default_context 用于 SSL 上下文。


3。 smtplib.py

我快速浏览了一下 smtplib.py看看会发生什么,如果我省略 smtplib.SMTP_SSLcontext 参数:

if context is None:
context = ssl._create_stdlib_context(certfile=certfile,
keyfile=keyfile)

因此调用了 ssl._create_stdlib_context,这似乎与安全注意事项一文中推荐的 ssl.create_default_context 不同。


4。 ssl.py

ssl.py 中的函数文档字符串中我发现:

All Python stdlib modules shall use this function to create SSLContext
objects in order to keep common settings in one place. The configuration
is less restrict than create_default_context()'s to increase backward
compatibility.


5.问题

根据安全注意事项一文,我应该如何调用 smtplib.SMTP_SSL?看来我真的需要每次都“手动”调用 create_default_context 来创建上下文?

server = smtplib.SMTP_SSL(context=ssl.create_default_context())

或者是

server = smtplib.SMTP_SSL()

够了吗?为什么?

非常感谢:-)

最佳答案

最佳做法是使用 server = smtplib.SMTP_SSL(context=ssl.create_default_context())

根据文档字符串,_create_stdlib_context 由于向后兼容而比 create_default_context 限制更少。

引用:https://github.com/python/cpython/blob/master/Lib/ssl.py#L581

关于Python 文档文章 "Security considerations"关于 SSL 上下文与 `smtplib`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53566679/

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