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

Python docs article "Security considerations" about SSL context with `smtplib`

1。 smtplib.SMTP_SSL

smtplib.SMTP_SSL 的 Python 3 文档中说:

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?看来我真的需要每次"manually"调用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