python - urllib 和服务器证书的验证

标签 python ssl ssl-certificate urllib

我使用 python 2.6 并请求 Facebook API (https)。我想我的服务可能成为中间人攻击的目标。 我今天早上再次阅读 urllib 模块文档时发现: 引文:

Warning : When opening HTTPS URLs, it is not attempted to validate the server certificate. Use at your own risk!

您是否有完成完整证书验证的提示/网址/示例?

谢谢你的帮助

最佳答案

您可以创建一个 urllib2 opener,它可以使用自定义处理程序为您进行验证。以下代码是适用于 Python 2.7.3 的示例。它假定您已下载 http://curl.haxx.se/ca/cacert.pem到保存脚本的同一文件夹。

#!/usr/bin/env python
import urllib2
import httplib
import ssl
import socket
import os

CERT_FILE = os.path.join(os.path.dirname(__file__), 'cacert.pem')


class ValidHTTPSConnection(httplib.HTTPConnection):
        "This class allows communication via SSL."

        default_port = httplib.HTTPS_PORT

        def __init__(self, *args, **kwargs):
            httplib.HTTPConnection.__init__(self, *args, **kwargs)

        def connect(self):
            "Connect to a host on a given (SSL) port."

            sock = socket.create_connection((self.host, self.port),
                                            self.timeout, self.source_address)
            if self._tunnel_host:
                self.sock = sock
                self._tunnel()
            self.sock = ssl.wrap_socket(sock,
                                        ca_certs=CERT_FILE,
                                        cert_reqs=ssl.CERT_REQUIRED)


class ValidHTTPSHandler(urllib2.HTTPSHandler):

    def https_open(self, req):
            return self.do_open(ValidHTTPSConnection, req)

opener = urllib2.build_opener(ValidHTTPSHandler)


def test_access(url):
    print "Acessing", url
    page = opener.open(url)
    print page.info()
    data = page.read()
    print "First 100 bytes:", data[0:100]
    print "Done accesing", url
    print ""

# This should work
test_access("https://www.google.com")

# Accessing a page with a self signed certificate should not work
# At the time of writing, the following page uses a self signed certificate
test_access("https://tidia.ita.br/")

运行这个脚本你应该看到这样的输出:

Acessing https://www.google.com
Date: Mon, 14 Jan 2013 14:19:03 GMT
Expires: -1
...

First 100 bytes: <!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop
Done accesing https://www.google.com

Acessing https://tidia.ita.br/
Traceback (most recent call last):
  File "https_validation.py", line 54, in <module>
    test_access("https://tidia.ita.br/")
  File "https_validation.py", line 42, in test_access
    page = opener.open(url)
  ...
  File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1177, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 1] _ssl.c:504: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed>

关于python - urllib 和服务器证书的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6648952/

相关文章:

python - 如何为分类值列表的列创建嵌入

python ,加权林空间

python - Inf在Matlab上的使用

python - 给出 'hints' 问题

android - 从 OkHttp 响应正文中解密 SSL 流量

java - 在 Android 中使用 SSL 证书

ssl - HTTPS(SSL/TLS)

ssl - 用paypal支付,需要ssl证书吗

ssl - React-native websocket TLS 连接

ssl - 使用 HTTP2 和 TLS 的牛仔网络服务器在 Chrome 中获取 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY