如何使用Python使用智能卡进行TLS请求?

8

我尝试使用Python库“requests”与一张智能卡保护的网站进行通信。这意味着在SSL中需要强大的身份验证:您必须提供客户端证书(cert和私钥)。

由于我正在使用智能卡,因此无法读取私钥(仅限模数),这是一种正常的保护措施。我可以使用Python库PyKCS11读取智能卡:只需给出PIN码即可读取所有证书、公钥和私钥模数。

如何混合使用requests和PyKCS11?
如何在智能卡中使用客户端证书进行SSL请求?

编辑 2017/08/04

在我的Mac上:

  • brew install openssl
  • brew install opensc
  • brew install engine_pkcs11
  • openssl
    • engine dynamic -pre SO_PATH:/usr/local/Cellar/engine_pkcs11/0.1.8/lib/engines/engine_pkcs11.so -pre ID:pkcs11 -pre LIST_ADD:1 -pre LOAD -pre MODULE_PATH:/usr/local/lib/(my specific Pkcs11 lib).dylib
      • Loaded: (pkcs11) pkcs11 engine
    • s_client -engine pkcs11 -key '(slot):(id)' -keyform engine -cert 'pem.cer' -connect (host):443 -state -debug
      • SSL握手成功

现在我的问题是,pyOpenSSL没有API中选择引擎(如pkcs11)的功能。因此我被阻止了。我无法使用Python。


1
你解决了这个问题吗?如果是的话,能否分享一下? - tux
@tux:没有解决方案。 - Mlier
1
我能够使用pkcs#11提取证书。您能否分享一下您提取密钥的代码? - Anudocs
3个回答

2

我有一个类似的问题,不过我在使用Windows时需要使用"capi"引擎来处理智能卡客户端证书。我已经使用cffi和requests以及pyopenssl编写了可工作的代码,我希望将其改为支持pkcs11应该不会太困难。

import os
import ssl
import sys

import cffi
import requests

pyopenssl = requests.packages.urllib3.contrib.pyopenssl
pyopenssl.inject_into_urllib3()

# I use anaconda and these paths are valid for me, change as required
libcryptopath = os.path.join(sys.prefix, "Library", "bin", "libcrypto-1_1-x64.dll")
libsslpath = os.path.join(sys.prefix, "Library", "bin", "libssl-1_1-x64.dll")
capipath = os.path.join(sys.prefix, "Library", "lib", "engines-1_1", "capi.dll")

ffi = cffi.FFI()
ffi.cdef(
    "void *ENGINE_by_id(const char *id);"
    "int ENGINE_ctrl_cmd_string(void *e, const char *cmd_name, const char *arg, int cmd_optional);"
    "int ENGINE_init(void *e);"
    "int SSL_CTX_set_client_cert_engine(void *ctx, void *e);"
)

try:
    libcrypto, libssl, engine
except NameError:
    libcrypto = ffi.dlopen(libcryptopath)
    libssl = ffi.dlopen(libsslpath)
    engine = libcrypto.ENGINE_by_id(b"dynamic")
    libcrypto.ENGINE_ctrl_cmd_string(engine, b"SO_PATH", capipath.encode(), 0)
    libcrypto.ENGINE_ctrl_cmd_string(engine, b"LOAD", ffi.NULL, 0)
    libcrypto.ENGINE_init(engine)


class PyOpenSSLContextCAPI(pyopenssl.PyOpenSSLContext):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        libssl.SSL_CTX_set_client_cert_engine(self._ctx._context, engine)


# https://lukasa.co.uk/2017/02/Configuring_TLS_With_Requests/
class HTTPAdapterCAPI(requests.adapters.HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        context = PyOpenSSLContextCAPI(ssl.PROTOCOL_TLS)
        kwargs['ssl_context'] = context
        return super().init_poolmanager(*args, **kwargs)


class SessionCAPI(requests.Session):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.mount("https://", HTTPAdapterCAPI())


if __name__ == '__main__':
    s = SessionCAPI()
    r = s.get("https://example.com")
    print(r.text)

0

它可以与M2Crypto一起使用:

def InitPKCS11Engine(id, dllPath):
    Engine.load_dynamic()
    e = Engine.Engine('dynamic')
    e.ctrl_cmd_string('SO_PATH', dllPath)
    e.ctrl_cmd_string('ID', id)
    e.ctrl_cmd_string('LIST_ADD', '1')
    e.ctrl_cmd_string('LOAD', None)
    return e

之后,您可以添加特定的PKCS11库并添加PIN码。


3
这并没有展示如何从引擎对象获取到一个HTTP请求。 - Sam Hartman

0

谢谢您的想法。我成功完成了第一个点,但没有完成第二个点。 - Mlier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接