.net-corewindows-servicespkcs11interop

Pkcs11Interop empty slot list


I recently created a Console app which held the context of Pkcs11Interop library, along with HSM dll. It worked fine, however I needed to rewrite the code to Windows Service (I hosted it as gRPC service since it's .NET Core). After hosting WS, it ocurred that the slot list on factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, libraryPath, AppType.MultiThreaded).GetSlotList(SlotsType.WithOrWithoutTokenPresent).Find(slot => slot.SlotId == slotId) returns an empty list of slots, even though it returned list of 3 elements in console app.

    public Pkcs11Signature(string libraryPath, ulong slotId)
    {
        Pkcs11InteropFactories factories = new Pkcs11InteropFactories();
        _pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, libraryPath, AppType.MultiThreaded);
        _slot = _pkcs11Library.GetSlotList(SlotsType.WithOrWithoutTokenPresent).Find(slot => slot.SlotId == slotId);
    }
    
    public Pkcs11Signature Select(string alias, string certLabel, string pin, bool login)
    {
        List<CKA> pkAttributeKeys = new List<CKA>();
        pkAttributeKeys.Add(CKA.CKA_KEY_TYPE);
        pkAttributeKeys.Add(CKA.CKA_LABEL);
        pkAttributeKeys.Add(CKA.CKA_ID);
        List<CKA> certAttributeKeys = new List<CKA>();
        certAttributeKeys.Add(CKA.CKA_VALUE);
        certAttributeKeys.Add(CKA.CKA_LABEL);

        //CloseSession();            

        _session = _slot.OpenSession(SessionType.ReadWrite);
        if (login)
            _session.Login(CKU.CKU_USER, pin);

        ObjectAttributeFactory objectAttributeFactory = new ObjectAttributeFactory();

        List<IObjectAttribute> attributes = new List<IObjectAttribute>();
        attributes.Add(objectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
        List<IObjectHandle> keys = _session.FindAllObjects(attributes);

        bool found = false;
        foreach (IObjectHandle key in keys)
        {
            List<IObjectAttribute> keyAttributes = _session.GetAttributeValue(key, pkAttributeKeys);

            ulong type = keyAttributes[0].GetValueAsUlong();
            string encryptionAlgorithm;
            switch (type)
            {
                case (ulong)CKK.CKK_RSA:
                    encryptionAlgorithm = "RSA";
                    break;
                case (ulong)CKK.CKK_DSA:
                    encryptionAlgorithm = "DSA";
                    break;
                case (ulong)CKK.CKK_ECDSA:
                    encryptionAlgorithm = "ECDSA";
                    break;
                default:
                    continue;
            }

            string thisAlias = keyAttributes[1].GetValueAsString();

            if (thisAlias == null || thisAlias.Length == 0)
                thisAlias = keyAttributes[2].GetValueAsString();
            if (alias != null && !alias.Equals(thisAlias))
                continue;

            attributes.Clear();
            attributes.Add(objectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
            attributes.Add(objectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509));

            if (certLabel == null && thisAlias != null && thisAlias.Length > 0)
                certLabel = thisAlias;
            if (certLabel != null)
                attributes.Add(objectAttributeFactory.Create(CKA.CKA_LABEL, certLabel));

            List<IObjectHandle> certificates =_session.FindAllObjects(attributes);

            if (certificates.Count != 1)
                continue;

            IObjectHandle certificate = certificates[0];
            List<IObjectAttribute> certificateAttributes =_session.GetAttributeValue(certificate, certAttributeKeys);
            X509Certificate x509Certificate =
                new X509Certificate(X509CertificateStructure.GetInstance(certificateAttributes[0].GetValueAsByteArray()));

            List<X509Certificate> x509Certificates = new List<X509Certificate>();
            x509Certificates.Add(x509Certificate);
            attributes.Clear();
            attributes.Add(objectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE));
            attributes.Add(objectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509));
            List<IObjectHandle> otherCertificates =_session.FindAllObjects(attributes);
            foreach (IObjectHandle otherCertificate in otherCertificates)
            {
                if (!certificate.ObjectId.Equals(otherCertificate.ObjectId))
                {
                    certificateAttributes =_session.GetAttributeValue(otherCertificate, certAttributeKeys);
                    X509Certificate otherX509Certificate =
                        new X509Certificate(X509CertificateStructure.GetInstance(certificateAttributes[0].GetValueAsByteArray()));
                    x509Certificates.Add(otherX509Certificate);
                }
            }

            found = true;
            _alias = thisAlias;
            _encryptionAlgorithm = encryptionAlgorithm;
            _privateKeyHandle = key;
            _chain = x509Certificates.ToArray();
            break;
        }

        if (!found)
        {
            Console.WriteLine("Havent found");
            _alias = null;
            _encryptionAlgorithm = null;
            _privateKeyHandle = null;
            _chain = null;
        }

        return this;
    }

Executing the library:

    using (var signature = new Pkcs11Signature(@"C:\Program Files (x86)\hsm\hsm.dll", 3).
        Select(null, "CERT LABEL", "PIN", true)
    {
        (...DO THE WORK HERE...)
    }  

I've seen this, but changing the "Log On As" to "Local Service" for Windows Service gives no effect: C_GetSlotList Failing when called from IIS but not from IIS express


Solution

  • Pkcs11Interop returns slots received by calling C_GetSlotList function of unmanaged PKCS#11 library. So if you get 0 slots then C_GetSlotList returned 0 slots. You need to discuss this situation with the vendor of your PKCS#11 library who might know why their library does not see any slots.