How to manage a network down and avoid error with

2019-07-30 23:11发布

问题:

Using PKCS11Interop on Safenet HSMs, I got this error

"Method C_OpenSession returned 2147484548"

the error, in my documentation, is CKR_SMS_ERROR: "General error from secure messaging system - probably caused by HSM failure or network failure".

This confirm the problem it happens when the connectivity is lacking.

The problem is when this happens, the service isn't able to resume the communication when the connectivity is back, until I restart manually the service managing the HSM access.

When the service starts, I call this:

private Pkcs11 _pkcs11 = null;
private Slot _slot = null;
private Session _session = null;

public async void InitPkcs11()
{
    try
    {
        _pkcs11 = new Pkcs11(pathCryptoki, Inter_Settings.AppType);
        _slot = Inter_Helpers.GetUsableSlot(_pkcs11, nSlot);
        _session = _slot.OpenSession(SessionType.ReadOnly);
        _session.Login(CKU.CKU_USER, Inter_Settings.NormalUserPin);
    }
    catch (Exception e)
    {
        ...
    }
}

When I have to use the HSM, I call something like:

using (var LocalSession = _slot.OpenSession(SessionType.ReadOnly))
{
    ...
}

And, when I fail the communication due to a connectivity lack, I call a function to reset the connection and try to change the slot:

private bool switching = false;

public async void SwitchSlot()
{
    try
    {
        if (!switching)
        {
            switching = true;
            if (nSlot == 0)
            {
                nSlot = 2;
            }
            else
            {
                nSlot = 0;
            }
            _session.Logout();
            _slot.CloseAllSessions();
            _pkcs11.Dispose();
            InitPkcs11();
            switching = false;
        }
    }
    catch (Exception e)
    {
        ...
    }
}

But, this last snippet doens't work as expected: it tries to change the slot, but it fails always to communicate with the HSM (after a network down). If I restart the service manually (when the connectivity is back), it works like charms. So, I'm sure I'm doing something wrong in the SwitchSlot function, when I try to close the _session and open a new one.

Do you see any errors/misunderstoonding here?