Python 文档文章 "Security considerations"有关 `smtplib` 的 SSL 上下文

标签 python python-3.x ssl smtplib

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_contextcreate_default_context 受到的限制更少。

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

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

相关文章:

python - 如何在单线程中运行 dask.distributed 集群?

python - 让函数在循环中只执行一次的有效方法

python - 有效地将字典映射为新列

amazon-web-services - AWS Lambda 上的证书固定

apache - 相对链接(来自 https)给出 301 永久移动(到 http)

python - 崩溃后写入文件而不会丢失数据

python - 如何拆分整数并将部分分配给变量

python - 将字符串的一部分附加到列表中

python - 如何用两种颜色绘制imshow?

PHP cURL https 不适用于新的 VPS