python请求验证SSL证书

时间:2019-02-21 09:42:18

标签: python flask openssl python-requests ssl-certificate

我正在尝试从受SSL保护的API中提取数据。我写了一个python脚本来提取数据。事先,我必须将.p12文件转换为openSSL证书。当我使用以下代码时,它可以正常工作:

# ----- SCRIPT 1 -----
def pfx_to_pem(pfx_path, pfx_password):
    ''' Decrypts the .pfx file to be used with requests. '''
    with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem:
        f_pem = open(t_pem.name, 'wb')
        pfx = open(pfx_path, 'rb').read()
        p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password)
        f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey()))
        f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate()))
        ca = p12.get_ca_certificates()
        if ca is not None:
            for cert in ca:
                f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
        f_pem.close()
        yield t_pem.name

# read some config
with open('config.json') as config_json:
    config = json.load(config_json)
    api_url = config['api_url']
    cert = config['cert']

    cert_pem_path = cert['file']
    cert_key_file = cert['pass']

# make the request
with pfx_to_pem(cert_pem_path, cert_key_file) as cert:
    r = requests.get(api_url, cert = cert)

因为我还使用相同的功能向服务器验证我的Flask Web服务,所以我将cert文件分为三个文件:

# ----- SCRIPT 1 -----
# get certificate
f_pem.write(OpenSSL.crypto.dump_certificate(
    OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate())
)

# get keyfile
f_key.write(OpenSSL.crypto.dump_privatekey(
    OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey())
)

# get CA_BUNDLE
ca = p12.get_ca_certificates()
    if ca is not None:
        for cert in ca:
            f_ca.write(
                OpenSSL.crypto.dump_certificate(
                    OpenSSL.crypto.FILETYPE_PEM, cert
            ))

然后,我使用以下代码运行Web服务:

# ----- SCRIPT 2 -----
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(cert_ca)
context.load_cert_chain(cert_pem, cert_key)

app.run(ssl_context = context, host = '0.0.0.0')

并将请求调用更改为

# ----- SCRIPT 1 -----
r = requests.get(api_url, cert = (cert_pem, cert_key), verify = cert_ca)

当尝试从API中提取数据时,出现错误

requests.exceptions.SSLError: HTTPSConnectionPool(host='some.host', port=443): Max retries exceeded with url: /some/path/var?ID=xxxxxx (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:847)'),))

问题1:创建CA_BUNDLE时我做错了什么?

问题2:我是否正确处理了Web服务的创建?我的目标是针对保存数据的服务器验证我的服务器,以最终能够通过推送请求接收数据。

编辑:(在浏览器中)连接到我的Web服务时,尽管我将.p12证书导入到浏览器中,但由于证书无效,我收到连接不安全的警告。

1 个答案:

答案 0 :(得分:0)

所以我正在使用请求和json库来调用API,就我而言,我可以设置请求以忽略证书,这样就可以快速解决我的问题

requests.get(url, headers=headers, verify=False) 

参数verify = False忽略证书,但是在您运行代码时,它将在输出中显示警告消息,提示证书错误,因此您可以添加另一段代码以免显示请求警告:

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

我知道这不能回答您的问题,但是也许您可以尝试看看是否没有证书就可以毫无问题地获取信息。