Repository: privacyidea/privacyidea

Issue:
HSM CKR_SESSION_HANDLE_INVALID
# What did you try to do?

Use privacyIDEA with an HSM (aes module) Luna SA.

# What outcome did you expect?

Should work :-)

# What outcome did you experience?

At some not reproducable points we receive a **CKR_SESSION_HANDLE_INVALID (0x000000B3)**.

This happens here:

    [WARNING][privacyidea.lib.security.aeshsm:200] Decryption failed: CKR_SESSION_HANDLE_INVALID (0x000000B3)   
    [WARNING][privacyidea.lib.crypto:363] ERR707: Failed to decrypt after multiple retries.
 
or here

<pre>
ERROR in app: Exception on /auth [POST]
Traceback (most recent call last):
  File "/opt/privacyidea/lib/python2.7/site-packages/flask/app.py",
line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/privacyidea/lib/python2.7/site-packages/flask/app.py",
line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/privacyidea/lib/python2.7/site-packages/flask/app.py",
line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/privacyidea/lib/python2.7/site-packages/flask/app.py",
line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/privacyidea/lib/python2.7/site-packages/flask/app.py",
line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File
"/opt/privacyidea/lib/python2.7/site-packages/privacyidea/api/lib/postpo
licy.py",
line 102, in policy_wrapper
    response = wrapped_function(*args, **kwds)
  File
"/opt/privacyidea/lib/python2.7/site-packages/privacyidea/api/auth.py",
line
265, in get_auth_token
    nonce = geturandom(hex=True)
  File
"/opt/privacyidea/lib/python2.7/site-packages/privacyidea/lib/crypto.py"
,
line 500, in geturandom
    ret = hsm.random(length)
  File
"/opt/privacyidea/lib/python2.7/site-packages/privacyidea/lib/security/a
eshsm.py",
line 164, in random
    r_integers = self.session.generateRandom(length)
  File
"/opt/privacyidea/lib/python2.7/site-packages/PyKCS11/__init__.py",
line 1513, in generateRandom
    raise PyKCS11Error(rv)
PyKCS11Error: CKR_SESSION_HANDLE_INVALID (0x000000B3)
</pre>

# Configuration

* privacyIDEA Version: 2.21.4
* Installation method: RPM repo on RHEL7

## more details: 

* OS: RHEL 7
* Webserver: Apache. (Also only with one wsgi process and 15 threads)

# Todos

We might at least need to catch a pykcs11 error during random generation:

https://github.com/privacyidea/privacyidea/blob/master/privacyidea/lib/security/aeshsm.py#L169



Discussion:

Resolving patch:
diff --git a/privacyidea/lib/security/aeshsm.py b/privacyidea/lib/security/aeshsm.py
--- a/privacyidea/lib/security/aeshsm.py
+++ b/privacyidea/lib/security/aeshsm.py
@@ -104,6 +104,15 @@ def __init__(self, config=None):
         self.initialize_hsm()
 
     def initialize_hsm(self):
+        """
+        Initialize the HSM:
+        * initialize PKCS11 library
+        * login to HSM
+        * get session
+        :return:
+        """
+        # Reset the is_ready state, so that we login again.
+        self.is_ready = False
         self.pkcs11.lib.C_Initialize()
         if self.password:
             self._login()
@@ -166,7 +175,18 @@ def random(self, length):
         :param length: length of the random bytestring
         :return:
         """
-        r_integers = self.session.generateRandom(length)
+        retries = 0
+        while True:
+            try:
+                r_integers = self.session.generateRandom(length)
+                break
+            except PyKCS11.PyKCS11Error as exx:
+                log.warning(u"Generate Random failed: {0!s}".format(exx))
+                self.initialize_hsm()
+                retries += 1
+                if retries > MAX_RETRIES:
+                    raise HSMException("Failed to generate random number after multiple retries.")
+
         # convert the array of the random integers to a string
         return int_list_to_bytestring(r_integers)
 


Test patch: