Skip to content

Commit

Permalink
Fix pre-commit check
Browse files Browse the repository at this point in the history
  • Loading branch information
mxamin committed Apr 5, 2024
1 parent 06f6e46 commit 2a2a014
Showing 1 changed file with 131 additions and 113 deletions.
244 changes: 131 additions & 113 deletions tests/softhsm_setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
Testing the PKCS#11 shim layer.
"""Testing the PKCS#11 shim layer.
Heavily inspired by from https://github.com/IdentityPython/pyXMLSecurity by leifj
under licence "As is", see https://github.com/IdentityPython/pyXMLSecurity/blob/master/LICENSE.txt
under license "As is", see https://github.com/IdentityPython/pyXMLSecurity/blob/master/LICENSE.txt
"""

import logging
Expand Down Expand Up @@ -31,9 +31,11 @@ def find_alts(component_name, alts: List[str]) -> str:
def run_cmd(args, softhsm_conf=None) -> Tuple[bytes, bytes]:
env = {}
if softhsm_conf is not None:
env['SOFTHSM_CONF'] = softhsm_conf
env['SOFTHSM2_CONF'] = softhsm_conf
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
env["SOFTHSM_CONF"] = softhsm_conf
env["SOFTHSM2_CONF"] = softhsm_conf
proc = subprocess.Popen(
args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
)
out, err = proc.communicate()
if err is not None and len(err) > 0:
logging.error(err)
Expand All @@ -43,7 +45,7 @@ def run_cmd(args, softhsm_conf=None) -> Tuple[bytes, bytes]:
if rv:
with open(softhsm_conf) as f:
conf = f.read()
msg = '[cmd: {cmd}] [code: {code}] [stdout: {out}] [stderr: {err}] [config: {conf}]'
msg = "[cmd: {cmd}] [code: {code}] [stdout: {out}] [stderr: {err}] [config: {conf}]"
msg = msg.format(
cmd=" ".join(args),
code=rv,
Expand All @@ -56,45 +58,49 @@ def run_cmd(args, softhsm_conf=None) -> Tuple[bytes, bytes]:


component_default_paths: Dict[str, List[str]] = {
'P11_MODULE': [
'/usr/lib/softhsm/libsofthsm2.so',
'/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so',
'/usr/lib/softhsm/libsofthsm.so',
'/usr/lib64/softhsm/libsofthsm2.so',
"P11_MODULE": [
"/usr/lib/softhsm/libsofthsm2.so",
"/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so",
"/usr/lib/softhsm/libsofthsm.so",
"/usr/lib64/softhsm/libsofthsm2.so",
],
'P11_ENGINE': [
'/usr/lib/ssl/engines/libpkcs11.so',
'/usr/lib/engines/engine_pkcs11.so',
'/usr/lib/x86_64-linux-gnu/engines-1.1/pkcs11.so',
'/usr/lib64/engines-1.1/pkcs11.so',
'/usr/lib64/engines-1.1/libpkcs11.so',
'/usr/lib64/engines-3/pkcs11.so',
'/usr/lib64/engines-3/libpkcs11.so',
'/usr/lib/x86_64-linux-gnu/engines-3/pkcs11.so',
'/usr/lib/x86_64-linux-gnu/engines-3/libpkcs11.so',
"P11_ENGINE": [
"/usr/lib/ssl/engines/libpkcs11.so",
"/usr/lib/engines/engine_pkcs11.so",
"/usr/lib/x86_64-linux-gnu/engines-1.1/pkcs11.so",
"/usr/lib64/engines-1.1/pkcs11.so",
"/usr/lib64/engines-1.1/libpkcs11.so",
"/usr/lib64/engines-3/pkcs11.so",
"/usr/lib64/engines-3/libpkcs11.so",
"/usr/lib/x86_64-linux-gnu/engines-3/pkcs11.so",
"/usr/lib/x86_64-linux-gnu/engines-3/libpkcs11.so",
],
'PKCS11_TOOL': [
'/usr/bin/pkcs11-tool',
"PKCS11_TOOL": [
"/usr/bin/pkcs11-tool",
],
'SOFTHSM': [
'/usr/bin/softhsm2-util',
'/usr/bin/softhsm',
"SOFTHSM": [
"/usr/bin/softhsm2-util",
"/usr/bin/softhsm",
],
'OPENSSL': [
'/usr/bin/openssl',
"OPENSSL": [
"/usr/bin/openssl",
],
}

component_path: Dict[str, str] = {
component_name: find_alts(component_name, paths_for_component(component_name, default_paths))
component_name: find_alts(
component_name, paths_for_component(component_name, default_paths)
)
for component_name, default_paths in component_default_paths.items()
}

softhsm_version = 1
if component_path['SOFTHSM'].endswith('softhsm2-util'):
if component_path["SOFTHSM"].endswith("softhsm2-util"):
softhsm_version = 2

openssl_version = subprocess.check_output([component_path['OPENSSL'], 'version'])[8:11].decode()
openssl_version = subprocess.check_output([component_path["OPENSSL"], "version"])[
8:11
].decode()

p11_test_files: List[str] = []
softhsm_conf: Optional[str] = None
Expand All @@ -113,7 +119,9 @@ def _temp_dir() -> str:
return d


@unittest.skipIf(component_path['P11_MODULE'] is None, "SoftHSM PKCS11 module not installed")
@unittest.skipIf(
component_path["P11_MODULE"] is None, "SoftHSM PKCS11 module not installed"
)
def setup() -> None:
logging.debug("Creating test pkcs11 token using softhsm")
try:
Expand Down Expand Up @@ -145,16 +153,16 @@ def setup() -> None:
logging.debug("Initializing the token")
out, err = run_cmd(
[
component_path['SOFTHSM'],
'--slot',
'0',
'--label',
'test',
'--init-token',
'--pin',
'secret1',
'--so-pin',
'secret2',
component_path["SOFTHSM"],
"--slot",
"0",
"--label",
"test",
"--init-token",
"--pin",
"secret1",
"--so-pin",
"secret2",
],
softhsm_conf=softhsm_conf,
)
Expand All @@ -173,17 +181,17 @@ def setup() -> None:
logging.debug("Converting test private key to format for softhsm")
run_cmd(
[
component_path['OPENSSL'],
'pkcs8',
'-topk8',
'-inform',
'PEM',
'-outform',
'PEM',
'-nocrypt',
'-in',
os.path.join(DATA_DIR, 'rsakey.pem'),
'-out',
component_path["OPENSSL"],
"pkcs8",
"-topk8",
"-inform",
"PEM",
"-outform",
"PEM",
"-nocrypt",
"-in",
os.path.join(DATA_DIR, "rsakey.pem"),
"-out",
hash_priv_key,
],
softhsm_conf=softhsm_conf,
Expand All @@ -192,27 +200,37 @@ def setup() -> None:
logging.debug("Importing the test key to softhsm")
run_cmd(
[
component_path['SOFTHSM'],
'--import',
component_path["SOFTHSM"],
"--import",
hash_priv_key,
'--token',
'test',
'--id',
'a1b2',
'--label',
'test',
'--pin',
'secret1',
"--token",
"test",
"--id",
"a1b2",
"--label",
"test",
"--pin",
"secret1",
],
softhsm_conf=softhsm_conf,
)
run_cmd(
[component_path['PKCS11_TOOL'], '--module', component_path['P11_MODULE'], '-l', '--pin', 'secret1', '-O'],
[
component_path["PKCS11_TOOL"],
"--module",
component_path["P11_MODULE"],
"-l",
"--pin",
"secret1",
"-O",
],
softhsm_conf=softhsm_conf,
)
signer_cert_pem = _temp_file()
openssl_conf = _temp_file()
logging.debug("Generating OpenSSL config for version {}".format(openssl_version))
logging.debug(
"Generating OpenSSL config for version {}".format(openssl_version)
)
with open(openssl_conf, "w") as f:
# Might be needed with some versions of openssl, but in more recent versions dynamic_path breaks it.
# dynamic_path = (
Expand All @@ -234,59 +252,59 @@ def setup() -> None:
"[pkcs11_section]",
"engine_id = pkcs11",
# dynamic_path,
"MODULE_PATH = %s" % component_path['P11_MODULE'],
"MODULE_PATH = %s" % component_path["P11_MODULE"],
"init = 0",
]
)
)

with open(openssl_conf, "r") as f:
logging.debug('-------- START DEBUG openssl_conf --------')
logging.debug("-------- START DEBUG openssl_conf --------")
logging.debug(f.readlines())
logging.debug('-------- END DEBUG openssl_conf --------')
logging.debug('-------- START DEBUG paths --------')
logging.debug(run_cmd(['ls', '-ld', component_path['P11_ENGINE']]))
logging.debug(run_cmd(['ls', '-ld', component_path['P11_MODULE']]))
logging.debug('-------- END DEBUG paths --------')
logging.debug("-------- END DEBUG openssl_conf --------")
logging.debug("-------- START DEBUG paths --------")
logging.debug(run_cmd(["ls", "-ld", component_path["P11_ENGINE"]]))
logging.debug(run_cmd(["ls", "-ld", component_path["P11_MODULE"]]))
logging.debug("-------- END DEBUG paths --------")

signer_cert_der = _temp_file()

logging.debug("Generating self-signed certificate")
run_cmd(
[
component_path['OPENSSL'],
'req',
'-new',
'-x509',
'-subj',
component_path["OPENSSL"],
"req",
"-new",
"-x509",
"-subj",
"/CN=Test Signer",
'-engine',
'pkcs11',
'-config',
"-engine",
"pkcs11",
"-config",
openssl_conf,
'-keyform',
'engine',
'-key',
'label_test',
'-passin',
'pass:secret1',
'-out',
"-keyform",
"engine",
"-key",
"label_test",
"-passin",
"pass:secret1",
"-out",
signer_cert_pem,
],
softhsm_conf=softhsm_conf,
)

run_cmd(
[
component_path['OPENSSL'],
'x509',
'-inform',
'PEM',
'-outform',
'DER',
'-in',
component_path["OPENSSL"],
"x509",
"-inform",
"PEM",
"-outform",
"DER",
"-in",
signer_cert_pem,
'-out',
"-out",
signer_cert_der,
],
softhsm_conf=softhsm_conf,
Expand All @@ -296,29 +314,29 @@ def setup() -> None:

run_cmd(
[
component_path['PKCS11_TOOL'],
'--module',
component_path['P11_MODULE'],
'-l',
'--slot-index',
'0',
'--id',
'a1b2',
'--label',
'test',
'-y',
'cert',
'-w',
component_path["PKCS11_TOOL"],
"--module",
component_path["P11_MODULE"],
"-l",
"--slot-index",
"0",
"--id",
"a1b2",
"--label",
"test",
"-y",
"cert",
"-w",
signer_cert_der,
'--pin',
'secret1',
"--pin",
"secret1",
],
softhsm_conf=softhsm_conf,
)

# TODO: Should be teardowned in teardown:
os.environ['SOFTHSM_CONF'] = softhsm_conf
os.environ['SOFTHSM2_CONF'] = softhsm_conf
os.environ["SOFTHSM_CONF"] = softhsm_conf
os.environ["SOFTHSM2_CONF"] = softhsm_conf

except Exception as ex:
print("-" * 64)
Expand Down

0 comments on commit 2a2a014

Please sign in to comment.