1- """
2- Testing the PKCS#11 shim layer.
1+ """Testing the PKCS#11 shim layer.
2+
33Heavily inspired by from https://github.com/IdentityPython/pyXMLSecurity by leifj
4- under licence "As is", see https://github.com/IdentityPython/pyXMLSecurity/blob/master/LICENSE.txt
4+ under license "As is", see https://github.com/IdentityPython/pyXMLSecurity/blob/master/LICENSE.txt
55"""
66
77import logging
1313import unittest
1414from typing import Dict , List , Optional , Tuple
1515
16- DATA_DIR = os .path .join (os .path .dirname (__file__ ), " data" )
16+ DATA_DIR = os .path .join (os .path .dirname (__file__ ), ' data' )
1717
1818
1919def paths_for_component (component : str , default_paths : List [str ]):
@@ -25,7 +25,7 @@ def find_alts(component_name, alts: List[str]) -> str:
2525 for a in alts :
2626 if os .path .exists (a ):
2727 return a
28- raise unittest .SkipTest (" Required component is missing: {}" .format (component_name ))
28+ raise unittest .SkipTest (' Required component is missing: {}' .format (component_name ))
2929
3030
3131def run_cmd (args , softhsm_conf = None ) -> Tuple [bytes , bytes ]:
@@ -45,7 +45,7 @@ def run_cmd(args, softhsm_conf=None) -> Tuple[bytes, bytes]:
4545 conf = f .read ()
4646 msg = '[cmd: {cmd}] [code: {code}] [stdout: {out}] [stderr: {err}] [config: {conf}]'
4747 msg = msg .format (
48- cmd = " " .join (args ),
48+ cmd = ' ' .join (args ),
4949 code = rv ,
5050 out = out .strip (),
5151 err = err .strip (),
@@ -113,36 +113,34 @@ def _temp_dir() -> str:
113113 return d
114114
115115
116- @unittest .skipIf (component_path ['P11_MODULE' ] is None , " SoftHSM PKCS11 module not installed" )
116+ @unittest .skipIf (component_path ['P11_MODULE' ] is None , ' SoftHSM PKCS11 module not installed' )
117117def setup () -> None :
118- logging .debug (" Creating test pkcs11 token using softhsm" )
118+ logging .debug (' Creating test pkcs11 token using softhsm' )
119119 try :
120120 global softhsm_conf
121121 softhsm_conf = _temp_file ()
122- logging .debug (" Generating softhsm.conf" )
123- with open (softhsm_conf , "w" ) as f :
122+ logging .debug (' Generating softhsm.conf' )
123+ with open (softhsm_conf , 'w' ) as f :
124124 if softhsm_version == 2 :
125125 softhsm_db = _temp_dir ()
126126 f .write (
127- """
127+ f """
128128# Generated by test
129- directories.tokendir = %s
129+ directories.tokendir = { softhsm_db }
130130objectstore.backend = file
131131log.level = DEBUG
132132"""
133- % softhsm_db
134133 )
135134 else :
136135 softhsm_db = _temp_file ()
137136 f .write (
138- """
137+ f """
139138# Generated by test
140- 0:%s
139+ 0:{ softhsm_db }
141140"""
142- % softhsm_db
143141 )
144142
145- logging .debug (" Initializing the token" )
143+ logging .debug (' Initializing the token' )
146144 out , err = run_cmd (
147145 [
148146 component_path ['SOFTHSM' ],
@@ -159,18 +157,8 @@ def setup() -> None:
159157 softhsm_conf = softhsm_conf ,
160158 )
161159
162- # logging.debug("Generating 1024 bit RSA key in token")
163- # run_cmd([component_path['PKCS11_TOOL'],
164- # '--module', component_path['P11_MODULE'],
165- # '-l',
166- # '-k',
167- # '--key-type', 'rsa:1024',
168- # '--id', 'a1b2',
169- # '--label', 'test',
170- # '--pin', 'secret1'], softhsm_conf=softhsm_conf)
171-
172160 hash_priv_key = _temp_file ()
173- logging .debug (" Converting test private key to format for softhsm" )
161+ logging .debug (' Converting test private key to format for softhsm' )
174162 run_cmd (
175163 [
176164 component_path ['OPENSSL' ],
@@ -189,7 +177,7 @@ def setup() -> None:
189177 softhsm_conf = softhsm_conf ,
190178 )
191179
192- logging .debug (" Importing the test key to softhsm" )
180+ logging .debug (' Importing the test key to softhsm' )
193181 run_cmd (
194182 [
195183 component_path ['SOFTHSM' ],
@@ -207,40 +195,42 @@ def setup() -> None:
207195 softhsm_conf = softhsm_conf ,
208196 )
209197 run_cmd (
210- [component_path ['PKCS11_TOOL' ], '--module' , component_path ['P11_MODULE' ], '-l' , '--pin' , 'secret1' , '-O' ],
198+ [
199+ component_path ['PKCS11_TOOL' ],
200+ '--module' ,
201+ component_path ['P11_MODULE' ],
202+ '-l' ,
203+ '--pin' ,
204+ 'secret1' ,
205+ '-O' ,
206+ ],
211207 softhsm_conf = softhsm_conf ,
212208 )
213209 signer_cert_pem = _temp_file ()
214210 openssl_conf = _temp_file ()
215- logging .debug ("Generating OpenSSL config for version {}" .format (openssl_version ))
216- with open (openssl_conf , "w" ) as f :
217- # Might be needed with some versions of openssl, but in more recent versions dynamic_path breaks it.
218- # dynamic_path = (
219- # "dynamic_path = %s" % component_path['P11_ENGINE']
220- # if openssl_version.startswith(b'1.')
221- # else ""
222- # )
211+ logging .debug ('Generating OpenSSL config for version %s' , openssl_version )
212+ with open (openssl_conf , 'w' ) as f :
223213 f .write (
224- " \n " .join (
214+ ' \n ' .join (
225215 [
226- " openssl_conf = openssl_def" ,
227- " [openssl_def]" ,
228- " engines = engine_section" ,
229- " [engine_section]" ,
230- " pkcs11 = pkcs11_section" ,
231- " [req]" ,
232- " distinguished_name = req_distinguished_name" ,
233- " [req_distinguished_name]" ,
234- " [pkcs11_section]" ,
235- " engine_id = pkcs11" ,
216+ ' openssl_conf = openssl_def' ,
217+ ' [openssl_def]' ,
218+ ' engines = engine_section' ,
219+ ' [engine_section]' ,
220+ ' pkcs11 = pkcs11_section' ,
221+ ' [req]' ,
222+ ' distinguished_name = req_distinguished_name' ,
223+ ' [req_distinguished_name]' ,
224+ ' [pkcs11_section]' ,
225+ ' engine_id = pkcs11' ,
236226 # dynamic_path,
237- "MODULE_PATH = %s" % component_path ['P11_MODULE' ],
238- " init = 0" ,
227+ f "MODULE_PATH = { component_path ['P11_MODULE' ]} " ,
228+ ' init = 0' ,
239229 ]
240230 )
241231 )
242232
243- with open (openssl_conf , "r" ) as f :
233+ with open (openssl_conf , 'r' ) as f :
244234 logging .debug ('-------- START DEBUG openssl_conf --------' )
245235 logging .debug (f .readlines ())
246236 logging .debug ('-------- END DEBUG openssl_conf --------' )
@@ -251,15 +241,15 @@ def setup() -> None:
251241
252242 signer_cert_der = _temp_file ()
253243
254- logging .debug (" Generating self-signed certificate" )
244+ logging .debug (' Generating self-signed certificate' )
255245 run_cmd (
256246 [
257247 component_path ['OPENSSL' ],
258248 'req' ,
259249 '-new' ,
260250 '-x509' ,
261251 '-subj' ,
262- " /CN=Test Signer" ,
252+ ' /CN=Test Signer' ,
263253 '-engine' ,
264254 'pkcs11' ,
265255 '-config' ,
@@ -292,7 +282,7 @@ def setup() -> None:
292282 softhsm_conf = softhsm_conf ,
293283 )
294284
295- logging .debug (" Importing certificate into token" )
285+ logging .debug (' Importing certificate into token' )
296286
297287 run_cmd (
298288 [
@@ -316,15 +306,15 @@ def setup() -> None:
316306 softhsm_conf = softhsm_conf ,
317307 )
318308
319- # TODO: Should be teardowned in teardown:
309+ # TODO: Should be teardowned in teardown # noqa: T101
320310 os .environ ['SOFTHSM_CONF' ] = softhsm_conf
321311 os .environ ['SOFTHSM2_CONF' ] = softhsm_conf
322312
323313 except Exception as ex :
324- print ("-" * 64 )
314+ print ('-' * 64 )
325315 traceback .print_exc ()
326- print ("-" * 64 )
327- logging .error ( " PKCS11 tests disabled: unable to initialize test token: %s" % ex )
316+ print ('-' * 64 )
317+ logging .exception ( ' PKCS11 tests disabled: unable to initialize test token' )
328318 raise ex
329319
330320
0 commit comments