Mr.*_*nko 1 python ssl https twisted twisted.web
在我扭曲的应用程序中,我想向Akismet发出异步请求以检查垃圾邮件。Akismet合理地使用HTTPS,因此我一直遵循文档中有关SSL的网络客户端指南。但是有一部分让我担心:
这是一个示例,显示了如何使用代理在不进行证书验证的情况下请求HTTPS URL。
我非常希望通过证书验证来防止中间人攻击。那么我该如何添加呢?
我未经验证的测试代码是这样的:
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()
Run Code Online (Sandbox Code Playgroud)
我希望它由于无法验证证书而失败。
我正在使用Twisted 15.1.0。
实际上,默认的init函数Agent将BrowserLikePolicyForHTTPS作为contextFactory传入,并具有验证服务器证书的能力。
简单地使用这个:
agent = Agent( reactor )
Run Code Online (Sandbox Code Playgroud)
将产生以下错误:
failure: [Failure instance: Traceback (failure with no frames):
<class 'twisted.web._newclient.ResponseNeverReceived'>:
[<twisted.python.failure.Failure <class 'OpenSSL.SSL.Error'>>]]
Run Code Online (Sandbox Code Playgroud)
确保您service_identity使用pip 安装了软件包。
如果你需要自定义的证书验证,您可以通过将PEM在创建自定义策略,描述在这里:
customPolicy = BrowserLikePolicyForHTTPS(
Certificate.loadPEM(FilePath("your-trust-root.pem").getContent())
)
agent = Agent(reactor, customPolicy)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1696 次 |
| 最近记录: |