【问题标题】:HTTPS request in twisted that checks the certificate用于检查证书的扭曲的 HTTPS 请求
【发布时间】:2015-04-30 12:16:38
【问题描述】:

在我的扭曲应用程序中,我想向 Akismet 发出异步请求以检查垃圾邮件。 Akismet 合理地使用 HTTPS,所以我一直在关注文档中的 web client guide on 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()

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

【问题讨论】:

    标签: python ssl https twisted twisted.web


    【解决方案1】:

    我正在使用 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)
    

    【讨论】:

    • 我最初是这样做的,但在连接到 google.com 时也遇到了上述错误。
    • 有趣的是,这种误报只发生在我的 Windows 开发机器上。我的 Ubuntu 服务器也可以愉快地执行?!我还尝试了一个不同的网站,该网站肯定是自签名的,结果相同。
    • 这个BrowserLikePolicyForHTTPS 将使用系统提供的证书。也许这就是 Ubuntu 和 Win 的结果不同的原因。
    • 这听起来可能,但我从未在 Ubuntu 机器上安装任何证书,当然也没有为自签名站点安装任何证书。
    • 那是因为 Ubuntu 自带了ca-certificates 包,没有它你甚至无法浏览 SO 和 Github 等有效证书的网站。
    【解决方案2】:

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

    我已提交this bug 以跟踪修复文档以使其准确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多