在我的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()
我希望它由于无法验证证书而失败
我用的是Twisted15.1.0。在
实际上,
Agent
的默认初始化函数将作为contextFactory传入BrowserLikePolicyForHTTPS
,并且能够验证服务器证书。在简单地使用这个:
将产生以下错误:
^{pr2}$确保使用pip安装了
service_identity
包。在如果需要自定义证书验证,可以通过传入pem来创建自定义策略,如here:
谢谢你指出这一点。这似乎是文档中的一个bug。在版本14.0之前,它是准确的;Twisted不能验证HTTPS,这是一个大问题。但是,正如您在the release notes for that version中看到的,Twisted(至少在14.0及更高版本中)确实验证了使用
Agent
建立的HTTPS连接上的TLS。(对于getPage
,这是一个旧的、坏的HTTP客户机,它仍然没有这样做;不要使用getPage
。)我已经提交了this bug以跟踪修正文档以确保其准确。在
相关问题 更多 >
编程相关推荐