twisted中的HTTPS请求检查证书

2024-06-01 05:22:58 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的twisted应用程序中,我想向Akismet发出异步请求,以检查垃圾邮件。Akismet合理地使用了HTTPS,所以我一直关注文档中的web client guide on SSL。但有一点让我担心:

Here’s an example which shows how to use Agent to request an HTTPS URL with no certificate verification.

我非常希望通过证书验证来防止中间人攻击。那我该怎么加呢?在

我未经验证的测试代码是:

from twisted.internet import reactor
from twisted.web.client import Agent
from twisted.internet.ssl import ClientContextFactory

class WebClientContextFactory(ClientContextFactory):
    def getContext(self, hostname, port):
        print( "getting context for {}:{}".format( hostname, port ) )
        # FIXME: no attempt to verify certificates!
        return ClientContextFactory.getContext(self)

agent = Agent( reactor, WebClientContextFactory() )

def success( response ):
    print( "connected!" )
def failure( failure ):
    print( "failure: {}".format( failure ) )
def stop( ignored ):
    reactor.stop()

agent.request( "GET", "https://www.pcwebshop.co.uk/" )\ # uses self-signed cert
.addCallbacks( success, failure )\
.addBoth( stop )

reactor.run()

我希望它由于无法验证证书而失败


Tags: tofromhttpsimportselfwebfailuredef
2条回答

我用的是Twisted15.1.0。在

实际上,Agent的默认初始化函数将作为contextFactory传入BrowserLikePolicyForHTTPS,并且能够验证服务器证书。在

简单地使用这个:

agent = Agent( reactor )

将产生以下错误:

^{pr2}$

确保使用pip安装了service_identity包。在


如果需要自定义证书验证,可以通过传入pem来创建自定义策略,如here

customPolicy = BrowserLikePolicyForHTTPS(
    Certificate.loadPEM(FilePath("your-trust-root.pem").getContent())
)
agent = Agent(reactor, customPolicy)

谢谢你指出这一点。这似乎是文档中的一个bug。在版本14.0之前,它是准确的;Twisted不能验证HTTPS,这是一个大问题。但是,正如您在the release notes for that version中看到的,Twisted(至少在14.0及更高版本中)确实验证了使用Agent建立的HTTPS连接上的TLS。(对于getPage,这是一个旧的、坏的HTTP客户机,它仍然没有这样做;不要使用getPage。)

我已经提交了this bug以跟踪修正文档以确保其准确。在

相关问题 更多 >