From fa7722bfc5bb615d7d63ca8367b5c4b5e647d5d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Douglas=20Mendiz=C3=A1bal?= Date: Tue, 23 Feb 2021 08:08:11 -0600 Subject: [PATCH] Fix PKCS#11 reinitialization after failure This patch fixes an error condition where the PCKS#11 object is lost afte multiple failures from the PKCS#11 device. Without this patch Barbican can enter an error state where the PKCS11 object is deallocated and is unable to recover returning 500s until the process is restarted. Story: 2008649 Task: 41913 Change-Id: Ieab0f152ef307fb9311b92f0ad8bd0032e78269e --- barbican/plugin/crypto/p11_crypto.py | 5 ++++- barbican/plugin/crypto/pkcs11.py | 3 ++- ...-2008649-reinitialize-pkcs11-object-4c0dc51c83288c21.yaml | 5 +++++ 3 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 releasenotes/notes/fix-story-2008649-reinitialize-pkcs11-object-4c0dc51c83288c21.yaml diff --git a/barbican/plugin/crypto/p11_crypto.py b/barbican/plugin/crypto/p11_crypto.py index 40fa1a4bb..a9f7606a4 100644 --- a/barbican/plugin/crypto/p11_crypto.py +++ b/barbican/plugin/crypto/p11_crypto.py @@ -184,6 +184,8 @@ class P11CryptoPlugin(plugin.CryptoPluginBase): # Wrap pkcs11 calls to enable a single retry when exceptions are raised # that can be fixed by reinitializing the pkcs11 library try: + if self.pkcs11 is None: + self._reinitialize_pkcs11() return func(*args, **kwargs) except (exception.PKCS11Exception) as pe: LOG.warning("Reinitializing PKCS#11 library: %s", pe) @@ -335,7 +337,8 @@ class P11CryptoPlugin(plugin.CryptoPluginBase): ) def _reinitialize_pkcs11(self): - self.pkcs11.finalize() + if self.pkcs11 is not None: + self.pkcs11.finalize() self.pkcs11 = None with self.caching_session_lock: diff --git a/barbican/plugin/crypto/pkcs11.py b/barbican/plugin/crypto/pkcs11.py index 4083c72ea..5cd55eeeb 100644 --- a/barbican/plugin/crypto/pkcs11.py +++ b/barbican/plugin/crypto/pkcs11.py @@ -31,6 +31,7 @@ CKMechanism = collections.namedtuple("CKMechanism", ["mech", "cffivals"]) Token = collections.namedtuple("Token", ["slot_id", "label", "serial_number"]) CKR_OK = 0 +CKR_CRYPTOKI_ALREADY_INITIALIZED = 0x00000191 CK_TRUE = 1 CKF_RW_SESSION = (1 << 1) CKF_SERIAL_SESSION = (1 << 2) @@ -867,7 +868,7 @@ class PKCS11(object): self._check_error(rv) def _check_error(self, value): - if value != CKR_OK: + if value != CKR_OK and value != CKR_CRYPTOKI_ALREADY_INITIALIZED: code = ERROR_CODES.get(value, 'CKR_????') hex_code = "{hex} {code}".format(hex=hex(value), code=code) diff --git a/releasenotes/notes/fix-story-2008649-reinitialize-pkcs11-object-4c0dc51c83288c21.yaml b/releasenotes/notes/fix-story-2008649-reinitialize-pkcs11-object-4c0dc51c83288c21.yaml new file mode 100644 index 000000000..0d04b4d2a --- /dev/null +++ b/releasenotes/notes/fix-story-2008649-reinitialize-pkcs11-object-4c0dc51c83288c21.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixed Story #2008649: Correctly reinitialize PKCS11 object after secondary + failures.