Add support for binary data to GStore
[platform/core/security/key-manager.git] / src / manager / service / ckm-logic.cpp
index b6ed4f5..728bfc5 100644 (file)
 #include <file-system.h>
 #include <ckm-logic.h>
 #include <key-impl.h>
+#include <key-aes-impl.h>
 #include <certificate-config.h>
 #include <certificate-store.h>
-
-#include <sw-backend/crypto-service.h>
+#include <dirent.h>
+#include <algorithm>
+#include <InitialValuesFile.h>
+#include <sw-backend/store.h>
+#include <generic-backend/exception.h>
 
 namespace {
-const char * const CERT_SYSTEM_DIR  = "/etc/ssl/certs";
-const uid_t        SYSTEM_DB_UID    = 0;
-const char * const SYSTEM_DB_PASSWD = "cAtRugU7";
+const char * const CERT_SYSTEM_DIR          = "/etc/ssl/certs";
+const char * const INIT_VALUES_DIR          = "/opt/data/ckm/initial_values/";
+const char * const INIT_VALUES_XSD          = "/usr/share/ckm/initial_values.xsd";
+const char * const INIT_VALUES_FILE_SUFFIX  = ".xml";
+const char * const SYSTEM_DB_PASSWD         = "cAtRugU7";
 
 bool isLabelValid(const CKM::Label &label) {
     // TODO: copy code from libprivilege control (for check smack label)
@@ -53,11 +59,50 @@ bool isNameValid(const CKM::Name &name) {
 
 namespace CKM {
 
+const uid_t CKMLogic::SYSTEM_DB_UID = 0;
+
 CKMLogic::CKMLogic()
 {
     CertificateConfig::addSystemCertificateDir(CERT_SYSTEM_DIR);
 
     m_accessControl.updateCCMode();
+
+    // make initial file list
+    std::vector<std::string> filesToParse;
+    DIR *dp = opendir(INIT_VALUES_DIR);
+    if(dp)
+    {
+        struct dirent *entry;
+        while ((entry = readdir(dp)))
+        {
+            std::string filename = std::string(entry->d_name);
+
+            // check if XML file
+            std::string lowercaseFilename = filename;
+            std::transform(lowercaseFilename.begin(), lowercaseFilename.end(), lowercaseFilename.begin(), ::tolower);
+            if(lowercaseFilename.find(INIT_VALUES_FILE_SUFFIX) == std::string::npos)
+                continue;
+
+            filesToParse.push_back(std::string(INIT_VALUES_DIR) + filename);
+        }
+        closedir(dp);
+    }
+
+    // parse
+    for(const auto & file : filesToParse)
+    {
+        InitialValues::InitialValuesFile xmlFile(file.c_str(), *this);
+        int rc = xmlFile.Validate(INIT_VALUES_XSD);
+        if(rc == XML::Parser::PARSE_SUCCESS)
+        {
+            rc = xmlFile.Parse();
+            if(rc != XML::Parser::PARSE_SUCCESS)
+                LogError("invalid initial values file: " << file << ", parsing code: " << rc);
+        }
+        else
+            LogError("invalid initial values file: " << file << ", validation code: " << rc);
+        unlink(file.c_str());
+    }
 }
 
 CKMLogic::~CKMLogic(){}
@@ -117,18 +162,8 @@ int CKMLogic::unlockDatabase(uid_t user, const Password & password)
                 handle.database.deleteKey(appSmackLabel);
             }
         }
-    } catch (const KeyProvider::Exception::PassWordError &e) {
-        LogError("Incorrect Password " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("Error in KeyProvider " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("FileSystem error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -154,15 +189,15 @@ UserData & CKMLogic::selectDatabase(const Credentials &cred, const Label &incomi
     if ( !m_accessControl.isSystemService(cred) )
     {
         if (0 == m_userDataMap.count(cred.clientUid))
-            ThrowMsg(Exception::DatabaseLocked, "database with UID: " << cred.clientUid << " locked");
+            ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked");
 
-        if (0 != incoming_label.compare(LABEL_SYSTEM_DB))
+        if (0 != incoming_label.compare(OWNER_ID_SYSTEM))
             return m_userDataMap[cred.clientUid];
     }
 
     // system database selected, modify the label
     if (CKM_API_SUCCESS != unlockSystemDB() )
-        ThrowMsg(Exception::DatabaseLocked, "can not unlock system database");
+        ThrowErr(Exc::DatabaseLocked, "can not unlock system database");
     return m_userDataMap[SYSTEM_DB_UID];
 }
 
@@ -242,15 +277,8 @@ RawBuffer CKMLogic::changeUserPassword(
     try
     {
         retCode = changeUserPasswordHelper(user, oldPassword, newPassword);
-    } catch (const KeyProvider::Exception::PassWordError &e) {
-        LogError("Incorrect Password " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("Error in KeyProvider " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -289,9 +317,8 @@ RawBuffer CKMLogic::resetUserPassword(
     int retCode = CKM_API_SUCCESS;
     try {
         retCode = resetUserPasswordHelper(user, newPassword);
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -327,9 +354,8 @@ RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel) {
     } catch (const DB::Crypto::Exception::TransactionError &e) {
         LogError("DB::Crypto transaction failed with message " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -346,7 +372,7 @@ int CKMLogic::checkSaveConditions(
 {
     // verify name and label are correct
     if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
-        LogWarning("Invalid parameter passed to key-manager");
+        LogDebug("Invalid parameter passed to key-manager");
         return CKM_API_ERROR_INPUT_PARAM;
     }
 
@@ -354,7 +380,7 @@ int CKMLogic::checkSaveConditions(
     int access_ec = m_accessControl.canSave(cred, ownerLabel);
     if( access_ec != CKM_API_SUCCESS)
     {
-        LogWarning("label " << cred.smackLabel << " can not save rows using label " << ownerLabel);
+        LogDebug("label " << cred.smackLabel << " can not save rows using label " << ownerLabel);
         return access_ec;
     }
 
@@ -391,7 +417,10 @@ DB::Row CKMLogic::createEncryptedRow(
     const RawBuffer &data,
     const Policy &policy) const
 {
-    DB::Row row(name, label, static_cast<int>(policy.extractable), dataType, data, static_cast<int>(data.size()));
+    Crypto::GStore& store = m_decider.getStore(dataType, policy.extractable);
+    Token token = store.import(dataType, data);
+
+    DB::Row row(std::move(token), name, label, static_cast<int>(policy.extractable));
 
     // do not encrypt data with password during cc_mode on
     if(m_accessControl.isCCMode()) {
@@ -402,34 +431,49 @@ DB::Row CKMLogic::createEncryptedRow(
     return row;
 }
 
-int CKMLogic::verifyBinaryData(DataType dataType, const RawBuffer &input_data) const
+int CKMLogic::verifyBinaryData(DataType dataType, RawBuffer &input_data) const
+{
+    RawBuffer dummy;
+    return toBinaryData(dataType, input_data, dummy);
+}
+
+int CKMLogic::toBinaryData(DataType dataType,
+                           const RawBuffer &input_data,
+                           RawBuffer &output_data) const
 {
     // verify the data integrity
     if (dataType.isKey())
     {
-        KeyShPtr output_key = CKM::Key::create(input_data);
+        KeyShPtr output_key;
+        if(dataType.isSKey())
+            output_key = CKM::Key::createAES(input_data);
+        else
+            output_key = CKM::Key::create(input_data);
         if(output_key.get() == NULL)
         {
-            LogError("provided binary data is not valid key data");
+            LogDebug("provided binary data is not valid key data");
             return CKM_API_ERROR_INPUT_PARAM;
         }
+        output_data = output_key->getDER();
     }
     else if (dataType.isCertificate() || dataType.isChainCert())
     {
         CertificateShPtr cert = CKM::Certificate::create(input_data, DataFormat::FORM_DER);
         if(cert.get() == NULL)
         {
-            LogError("provided binary data is not valid certificate data");
+            LogDebug("provided binary data is not valid certificate data");
             return CKM_API_ERROR_INPUT_PARAM;
         }
+        output_data = cert->getDER();
     }
+    else
+        output_data = input_data;
     // TODO: add here BINARY_DATA verification, i.e: max size etc.
     return CKM_API_SUCCESS;
 }
 
-RawBuffer CKMLogic::saveData(
+int CKMLogic::verifyAndSaveDataHelper(
     const Credentials &cred,
-    int commandId,
     const Name &name,
     const Label &label,
     const RawBuffer &data,
@@ -440,34 +484,62 @@ RawBuffer CKMLogic::saveData(
 
     try {
         // check if data is correct
-        retCode = verifyBinaryData(dataType, data);
+        RawBuffer binaryData;
+        retCode = toBinaryData(dataType, data, binaryData);
         if(retCode == CKM_API_SUCCESS)
         {
-            retCode = saveDataHelper(cred, name, label, dataType, data, policy);
+            retCode = saveDataHelper(cred, name, label, dataType, binaryData, policy);
         }
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("KeyProvider failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::InternalError &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
     } catch (const DB::Crypto::Exception::TransactionError &e) {
         LogError("DB::Crypto transaction failed with message " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const FileSystem::Exception::Base &e) {
-        LogError("Error in FileSystem " << e.GetMessage());
-        retCode = CKM_API_ERROR_FILE_SYSTEM;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
     }
+    return retCode;
+}
+
+int CKMLogic::getKeyForService(
+        const Credentials &cred,
+        const Name &name,
+        const Label &label,
+        const Password &pass,
+        Crypto::GObjShPtr &key)
+{
+    DB::Row row;
+    try {
+        // Key is for internal service use. It won't be exported to the client
+        int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, label, pass, row);
+        if (retCode == CKM_API_SUCCESS)
+            key = m_decider.getStore(row).getObject(row);
+        return retCode;
+    } catch (const DB::Crypto::Exception::Base &e) {
+        LogError("DB::Crypto failed with message: " << e.GetMessage());
+        return CKM_API_ERROR_DB_ERROR;
+    } catch (const Exc::Exception &e) {
+        return e.error();
+    } catch (const CKM::Exception &e) {
+        LogError("CKM::Exception: " << e.GetMessage());
+        return CKM_API_ERROR_SERVER_ERROR;
+    }
+}
 
+RawBuffer CKMLogic::saveData(
+    const Credentials &cred,
+    int commandId,
+    const Name &name,
+    const Label &label,
+    const RawBuffer &data,
+    DataType dataType,
+    const PolicySerializable &policy)
+{
+    int retCode = verifyAndSaveDataHelper(cred, name, label, data, dataType, policy);
     auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
                                              commandId,
                                              retCode,
@@ -532,12 +604,8 @@ RawBuffer CKMLogic::savePKCS12(
     int retCode = CKM_API_ERROR_UNKNOWN;
     try {
         retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy);
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("KeyProvider failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const DB::Crypto::Exception::InternalError &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
@@ -566,7 +634,7 @@ int CKMLogic::removeDataHelper(
     // use client label if not explicitly provided
     const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
     if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
-        LogError("Invalid label or name format");
+        LogDebug("Invalid label or name format");
         return CKM_API_ERROR_INPUT_PARAM;
     }
 
@@ -583,15 +651,38 @@ int CKMLogic::removeDataHelper(
         return retCode;
     }
 
-    auto erased = handler.database.deleteRow(name, ownerLabel);
-    // check if the data existed or not
-    if(erased)
-        transaction.commit();
-    else {
-        LogError("No row for given name and label");
+    // get all matching rows
+    DB::RowVector rows;
+    handler.database.getRows(name, ownerLabel, DataType::DB_FIRST, DataType::DB_LAST, rows);
+    if (rows.empty()) {
+        LogDebug("No row for given name and label");
         return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
     }
 
+    // load app key if needed
+    retCode = loadAppKey(handler, rows.front().ownerLabel);
+    if(CKM_API_SUCCESS != retCode)
+        return retCode;
+
+    // destroy it in store
+    for(auto& r : rows) {
+        /*
+         * TODO: If row is encrypted with user password we won't be able to decrypt it (tz id).
+         * Encryption/decryption with user password and with app key should both be done inside the
+         * store (import, getKey and generateXKey).
+         */
+        try {
+            handler.crypto.decryptRow(Password(), r);
+        } catch (const Exc::AuthenticationFailed&) {
+            LogDebug("Authentication failed when removing data. Ignored.");
+        }
+        m_decider.getStore(r.dataType, r.exportable).destroy(r);
+    }
+
+    // delete row in db
+    handler.database.deleteRow(name, ownerLabel);
+    transaction.commit();
+
     return CKM_API_SUCCESS;
 }
 
@@ -607,10 +698,9 @@ RawBuffer CKMLogic::removeData(
     {
         retCode = removeDataHelper(cred, name, label);
     }
-    catch (const CKMLogic::Exception::DatabaseLocked &e)
+    catch (const Exc::Exception &e)
     {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+        retCode = e.error();
     }
     catch (const CKM::Exception &)
     {
@@ -646,7 +736,7 @@ int CKMLogic::readSingleRow(const Name &name,
     }
 
     if(!row_optional) {
-        LogError("No row for given name, label and type");
+        LogDebug("No row for given name, label and type");
         return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
     } else {
         row = *row_optional;
@@ -690,7 +780,7 @@ int CKMLogic::readMultiRow(const Name &name,
     }
 
     if(!output.size()) {
-        LogError("No row for given name, label and type");
+        LogDebug("No row for given name, label and type");
         return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
     }
 
@@ -744,18 +834,12 @@ int CKMLogic::readDataHelper(
     if(CKM_API_SUCCESS != retCode)
         return retCode;
 
+    // load app key if needed
+    retCode = loadAppKey(handler, firstRow.ownerLabel);
+    if(CKM_API_SUCCESS != retCode)
+        return retCode;
+
     // decrypt row
-    if (!handler.crypto.haveKey(firstRow.ownerLabel)) {
-        RawBuffer key;
-        auto key_optional = handler.database.getKey(firstRow.ownerLabel);
-        if(!key_optional) {
-            LogError("No key for given label in database");
-            return CKM_API_ERROR_DB_ERROR;
-        }
-        key = *key_optional;
-        key = handler.keyProvider.getPureDEK(key);
-        handler.crypto.pushKey(firstRow.ownerLabel, key);
-    }
     for(auto &row : rows)
         handler.crypto.decryptRow(password, row);
 
@@ -790,18 +874,12 @@ int CKMLogic::readDataHelper(
     if(CKM_API_SUCCESS != retCode)
         return retCode;
 
+    // load app key if needed
+    retCode = loadAppKey(handler, row.ownerLabel);
+    if(CKM_API_SUCCESS != retCode)
+        return retCode;
+
     // decrypt row
-    if (!handler.crypto.haveKey(row.ownerLabel)) {
-        RawBuffer key;
-        auto key_optional = handler.database.getKey(row.ownerLabel);
-        if(!key_optional) {
-            LogError("No key for given label in database");
-            return CKM_API_ERROR_DB_ERROR;
-        }
-        key = *key_optional;
-        key = handler.keyProvider.getPureDEK(key);
-        handler.crypto.pushKey(row.ownerLabel, key);
-    }
     handler.crypto.decryptRow(password, row);
 
     return CKM_API_SUCCESS;
@@ -820,21 +898,11 @@ RawBuffer CKMLogic::getData(
 
     try {
         retCode = readDataHelper(true, cred, dataType, name, label, password, row);
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("KeyProvider failed with error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -915,22 +983,11 @@ RawBuffer CKMLogic::getPKCS12(
         // prepare response
         if(retCode == CKM_API_SUCCESS)
             output = PKCS12Serializable(privKey, cert, caChain);
-
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("KeyProvider failed with error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -994,7 +1051,7 @@ RawBuffer CKMLogic::getDataList(
         {
             // lookup system DB
             retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
-                                                    LABEL_SYSTEM_DB),
+                                                    OWNER_ID_SYSTEM),
                                         dataType,
                                         systemVector);
         }
@@ -1041,7 +1098,7 @@ int CKMLogic::saveDataHelper(
 
     // use client label if not explicitly provided
     const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
-    if( m_accessControl.isSystemService(cred) && ownerLabel.compare(LABEL_SYSTEM_DB)!=0)
+    if( m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM)!=0)
         return CKM_API_ERROR_INPUT_PARAM;
 
     // check if save is possible
@@ -1070,7 +1127,7 @@ int CKMLogic::saveDataHelper(
 
     // use client label if not explicitly provided
     const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
-    if( m_accessControl.isSystemService(cred) && ownerLabel.compare(LABEL_SYSTEM_DB)!=0)
+    if( m_accessControl.isSystemService(cred) && ownerLabel.compare(OWNER_ID_SYSTEM)!=0)
         return CKM_API_ERROR_INPUT_PARAM;
 
     // check if save is possible
@@ -1093,10 +1150,30 @@ int CKMLogic::saveDataHelper(
 }
 
 
+int CKMLogic::createKeyAESHelper(
+    const Credentials &cred,
+    const int size,
+    const Name &name,
+    const Label &label,
+    const PolicySerializable &policy)
+{
+    CryptoAlgorithm keyGenAlgorithm;
+    keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::AES_GEN);
+    keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, size);
+    Token key = m_decider.getStore(DataType::KEY_AES, policy.extractable).generateSKey(keyGenAlgorithm);
+
+    return saveDataHelper(cred,
+                          name,
+                          label,
+                          DataType::KEY_AES,
+                          key.data,
+                          policy);
+}
+
+
 int CKMLogic::createKeyPairHelper(
     const Credentials &cred,
-    const KeyType key_type,
-    const int additional_param,
+    const CryptoAlgorithmSerializable & keyGenParams,
     const Name &namePrivate,
     const Label &labelPrivate,
     const Name &namePublic,
@@ -1107,46 +1184,26 @@ int CKMLogic::createKeyPairHelper(
     auto &handlerPriv = selectDatabase(cred, labelPrivate);
     auto &handlerPub = selectDatabase(cred, labelPublic);
 
+    AlgoType keyType = AlgoType::RSA_GEN;
+    if(!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
+        ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
+    DataType dt(keyType);
+    if(!dt.isKey())
+        ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
 
-    int retCode;
-    KeyImpl prv, pub;
-    switch(key_type)
-    {
-        case KeyType::KEY_RSA_PUBLIC:
-        case KeyType::KEY_RSA_PRIVATE:
-            retCode = Crypto::SW::CryptoService::createKeyPairRSA(additional_param, prv, pub);
-            break;
-
-        case KeyType::KEY_DSA_PUBLIC:
-        case KeyType::KEY_DSA_PRIVATE:
-            retCode = Crypto::SW::CryptoService::createKeyPairDSA(additional_param, prv, pub);
-            break;
-
-        case KeyType::KEY_ECDSA_PUBLIC:
-        case KeyType::KEY_ECDSA_PRIVATE:
-            retCode = Crypto::SW::CryptoService::createKeyPairECDSA(static_cast<ElipticCurve>(additional_param), prv, pub);
-            break;
-
-        default:
-            return CKM_API_ERROR_INPUT_PARAM;
-    }
-
-    if (CKM_CRYPTO_CREATEKEY_SUCCESS != retCode)
-    {
-        LogDebug("CryptoService error with code: " << retCode);
-        return CKM_API_ERROR_SERVER_ERROR; // TODO error code
-    }
+    bool exportable = policyPrivate.extractable || policyPublic.extractable;
+    TokenPair keys = m_decider.getStore(dt, exportable).generateAKey(keyGenParams);
 
     DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
     // in case the same database is used for private and public - the second
     // transaction will not be executed
     DB::Crypto::Transaction transactionPub(&handlerPub.database);
 
-    retCode = saveDataHelper(cred,
+    int retCode = saveDataHelper(cred,
                              namePrivate,
                              labelPrivate,
-                             DataType(prv.getType()),
-                             prv.getDER(),
+                             keys.first.dataType,
+                             keys.first.data,
                              policyPrivate);
     if (CKM_API_SUCCESS != retCode)
         return retCode;
@@ -1154,23 +1211,21 @@ int CKMLogic::createKeyPairHelper(
     retCode = saveDataHelper(cred,
                              namePublic,
                              labelPublic,
-                             DataType(pub.getType()),
-                             pub.getDER(),
+                             keys.second.dataType,
+                             keys.second.data,
                              policyPublic);
     if (CKM_API_SUCCESS != retCode)
         return retCode;
 
     transactionPub.commit();
     transactionPriv.commit();
-
-    return retCode;
+    return CKM_API_SUCCESS;
 }
 
 RawBuffer CKMLogic::createKeyPair(
     const Credentials &cred,
-    LogicCommand protocol_cmd,
     int commandId,
-    const int additional_param,
+    const CryptoAlgorithmSerializable & keyGenParams,
     const Name &namePrivate,
     const Label &labelPrivate,
     const Name &namePublic,
@@ -1180,51 +1235,63 @@ RawBuffer CKMLogic::createKeyPair(
 {
     int retCode = CKM_API_SUCCESS;
 
-    KeyType key_type = KeyType::KEY_NONE;
-    switch(protocol_cmd)
-    {
-        case LogicCommand::CREATE_KEY_PAIR_RSA:
-            key_type = KeyType::KEY_RSA_PUBLIC;
-            break;
-        case LogicCommand::CREATE_KEY_PAIR_DSA:
-            key_type = KeyType::KEY_DSA_PUBLIC;
-            break;
-        case LogicCommand::CREATE_KEY_PAIR_ECDSA:
-            key_type = KeyType::KEY_ECDSA_PUBLIC;
-            break;
-        default:
-            break;
-    }
-
     try {
         retCode = createKeyPairHelper(
                         cred,
-                        key_type,
-                        additional_param,
+                        keyGenParams,
                         namePrivate,
                         labelPrivate,
                         namePublic,
                         labelPublic,
                         policyPrivate,
                         policyPublic);
+    } catch(const Exc::Exception &e) {
+        retCode = e.error();
     } catch (DB::Crypto::Exception::TransactionError &e) {
         LogDebug("DB::Crypto error: transaction error: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (CKM::CryptoLogic::Exception::Base &e) {
-        LogDebug("CryptoLogic error: " << e.GetMessage());
+    } catch (DB::Crypto::Exception::InternalError &e) {
+        LogDebug("DB::Crypto internal error: " << e.GetMessage());
+        retCode = CKM_API_ERROR_DB_ERROR;
+    } catch (const CKM::Exception &e) {
+        LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
+    }
+
+    return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
+                                    commandId, retCode).Pop();
+}
+
+RawBuffer CKMLogic::createKeyAES(
+    const Credentials &cred,
+    int commandId,
+    const int size,
+    const Name &name,
+    const Label &label,
+    const PolicySerializable &policy)
+{
+    int retCode = CKM_API_SUCCESS;
+
+    try {
+        retCode = createKeyAESHelper(cred, size, name, label, policy);
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
+    } catch (std::invalid_argument &e) {
+        LogDebug("invalid argument error: " << e.what());
+        retCode = CKM_API_ERROR_INPUT_PARAM;
+    } catch (DB::Crypto::Exception::TransactionError &e) {
+        LogDebug("DB::Crypto error: transaction error: " << e.GetMessage());
+        retCode = CKM_API_ERROR_DB_ERROR;
     } catch (DB::Crypto::Exception::InternalError &e) {
         LogDebug("DB::Crypto internal error: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
     } catch (const CKM::Exception &e) {
         LogError("CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
     }
 
-    return MessageBuffer::Serialize(static_cast<int>(protocol_cmd), commandId, retCode).Pop();
+    return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
+                                    commandId, retCode).Pop();
 }
 
 int CKMLogic::readCertificateHelper(
@@ -1264,10 +1331,18 @@ int CKMLogic::getCertificateChainHelper(
     if (cert.empty())
         return CKM_API_ERROR_INPUT_PARAM;
 
-    for (auto &e: untrustedCertificates)
-        untrustedCertVector.push_back(CertificateImpl(e, DataFormat::FORM_DER));
-    for (auto &e: trustedCertificates)
-        trustedCertVector.push_back(CertificateImpl(e, DataFormat::FORM_DER));
+    for (auto &e: untrustedCertificates) {
+        CertificateImpl c(e, DataFormat::FORM_DER);
+        if(c.empty())
+            return CKM_API_ERROR_INPUT_PARAM;
+        untrustedCertVector.push_back(std::move(c));
+    }
+    for (auto &e: trustedCertificates) {
+        CertificateImpl c(e, DataFormat::FORM_DER);
+        if(c.empty())
+            return CKM_API_ERROR_INPUT_PARAM;
+        trustedCertVector.push_back(std::move(c));
+    }
 
     CertificateStore store;
     int retCode = store.verifyCertificate(cert,
@@ -1340,9 +1415,8 @@ RawBuffer CKMLogic::getCertificateChain(
                                             trustedCertificates,
                                             useTrustedSystemCertificates,
                                             chainRawVector);
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
@@ -1378,18 +1452,11 @@ RawBuffer CKMLogic::getCertificateChain(
                                             trustedCertificates,
                                             useTrustedSystemCertificates,
                                             chainRawVector);
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const std::exception& e) {
         LogError("STD exception " << e.what());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1415,36 +1482,23 @@ RawBuffer CKMLogic::createSignature(
         const RSAPaddingAlgorithm padding)
 {
     DB::Row row;
-    Crypto::SW::CryptoService cs;
     RawBuffer signature;
+    CryptoAlgorithm cryptoAlg;
+    cryptoAlg.setParam(ParamName::SV_HASH_ALGO, hash);
+    cryptoAlg.setParam(ParamName::SV_RSA_PADDING, padding);
 
     int retCode = CKM_API_SUCCESS;
 
     try {
         retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName, ownerLabel, password, row);
-        if(retCode == CKM_API_SUCCESS)
-        {
-            KeyImpl keyParsed(row.data, Password());
-            if (keyParsed.empty())
-                retCode = CKM_API_ERROR_SERVER_ERROR;
-            else
-                retCode = cs.createSignature(keyParsed, message, hash, padding, signature);
+        if(retCode == CKM_API_SUCCESS) {
+            signature = m_decider.getStore(row).getObject(row)->sign(cryptoAlg, message);
         }
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("KeyProvider failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const CKM::Exception &e) {
         LogError("Unknown CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1471,55 +1525,28 @@ RawBuffer CKMLogic::verifySignature(
     int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
 
     try {
-        do {
-            Crypto::SW::CryptoService cs;
-            DB::Row row;
-            KeyImpl key;
-
-            // try certificate first - looking for a public key.
-            // in case of PKCS, pub key from certificate will be found first
-            // rather than private key from the same PKCS.
-            retCode = readDataHelper(false, cred, DataType::CERTIFICATE, publicKeyOrCertName, ownerLabel, password, row);
-            if (retCode == CKM_API_SUCCESS) {
-                CertificateImpl cert(row.data, DataFormat::FORM_DER);
-                key = cert.getKeyImpl();
-            } else if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
-                retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, publicKeyOrCertName, ownerLabel, password, row);
-                if (retCode != CKM_API_SUCCESS)
-                    break;
-                key = KeyImpl(row.data);
-            } else {
-                break;
-            }
-
-            if (key.empty()) {
-                retCode = CKM_API_ERROR_SERVER_ERROR;
-                break;
-            }
+        DB::Row row;
+
+        CryptoAlgorithm params;
+        params.setParam(ParamName::SV_HASH_ALGO, hash);
+        params.setParam(ParamName::SV_RSA_PADDING, padding);
+
+        // try certificate first - looking for a public key.
+        // in case of PKCS, pub key from certificate will be found first
+        // rather than private key from the same PKCS.
+        retCode = readDataHelper(false, cred, DataType::CERTIFICATE, publicKeyOrCertName, ownerLabel, password, row);
+        if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
+            retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, publicKeyOrCertName, ownerLabel, password, row);
+        }
 
-            retCode = cs.verifySignature(key, message, signature, hash, padding);
-        } while(0);
-    } catch (const Crypto::SW::CryptoService::Exception::Crypto_internal &e) {
-        LogError("KeyProvider failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const Crypto::SW::CryptoService::Exception::opensslError &e) {
-        LogError("KeyProvider failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const KeyProvider::Exception::Base &e) {
-        LogError("KeyProvider failed with error: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
-    } catch (const CryptoLogic::Exception::DecryptDBRowError &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_AUTHENTICATION_FAILED;
-    } catch (const CryptoLogic::Exception::Base &e) {
-        LogError("CryptoLogic failed with message: " << e.GetMessage());
-        retCode = CKM_API_ERROR_SERVER_ERROR;
+        if (retCode == CKM_API_SUCCESS) {
+            retCode = m_decider.getStore(row).getObject(row)->verify(params, message, signature);
+        }
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } catch (const DB::Crypto::Exception::Base &e) {
         LogError("DB::Crypto failed with message: " << e.GetMessage());
         retCode = CKM_API_ERROR_DB_ERROR;
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
     } catch (const CKM::Exception &e) {
         LogError("Unknown CKM::Exception: " << e.GetMessage());
         retCode = CKM_API_ERROR_SERVER_ERROR;
@@ -1556,7 +1583,7 @@ int CKMLogic::setPermissionHelper(
         return CKM_API_ERROR_INPUT_PARAM;
 
     // system database does not support write/remove permissions
-    if ((0 == ownerLabel.compare(LABEL_SYSTEM_DB)) &&
+    if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) &&
         (permissionMask & Permission::REMOVE))
         return CKM_API_ERROR_INPUT_PARAM;
 
@@ -1596,9 +1623,8 @@ RawBuffer CKMLogic::setPermission(
     int retCode;
     Try {
         retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
-    } catch (const CKMLogic::Exception::DatabaseLocked &e) {
-        LogError("Error " << e.GetMessage());
-        retCode = CKM_API_ERROR_DB_LOCKED;
+    } catch (const Exc::Exception &e) {
+        retCode = e.error();
     } Catch (CKM::Exception) {
         LogError("Error in set row!");
         retCode = CKM_API_ERROR_DB_ERROR;
@@ -1607,5 +1633,21 @@ RawBuffer CKMLogic::setPermission(
     return MessageBuffer::Serialize(command, msgID, retCode).Pop();
 }
 
+int CKMLogic::loadAppKey(UserData& handle, const Label& appLabel)
+{
+    if (!handle.crypto.haveKey(appLabel)) {
+        RawBuffer key;
+        auto key_optional = handle.database.getKey(appLabel);
+        if(!key_optional) {
+            LogError("No key for given label in database");
+            return CKM_API_ERROR_DB_ERROR;
+        }
+        key = *key_optional;
+        key = handle.keyProvider.getPureDEK(key);
+        handle.crypto.pushKey(appLabel, key);
+    }
+    return CKM_API_SUCCESS;
+}
+
 } // namespace CKM