python - 检查证书的扭曲的 HTTPS 请求

标签 python ssl https twisted twisted.web

在我扭曲的应用程序中,我想向 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()

我希望它因无法验证证书而失败。

最佳答案

我正在使用 Twisted 15.1.0。

实际上,Agent的默认init函数会传入BrowserLikePolicyForHTTPS作为contextFactory,并具备验证服务器证书的能力。

简单地使用这个:

agent = Agent( reactor )

会产生以下错误:

failure: [Failure instance: Traceback (failure with no frames):     
<class 'twisted.web._newclient.ResponseNeverReceived'>:
[<twisted.python.failure.Failure <class 'OpenSSL.SSL.Error'>>]]

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


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

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

关于python - 检查证书的扭曲的 HTTPS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29967559/

相关文章:

python - 我如何知道亚马逊是否成功发送电子邮件

ssl - 如何将多个握手消息组合到 java 中的一条记录?

Python:json标准化 "String indices must be integers"错误

python - 在 keras 的预训练密集层之间添加 dropout 层

python - 如何将整个 python 空闲命令历史记录打印到文本文件

amazon-web-services - Heroku SSL Cloudfront 缺少 key 对 ID 403 错误

rest - SunCertPathBuilderException : unable to find valid certification path to requested target in CN1 app

https - 访问K8S仪表板的正确方法是什么?

php - 以 PHP SSL 上下文选项 "cafile"可接受的格式导出 HTTPS 证书

.htaccess - 重定向到 https ://www. example.com