2 * Copyright (c) 2014-2020 Samsung Electronics Co., Ltd. All rights reserved
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
18 * @author Bartlomiej Grzelewski (b.grzelewski@samsung.com)
20 * @brief Sample service implementation.
22 #include <dpl/serialization.h>
23 #include <dpl/log/log.h>
24 #include <ckm/ckm-error.h>
25 #include <ckm/ckm-type.h>
26 #include <key-provider.h>
27 #include <file-system.h>
28 #include <ckm-logic.h>
30 #include <key-aes-impl.h>
31 #include <certificate-config.h>
32 #include <certificate-store.h>
34 #include <sw-backend/store.h>
35 #include <generic-backend/exception.h>
36 #include <ss-migrate.h>
39 const char *const CERT_SYSTEM_DIR = CA_CERTS_DIR;
40 const char *const SYSTEM_DB_PASSWD = "cAtRugU7";
42 bool isClientValid(const CKM::ClientId &client)
44 if (client.find(CKM::ALIAS_SEPARATOR) != CKM::ClientId::npos)
50 bool isNameValid(const CKM::Name &name)
52 if (name.find(CKM::ALIAS_SEPARATOR) != CKM::Name::npos)
58 // keypair data type, having private key data type and public key data type
59 // private is assumed to be .first, public .second
60 using DataTypePair = std::pair<CKM::DataType, CKM::DataType>;
62 const std::map<CKM::AlgoType, DataTypePair> ALGO_TYPE_TO_DATA_TYPE_PAIR_MAP = {
63 { CKM::AlgoType::RSA_GEN, { CKM::DataType(CKM::KeyType::KEY_RSA_PRIVATE), CKM::DataType(CKM::KeyType::KEY_RSA_PUBLIC) } },
64 { CKM::AlgoType::DSA_GEN, { CKM::DataType(CKM::KeyType::KEY_DSA_PRIVATE), CKM::DataType(CKM::KeyType::KEY_DSA_PUBLIC) } },
65 { CKM::AlgoType::ECDSA_GEN, { CKM::DataType(CKM::KeyType::KEY_ECDSA_PRIVATE), CKM::DataType(CKM::KeyType::KEY_ECDSA_PUBLIC) } },
68 } // anonymous namespace
72 const uid_t CKMLogic::SYSTEM_DB_UID = 0;
73 const uid_t CKMLogic::ADMIN_USER_DB_UID = 5001;
77 CertificateConfig::addSystemCertificateDir(CERT_SYSTEM_DIR);
79 m_accessControl.updateCCMode();
82 CKMLogic::~CKMLogic() {}
84 void CKMLogic::loadDKEKFile(uid_t user, const Password &password)
86 auto &handle = m_userDataMap[user];
90 auto wrappedDKEK = fs.getDKEK();
92 if (wrappedDKEK.empty()) {
93 wrappedDKEK = KeyProvider::generateDomainKEK(std::to_string(user), password);
94 fs.saveDKEK(wrappedDKEK);
97 handle.keyProvider = KeyProvider(wrappedDKEK, password);
100 void CKMLogic::saveDKEKFile(uid_t user, const Password &password)
102 auto &handle = m_userDataMap[user];
105 fs.saveDKEK(handle.keyProvider.getWrappedDomainKEK(password));
108 void CKMLogic::migrateSecureStorageData(bool isAdminUser)
110 SsMigration::migrate(isAdminUser, [this](const std::string &name,
111 const Crypto::Data &data,
112 bool adminUserFlag) {
113 LogInfo("Migrate data called with name: " << name);
114 auto ownerId = adminUserFlag ? CLIENT_ID_ADMIN_USER : CLIENT_ID_SYSTEM;
115 auto uid = adminUserFlag ? ADMIN_USER_DB_UID : SYSTEM_DB_UID;
117 int ret = verifyAndSaveDataHelper(Credentials(uid, ownerId), name, ownerId, data,
118 PolicySerializable());
120 if (ret == CKM_API_ERROR_DB_ALIAS_EXISTS)
121 LogWarning("Alias already exist for migrated name: " << name);
122 else if (ret != CKM_API_SUCCESS)
123 LogError("Failed to migrate secure-storage data. name: " << name <<
128 int CKMLogic::unlockDatabase(uid_t user, const Password &password)
130 if (0 < m_userDataMap.count(user) &&
131 m_userDataMap[user].keyProvider.isInitialized())
132 return CKM_API_SUCCESS;
134 int retCode = CKM_API_SUCCESS;
137 auto &handle = m_userDataMap[user];
140 loadDKEKFile(user, password);
142 auto wrappedDatabaseDEK = fs.getDBDEK();
144 if (wrappedDatabaseDEK.empty()) {
145 wrappedDatabaseDEK = handle.keyProvider.generateDEK(std::to_string(user));
146 fs.saveDBDEK(wrappedDatabaseDEK);
149 RawBuffer key = handle.keyProvider.getPureDEK(wrappedDatabaseDEK);
151 handle.database = DB::Crypto(fs.getLegacyDBPath(), fs.getDBPath(), key);
152 handle.crypto = CryptoLogic();
154 if (!m_accessControl.isSystemService(user)) {
155 // remove data of removed apps during locked state
156 ClientIdVector removedApps = fs.clearRemovedsApps();
158 for (auto &app : removedApps) {
159 handle.crypto.removeKey(app);
160 handle.database.deleteKey(app);
164 if (user == SYSTEM_DB_UID && SsMigration::hasData())
165 migrateSecureStorageData(false);
166 else if (user == ADMIN_USER_DB_UID && SsMigration::hasData())
167 migrateSecureStorageData(true);
168 } catch (const Exc::Exception &e) {
170 } catch (const CKM::Exception &e) {
171 LogError("CKM::Exception: " << e.GetMessage());
172 retCode = CKM_API_ERROR_SERVER_ERROR;
175 if (CKM_API_SUCCESS != retCode)
176 m_userDataMap.erase(user);
181 int CKMLogic::unlockSystemDB()
183 return unlockDatabase(SYSTEM_DB_UID, SYSTEM_DB_PASSWD);
186 UserData &CKMLogic::selectDatabase(const Credentials &cred,
187 const ClientId &explicitOwner)
189 // if user trying to access system service - check:
190 // * if user database is unlocked [mandatory]
191 // * if not - proceed with regular user database
192 // * if explicit system database owner given -> switch to system DB
193 if (!m_accessControl.isSystemService(cred)) {
194 if (0 == m_userDataMap.count(cred.clientUid))
195 ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked");
197 if (0 != explicitOwner.compare(CLIENT_ID_SYSTEM))
198 return m_userDataMap[cred.clientUid];
201 // system database selected, modify the owner id
202 if (CKM_API_SUCCESS != unlockSystemDB())
203 ThrowErr(Exc::DatabaseLocked, "can not unlock system database");
205 return m_userDataMap[SYSTEM_DB_UID];
208 RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password)
210 int retCode = CKM_API_SUCCESS;
212 if (!m_accessControl.isSystemService(user))
213 retCode = unlockDatabase(user, password);
214 else // do not allow lock/unlock operations for system users
215 retCode = CKM_API_ERROR_INPUT_PARAM;
217 return MessageBuffer::Serialize(retCode).Pop();
220 RawBuffer CKMLogic::updateCCMode()
222 m_accessControl.updateCCMode();
223 return MessageBuffer::Serialize(CKM_API_SUCCESS).Pop();
226 RawBuffer CKMLogic::lockUserKey(uid_t user)
228 int retCode = CKM_API_SUCCESS;
230 if (!m_accessControl.isSystemService(user))
231 m_userDataMap.erase(user);
232 else // do not allow lock/unlock operations for system users
233 retCode = CKM_API_ERROR_INPUT_PARAM;
235 return MessageBuffer::Serialize(retCode).Pop();
238 RawBuffer CKMLogic::removeUserData(uid_t user)
240 if (m_accessControl.isSystemService(user))
241 user = SYSTEM_DB_UID;
243 m_userDataMap.erase(user);
245 const int retCode = FileSystem(user).removeUserData()
246 ? CKM_API_ERROR_FILE_SYSTEM
249 return MessageBuffer::Serialize(retCode).Pop();
252 int CKMLogic::changeUserPasswordHelper(uid_t user,
253 const Password &oldPassword,
254 const Password &newPassword)
256 // do not allow to change system database password
257 if (m_accessControl.isSystemService(user))
258 return CKM_API_ERROR_INPUT_PARAM;
260 loadDKEKFile(user, oldPassword);
261 saveDKEKFile(user, newPassword);
263 return CKM_API_SUCCESS;
266 RawBuffer CKMLogic::changeUserPassword(
268 const Password &oldPassword,
269 const Password &newPassword)
271 int retCode = CKM_API_SUCCESS;
274 retCode = changeUserPasswordHelper(user, oldPassword, newPassword);
275 } catch (const Exc::Exception &e) {
277 } catch (const CKM::Exception &e) {
278 LogError("CKM::Exception: " << e.GetMessage());
279 retCode = CKM_API_ERROR_SERVER_ERROR;
282 return MessageBuffer::Serialize(retCode).Pop();
285 int CKMLogic::resetUserPasswordHelper(
287 const Password &newPassword)
289 // do not allow to reset system database password
290 if (m_accessControl.isSystemService(user))
291 return CKM_API_ERROR_INPUT_PARAM;
293 int retCode = CKM_API_SUCCESS;
295 if (0 == m_userDataMap.count(user)) {
296 // Check if key exists. If exists we must return error
298 auto wrappedDKEKMain = fs.getDKEK();
300 if (!wrappedDKEKMain.empty())
301 retCode = CKM_API_ERROR_BAD_REQUEST;
303 saveDKEKFile(user, newPassword);
309 RawBuffer CKMLogic::resetUserPassword(
311 const Password &newPassword)
313 int retCode = CKM_API_SUCCESS;
316 retCode = resetUserPasswordHelper(user, newPassword);
317 } catch (const Exc::Exception &e) {
319 } catch (const CKM::Exception &e) {
320 LogError("CKM::Exception: " << e.GetMessage());
321 retCode = CKM_API_ERROR_SERVER_ERROR;
324 return MessageBuffer::Serialize(retCode).Pop();
327 RawBuffer CKMLogic::removeApplicationData(const ClientId &owner)
329 int retCode = CKM_API_SUCCESS;
333 retCode = CKM_API_ERROR_INPUT_PARAM;
335 UidVector uids = FileSystem::getUIDsFromDBFile();
337 for (auto userId : uids) {
338 if (0 == m_userDataMap.count(userId)) {
339 FileSystem fs(userId);
340 fs.addRemovedApp(owner);
342 auto &handle = m_userDataMap[userId];
343 handle.crypto.removeKey(owner);
344 handle.database.deleteKey(owner);
348 } catch (const Exc::Exception &e) {
350 } catch (const CKM::Exception &e) {
351 LogError("CKM::Exception: " << e.GetMessage());
352 retCode = CKM_API_ERROR_SERVER_ERROR;
355 return MessageBuffer::Serialize(retCode).Pop();
358 int CKMLogic::checkSaveConditions(
359 const Credentials &accessorCred,
362 const ClientId &owner)
364 // verify name and client are correct
365 if (!isNameValid(name) || !isClientValid(owner)) {
366 LogDebug("Invalid parameter passed to key-manager");
367 return CKM_API_ERROR_INPUT_PARAM;
370 // check if accessor is allowed to save owner's items
371 int access_ec = m_accessControl.canSave(accessorCred, owner);
373 if (access_ec != CKM_API_SUCCESS) {
374 LogDebug("accessor " << accessorCred.client << " can not save rows owned by " <<
379 // check if not a duplicate
380 if (handler.database.isNameOwnerPresent(name, owner))
381 return CKM_API_ERROR_DB_ALIAS_EXISTS;
383 // encryption section
384 if (!handler.crypto.haveKey(owner)) {
386 auto key_optional = handler.database.getKey(owner);
389 LogDebug("No Key in database found. Generating new one for client: " <<
391 got_key = handler.keyProvider.generateDEK(owner);
392 handler.database.saveKey(owner, got_key);
394 LogDebug("Key from DB");
395 got_key = *key_optional;
398 got_key = handler.keyProvider.getPureDEK(got_key);
399 handler.crypto.pushKey(owner, got_key);
402 return CKM_API_SUCCESS;
405 DB::Row CKMLogic::createEncryptedRow(
408 const ClientId &owner,
409 const Crypto::Data &data,
410 const Policy &policy)
412 Crypto::GStore &store = m_decider.getStore(data.type, policy);
414 // do not encrypt data with password during cc_mode on
415 Token token = store.import(data,
416 m_accessControl.isCCMode() ? "" : policy.password,
417 Crypto::EncryptionParams());
418 DB::Row row(std::move(token), name, owner,
419 static_cast<int>(policy.extractable));
420 crypto.encryptRow(row);
424 int CKMLogic::verifyBinaryData(Crypto::Data &input) const
427 return toBinaryData(input, dummy);
430 int CKMLogic::toBinaryData(const Crypto::Data &input,
431 Crypto::Data &output) const
433 // verify the data integrity
434 if (input.type.isKey()) {
437 if (input.type.isSKey())
438 output_key = CKM::Key::createAES(input.data);
440 output_key = CKM::Key::create(input.data);
442 if (output_key.get() == NULL) {
443 LogDebug("provided binary data is not valid key data");
444 return CKM_API_ERROR_INPUT_PARAM;
447 output = std::move(Crypto::Data(input.type, output_key->getDER()));
448 } else if (input.type.isCertificate() || input.type.isChainCert()) {
449 CertificateShPtr cert = CKM::Certificate::create(input.data,
450 DataFormat::FORM_DER);
452 if (cert.get() == NULL) {
453 LogDebug("provided binary data is not valid certificate data");
454 return CKM_API_ERROR_INPUT_PARAM;
457 output = std::move(Crypto::Data(input.type, cert->getDER()));
462 // TODO: add here BINARY_DATA verification, i.e: max size etc.
463 return CKM_API_SUCCESS;
466 int CKMLogic::verifyAndSaveDataHelper(
467 const Credentials &cred,
469 const ClientId &explicitOwner,
470 const Crypto::Data &data,
471 const PolicySerializable &policy)
473 int retCode = CKM_API_ERROR_UNKNOWN;
476 // check if data is correct
477 Crypto::Data binaryData;
478 retCode = toBinaryData(data, binaryData);
480 if (retCode != CKM_API_SUCCESS)
483 return saveDataHelper(cred, name, explicitOwner, binaryData, policy);
484 } catch (const Exc::Exception &e) {
486 } catch (const CKM::Exception &e) {
487 LogError("CKM::Exception: " << e.GetMessage());
488 return CKM_API_ERROR_SERVER_ERROR;
492 int CKMLogic::getKeyForService(
493 const Credentials &cred,
495 const ClientId &explicitOwner,
496 const Password &pass,
497 Crypto::GObjShPtr &key)
500 // Key is for internal service use. It won't be exported to the client
501 Crypto::GObjUPtr obj;
502 int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, explicitOwner,
505 if (retCode == CKM_API_SUCCESS)
506 key = std::move(obj);
509 } catch (const Exc::Exception &e) {
511 } catch (const CKM::Exception &e) {
512 LogError("CKM::Exception: " << e.GetMessage());
513 return CKM_API_ERROR_SERVER_ERROR;
517 RawBuffer CKMLogic::saveData(
518 const Credentials &cred,
521 const ClientId &explicitOwner,
522 const Crypto::Data &data,
523 const PolicySerializable &policy)
525 int retCode = verifyAndSaveDataHelper(cred, name, explicitOwner, data, policy);
526 auto response = MessageBuffer::Serialize(msgId, retCode, data.type);
527 return response.Pop();
530 int CKMLogic::extractPKCS12Data(
533 const ClientId &owner,
534 const PKCS12Serializable &pkcs,
535 const PolicySerializable &keyPolicy,
536 const PolicySerializable &certPolicy,
537 DB::RowVector &output)
539 // private key is mandatory
540 auto key = pkcs.getKey();
543 LogError("Failed to get private key from pkcs");
544 return CKM_API_ERROR_INVALID_FORMAT;
547 Crypto::Data keyData(DataType(key->getType()), key->getDER());
548 int retCode = verifyBinaryData(keyData);
550 if (retCode != CKM_API_SUCCESS)
553 output.push_back(createEncryptedRow(crypto, name, owner, keyData,
556 // certificate is mandatory
557 auto cert = pkcs.getCertificate();
560 LogError("Failed to get certificate from pkcs");
561 return CKM_API_ERROR_INVALID_FORMAT;
564 Crypto::Data certData(DataType::CERTIFICATE, cert->getDER());
565 retCode = verifyBinaryData(certData);
567 if (retCode != CKM_API_SUCCESS)
570 output.push_back(createEncryptedRow(crypto, name, owner, certData,
574 unsigned int cert_index = 0;
576 for (const auto &ca : pkcs.getCaCertificateShPtrVector()) {
577 Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++),
579 int retCode = verifyBinaryData(caCertData);
581 if (retCode != CKM_API_SUCCESS)
584 output.push_back(createEncryptedRow(crypto, name, owner, caCertData,
588 return CKM_API_SUCCESS;
591 RawBuffer CKMLogic::savePKCS12(
592 const Credentials &cred,
595 const ClientId &explicitOwner,
596 const PKCS12Serializable &pkcs,
597 const PolicySerializable &keyPolicy,
598 const PolicySerializable &certPolicy)
600 int retCode = CKM_API_ERROR_UNKNOWN;
603 retCode = saveDataHelper(cred, name, explicitOwner, pkcs, keyPolicy, certPolicy);
604 } catch (const Exc::Exception &e) {
606 } catch (const CKM::Exception &e) {
607 LogError("CKM::Exception: " << e.GetMessage());
608 retCode = CKM_API_ERROR_SERVER_ERROR;
611 auto response = MessageBuffer::Serialize(msgId, retCode);
612 return response.Pop();
616 int CKMLogic::removeDataHelper(
617 const Credentials &cred,
619 const ClientId &explicitOwner)
621 auto &handler = selectDatabase(cred, explicitOwner);
623 // use client id if not explicitly provided
624 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
626 if (!isNameValid(name) || !isClientValid(owner)) {
627 LogDebug("Invalid owner or name format");
628 return CKM_API_ERROR_INPUT_PARAM;
631 DB::Crypto::Transaction transaction(&handler.database);
633 // read and check permissions
634 PermissionMaskOptional permissionRowOpt =
635 handler.database.getPermissionRow(name, owner, cred.client);
636 int retCode = m_accessControl.canDelete(cred,
637 toPermissionMask(permissionRowOpt));
639 if (retCode != CKM_API_SUCCESS) {
640 LogWarning("access control check result: " << retCode);
644 // get all matching rows
646 handler.database.getRows(name, owner, DataType::DB_FIRST,
647 DataType::DB_LAST, rows);
650 LogDebug("No row for given name and owner");
651 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
654 // load app key if needed
655 retCode = loadAppKey(handler, rows.front().owner);
657 if (CKM_API_SUCCESS != retCode)
660 // destroy it in store
661 for (auto &r : rows) {
663 handler.crypto.decryptRow(Password(), r);
664 m_decider.getStore(r).destroy(r);
665 } catch (const Exc::AuthenticationFailed &) {
666 LogDebug("Authentication failed when removing data. Ignored.");
671 handler.database.deleteRow(name, owner);
672 transaction.commit();
674 return CKM_API_SUCCESS;
677 RawBuffer CKMLogic::removeData(
678 const Credentials &cred,
681 const ClientId &explicitOwner)
683 int retCode = CKM_API_ERROR_UNKNOWN;
686 retCode = removeDataHelper(cred, name, explicitOwner);
687 } catch (const Exc::Exception &e) {
689 } catch (const CKM::Exception &e) {
690 LogError("Error: " << e.GetMessage());
691 retCode = CKM_API_ERROR_DB_ERROR;
694 auto response = MessageBuffer::Serialize(msgId, retCode);
695 return response.Pop();
698 int CKMLogic::readSingleRow(const Name &name,
699 const ClientId &owner,
701 DB::Crypto &database,
704 DB::Crypto::RowOptional row_optional;
706 if (dataType.isKey()) {
707 // read all key types
708 row_optional = database.getRow(name,
710 DataType::DB_KEY_FIRST,
711 DataType::DB_KEY_LAST);
713 // read anything else
714 row_optional = database.getRow(name,
720 LogDebug("No row for given name, owner and type");
721 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
726 return CKM_API_SUCCESS;
730 int CKMLogic::readMultiRow(const Name &name,
731 const ClientId &owner,
733 DB::Crypto &database,
734 DB::RowVector &output)
736 if (dataType.isKey())
737 // read all key types
738 database.getRows(name,
740 DataType::DB_KEY_FIRST,
741 DataType::DB_KEY_LAST,
743 else if (dataType.isChainCert())
744 // read all key types
745 database.getRows(name,
747 DataType::DB_CHAIN_FIRST,
748 DataType::DB_CHAIN_LAST,
751 // read anything else
752 database.getRows(name,
757 if (!output.size()) {
758 LogDebug("No row for given name, owner and type");
759 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
762 return CKM_API_SUCCESS;
765 int CKMLogic::checkDataPermissionsHelper(const Credentials &accessorCred,
767 const ClientId &owner,
770 DB::Crypto &database)
772 PermissionMaskOptional permissionRowOpt =
773 database.getPermissionRow(name, owner, accessorCred.client);
776 return m_accessControl.canExport(accessorCred,
778 toPermissionMask(permissionRowOpt));
780 return m_accessControl.canRead(accessorCred,
781 toPermissionMask(permissionRowOpt));
784 Crypto::GObjUPtr CKMLogic::rowToObject(
787 const Password &password)
789 Crypto::GStore &store = m_decider.getStore(row);
791 Password pass = m_accessControl.isCCMode() ? "" : password;
794 Crypto::GObjUPtr obj;
796 if (CryptoLogic::getSchemeVersion(row.encryptionScheme) ==
797 CryptoLogic::ENCRYPTION_V2) {
798 handler.crypto.decryptRow(Password(), row);
800 obj = store.getObject(row, pass);
802 // decrypt entirely with old scheme: b64(pass(appkey(data))) -> data
803 handler.crypto.decryptRow(pass, row);
804 // destroy it in store
807 // import it to store with new scheme: data -> pass(data)
808 Token token = store.import(Crypto::Data(row.dataType, row.data), pass, Crypto::EncryptionParams());
810 // get it from the store (it can be different than the data we imported into store)
811 obj = store.getObject(token, pass);
813 // update row with new token
814 *static_cast<Token *>(&row) = std::move(token);
816 // encrypt it with app key: pass(data) -> b64(appkey(pass(data))
817 handler.crypto.encryptRow(row);
820 handler.database.updateRow(row);
826 int CKMLogic::readDataHelper(
828 const Credentials &cred,
831 const ClientId &explicitOwner,
832 const Password &password,
833 Crypto::GObjUPtrVector &objs)
835 auto &handler = selectDatabase(cred, explicitOwner);
837 // use client id if not explicitly provided
838 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
840 if (!isNameValid(name) || !isClientValid(owner))
841 return CKM_API_ERROR_INPUT_PARAM;
844 DB::Crypto::Transaction transaction(&handler.database);
846 int retCode = readMultiRow(name, owner, dataType, handler.database, rows);
848 if (CKM_API_SUCCESS != retCode)
851 // all read rows belong to the same owner
852 DB::Row &firstRow = rows.at(0);
854 // check access rights
855 retCode = checkDataPermissionsHelper(cred, name, owner, firstRow,
856 exportFlag, handler.database);
858 if (CKM_API_SUCCESS != retCode)
861 // load app key if needed
862 retCode = loadAppKey(handler, firstRow.owner);
864 if (CKM_API_SUCCESS != retCode)
868 for (auto &row : rows)
869 objs.push_back(rowToObject(handler, std::move(row), password));
871 // rowToObject may modify db
872 transaction.commit();
874 return CKM_API_SUCCESS;
877 int CKMLogic::readDataHelper(
879 const Credentials &cred,
882 const ClientId &explicitOwner,
883 const Password &password,
884 Crypto::GObjUPtr &obj)
886 DataType objDataType;
887 return readDataHelper(exportFlag, cred, dataType, name, explicitOwner,
888 password, obj, objDataType);
891 int CKMLogic::readDataHelper(
893 const Credentials &cred,
896 const ClientId &explicitOwner,
897 const Password &password,
898 Crypto::GObjUPtr &obj,
899 DataType &objDataType)
901 auto &handler = selectDatabase(cred, explicitOwner);
903 // use client id if not explicitly provided
904 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
906 if (!isNameValid(name) || !isClientValid(owner))
907 return CKM_API_ERROR_INPUT_PARAM;
910 DB::Crypto::Transaction transaction(&handler.database);
912 int retCode = readSingleRow(name, owner, dataType, handler.database, row);
914 if (CKM_API_SUCCESS != retCode)
917 objDataType = row.dataType;
919 // check access rights
920 retCode = checkDataPermissionsHelper(cred, name, owner, row, exportFlag,
923 if (CKM_API_SUCCESS != retCode)
926 // load app key if needed
927 retCode = loadAppKey(handler, row.owner);
929 if (CKM_API_SUCCESS != retCode)
932 obj = rowToObject(handler, std::move(row), password);
933 // rowToObject may modify db
934 transaction.commit();
936 return CKM_API_SUCCESS;
939 RawBuffer CKMLogic::getData(
940 const Credentials &cred,
944 const ClientId &explicitOwner,
945 const Password &password)
947 int retCode = CKM_API_SUCCESS;
949 DataType objDataType;
952 Crypto::GObjUPtr obj;
953 retCode = readDataHelper(true, cred, dataType, name, explicitOwner,
954 password, obj, objDataType);
956 if (retCode == CKM_API_SUCCESS)
957 rowData = obj->getBinary();
958 } catch (const Exc::Exception &e) {
960 } catch (const CKM::Exception &e) {
961 LogError("CKM::Exception: " << e.GetMessage());
962 retCode = CKM_API_ERROR_SERVER_ERROR;
965 if (CKM_API_SUCCESS != retCode)
968 auto response = MessageBuffer::Serialize(msgId,
972 return response.Pop();
975 RawBuffer CKMLogic::getDataProtectionStatus(
976 const Credentials &cred,
980 const ClientId &explicitOwner)
982 int retCode = CKM_API_SUCCESS;
984 DataType objDataType;
988 Crypto::GObjUPtr obj;
989 retCode = readDataHelper(false, cred, dataType, name, explicitOwner,
990 password, obj, objDataType);
992 } catch (const Exc::Exception &e) {
994 } catch (const CKM::Exception &e) {
995 LogError("CKM::Exception: " << e.GetMessage());
996 retCode = CKM_API_ERROR_SERVER_ERROR;
999 if (retCode == CKM_API_ERROR_AUTHENTICATION_FAILED) {
1001 retCode = CKM_API_SUCCESS;
1004 auto response = MessageBuffer::Serialize(msgId,
1008 return response.Pop();
1011 int CKMLogic::getPKCS12Helper(
1012 const Credentials &cred,
1014 const ClientId &explicitOwner,
1015 const Password &keyPassword,
1016 const Password &certPassword,
1018 CertificateShPtr &cert,
1019 CertificateShPtrVector &caChain)
1023 // read private key (mandatory)
1024 Crypto::GObjUPtr keyObj;
1025 retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, explicitOwner,
1026 keyPassword, keyObj);
1028 if (retCode != CKM_API_SUCCESS) {
1029 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1032 privKey = CKM::Key::create(keyObj->getBinary());
1035 // read certificate (mandatory)
1036 Crypto::GObjUPtr certObj;
1037 retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, explicitOwner,
1038 certPassword, certObj);
1040 if (retCode != CKM_API_SUCCESS) {
1041 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1044 cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER);
1047 // read CA cert chain (optional)
1048 Crypto::GObjUPtrVector caChainObjs;
1049 retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, explicitOwner,
1050 certPassword, caChainObjs);
1052 if (retCode != CKM_API_SUCCESS && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
1053 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1056 for (auto &caCertObj : caChainObjs)
1057 caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(),
1058 DataFormat::FORM_DER));
1061 // if anything found, return it
1062 if (privKey || cert || caChain.size() > 0)
1063 retCode = CKM_API_SUCCESS;
1068 RawBuffer CKMLogic::getPKCS12(
1069 const Credentials &cred,
1072 const ClientId &explicitOwner,
1073 const Password &keyPassword,
1074 const Password &certPassword)
1076 int retCode = CKM_API_ERROR_UNKNOWN;
1078 PKCS12Serializable output;
1082 CertificateShPtr cert;
1083 CertificateShPtrVector caChain;
1084 retCode = getPKCS12Helper(cred, name, explicitOwner, keyPassword,
1085 certPassword, privKey, cert, caChain);
1088 if (retCode == CKM_API_SUCCESS)
1089 output = PKCS12Serializable(std::move(privKey), std::move(cert), std::move(caChain));
1090 } catch (const Exc::Exception &e) {
1091 retCode = e.error();
1092 } catch (const CKM::Exception &e) {
1093 LogError("CKM::Exception: " << e.GetMessage());
1094 retCode = CKM_API_ERROR_SERVER_ERROR;
1097 auto response = MessageBuffer::Serialize(msgId, retCode, output);
1098 return response.Pop();
1101 int CKMLogic::getDataListHelper(const Credentials &cred,
1102 const DataType dataType,
1103 OwnerNameVector &ownerNameVector)
1105 int retCode = CKM_API_ERROR_DB_LOCKED;
1107 if (0 < m_userDataMap.count(cred.clientUid)) {
1108 auto &database = m_userDataMap[cred.clientUid].database;
1111 OwnerNameVector tmpVector;
1113 if (dataType.isKey()) {
1114 // list all key types
1115 database.listNames(cred.client,
1117 DataType::DB_KEY_FIRST,
1118 DataType::DB_KEY_LAST);
1120 // list anything else
1121 database.listNames(cred.client,
1126 ownerNameVector.insert(ownerNameVector.end(), tmpVector.begin(),
1128 retCode = CKM_API_SUCCESS;
1129 } catch (const CKM::Exception &e) {
1130 LogError("Error: " << e.GetMessage());
1131 retCode = CKM_API_ERROR_DB_ERROR;
1132 } catch (const Exc::Exception &e) {
1133 retCode = e.error();
1140 RawBuffer CKMLogic::getDataList(
1141 const Credentials &cred,
1145 OwnerNameVector systemVector;
1146 OwnerNameVector userVector;
1147 OwnerNameVector ownerNameVector;
1149 int retCode = unlockSystemDB();
1151 if (CKM_API_SUCCESS == retCode) {
1153 if (m_accessControl.isSystemService(cred)) {
1155 retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1160 // user - lookup system, then client DB
1161 retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1167 if (retCode == CKM_API_SUCCESS) {
1168 retCode = getDataListHelper(cred,
1175 if (retCode == CKM_API_SUCCESS) {
1176 ownerNameVector.insert(ownerNameVector.end(), systemVector.begin(),
1177 systemVector.end());
1178 ownerNameVector.insert(ownerNameVector.end(), userVector.begin(),
1182 auto response = MessageBuffer::Serialize(msgId,
1186 return response.Pop();
1189 int CKMLogic::importInitialData(
1191 const Crypto::Data &data,
1192 const Crypto::EncryptionParams &encParams,
1193 const Policy &policy)
1196 if (encParams.iv.empty() != encParams.tag.empty()) {
1197 LogError("Both iv and tag must be empty or set");
1198 return CKM_API_ERROR_INPUT_PARAM;
1201 // Inital values are always imported with root credentials. Client id is not important.
1202 Credentials rootCred(0, "");
1204 auto &handler = selectDatabase(rootCred, CLIENT_ID_SYSTEM);
1206 // check if save is possible
1207 DB::Crypto::Transaction transaction(&handler.database);
1208 int retCode = checkSaveConditions(rootCred, handler, name, CLIENT_ID_SYSTEM);
1210 if (retCode != CKM_API_SUCCESS)
1213 Crypto::GStore &store =
1214 m_decider.getStore(data.type, policy, !encParams.iv.empty());
1218 if (encParams.iv.empty()) {
1219 // Data are not encrypted, let's try to verify them
1220 Crypto::Data binaryData;
1222 if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
1225 token = store.import(binaryData,
1226 m_accessControl.isCCMode() ? "" : policy.password,
1229 token = store.import(data,
1230 m_accessControl.isCCMode() ? "" : policy.password,
1234 DB::Row row(std::move(token), name, CLIENT_ID_SYSTEM,
1235 static_cast<int>(policy.extractable));
1236 handler.crypto.encryptRow(row);
1238 handler.database.saveRow(row);
1239 transaction.commit();
1240 } catch (const Exc::Exception &e) {
1242 } catch (const CKM::Exception &e) {
1243 LogError("CKM::Exception: " << e.GetMessage());
1244 return CKM_API_ERROR_SERVER_ERROR;
1245 } catch (const std::exception &e) {
1246 LogError("Std::exception: " << e.what());
1247 return CKM_API_ERROR_SERVER_ERROR;
1250 return CKM_API_SUCCESS;
1253 int CKMLogic::saveDataHelper(
1254 const Credentials &cred,
1256 const ClientId &explicitOwner,
1257 const Crypto::Data &data,
1258 const PolicySerializable &policy)
1260 auto &handler = selectDatabase(cred, explicitOwner);
1262 // use client id if not explicitly provided
1263 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
1265 if (m_accessControl.isSystemService(cred) &&
1266 owner.compare(CLIENT_ID_SYSTEM) != 0) {
1267 LogError("System services can only use " << CLIENT_ID_SYSTEM << " as owner id") ;
1268 return CKM_API_ERROR_INPUT_PARAM;
1271 // check if save is possible
1272 DB::Crypto::Transaction transaction(&handler.database);
1273 int retCode = checkSaveConditions(cred, handler, name, owner);
1275 if (retCode != CKM_API_SUCCESS)
1279 DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, owner,
1281 handler.database.saveRow(encryptedRow);
1283 transaction.commit();
1284 return CKM_API_SUCCESS;
1287 int CKMLogic::saveDataHelper(
1288 const Credentials &cred,
1290 const ClientId &explicitOwner,
1291 const PKCS12Serializable &pkcs,
1292 const PolicySerializable &keyPolicy,
1293 const PolicySerializable &certPolicy)
1295 auto &handler = selectDatabase(cred, explicitOwner);
1297 // use client id if not explicitly provided
1298 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
1300 if (m_accessControl.isSystemService(cred) &&
1301 owner.compare(CLIENT_ID_SYSTEM) != 0)
1302 return CKM_API_ERROR_INPUT_PARAM;
1304 // check if save is possible
1305 DB::Crypto::Transaction transaction(&handler.database);
1306 int retCode = checkSaveConditions(cred, handler, name, owner);
1308 if (retCode != CKM_API_SUCCESS)
1311 // extract and encrypt the data
1312 DB::RowVector encryptedRows;
1313 retCode = extractPKCS12Data(handler.crypto, name, owner, pkcs, keyPolicy,
1314 certPolicy, encryptedRows);
1316 if (retCode != CKM_API_SUCCESS)
1320 handler.database.saveRows(name, owner, encryptedRows);
1321 transaction.commit();
1323 return CKM_API_SUCCESS;
1327 int CKMLogic::createKeyAESHelper(
1328 const Credentials &cred,
1331 const ClientId &explicitOwner,
1332 const PolicySerializable &policy)
1334 auto &handler = selectDatabase(cred, explicitOwner);
1336 // use client id if not explicitly provided
1337 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
1339 if (m_accessControl.isSystemService(cred) &&
1340 owner.compare(CLIENT_ID_SYSTEM) != 0)
1341 return CKM_API_ERROR_INPUT_PARAM;
1343 // check if save is possible
1344 DB::Crypto::Transaction transaction(&handler.database);
1345 int retCode = checkSaveConditions(cred, handler, name, owner);
1347 if (retCode != CKM_API_SUCCESS)
1350 // create key in store
1351 CryptoAlgorithm keyGenAlgorithm;
1352 keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::AES_GEN);
1353 keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, size);
1354 Token key = m_decider.getStore(DataType::KEY_AES,
1355 policy).generateSKey(keyGenAlgorithm, policy.password);
1358 DB::Row row(std::move(key), name, owner,
1359 static_cast<int>(policy.extractable));
1360 handler.crypto.encryptRow(row);
1362 handler.database.saveRow(row);
1364 transaction.commit();
1365 return CKM_API_SUCCESS;
1368 int CKMLogic::createKeyPairHelper(
1369 const Credentials &cred,
1370 const CryptoAlgorithmSerializable &keyGenParams,
1371 const Name &namePrivate,
1372 const ClientId &explicitOwnerPrivate,
1373 const Name &namePublic,
1374 const ClientId &explicitOwnerPublic,
1375 const PolicySerializable &policyPrivate,
1376 const PolicySerializable &policyPublic)
1378 auto &handlerPriv = selectDatabase(cred, explicitOwnerPrivate);
1379 auto &handlerPub = selectDatabase(cred, explicitOwnerPublic);
1381 AlgoType keyType = AlgoType::RSA_GEN;
1383 if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
1384 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
1386 const auto dtIt = ALGO_TYPE_TO_DATA_TYPE_PAIR_MAP.find(keyType);
1387 if (dtIt == ALGO_TYPE_TO_DATA_TYPE_PAIR_MAP.end())
1388 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
1389 const DataTypePair& dt = dtIt->second;
1391 if (policyPrivate.backend != policyPublic.backend)
1392 ThrowErr(Exc::InputParam, "Error, key pair must be supported with the same backend.");
1394 // use client id if not explicitly provided
1395 const ClientId &ownerPrv = explicitOwnerPrivate.empty() ? cred.client :
1396 explicitOwnerPrivate;
1398 if (m_accessControl.isSystemService(cred) &&
1399 ownerPrv.compare(CLIENT_ID_SYSTEM) != 0)
1400 return CKM_API_ERROR_INPUT_PARAM;
1402 const ClientId &ownerPub = explicitOwnerPublic.empty() ? cred.client :
1403 explicitOwnerPublic;
1405 if (m_accessControl.isSystemService(cred) &&
1406 ownerPub.compare(CLIENT_ID_SYSTEM) != 0)
1407 return CKM_API_ERROR_INPUT_PARAM;
1409 bool exportable = policyPrivate.extractable || policyPublic.extractable;
1410 Policy lessRestricted(Password(), exportable, policyPrivate.backend);
1412 TokenPair keys = m_decider.getStore(policyPrivate, dt.first, dt.second).generateAKey(keyGenParams,
1413 policyPrivate.password,
1414 policyPublic.password);
1416 DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
1417 // in case the same database is used for private and public - the second
1418 // transaction will not be executed
1419 DB::Crypto::Transaction transactionPub(&handlerPub.database);
1422 retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerPrv);
1424 if (CKM_API_SUCCESS != retCode)
1427 retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerPub);
1429 if (CKM_API_SUCCESS != retCode)
1433 DB::Row rowPrv(std::move(keys.first), namePrivate, ownerPrv,
1434 static_cast<int>(policyPrivate.extractable));
1435 handlerPriv.crypto.encryptRow(rowPrv);
1436 handlerPriv.database.saveRow(rowPrv);
1438 DB::Row rowPub(std::move(keys.second), namePublic, ownerPub,
1439 static_cast<int>(policyPublic.extractable));
1440 handlerPub.crypto.encryptRow(rowPub);
1441 handlerPub.database.saveRow(rowPub);
1443 transactionPub.commit();
1444 transactionPriv.commit();
1445 return CKM_API_SUCCESS;
1448 RawBuffer CKMLogic::createKeyPair(
1449 const Credentials &cred,
1451 const CryptoAlgorithmSerializable &keyGenParams,
1452 const Name &namePrivate,
1453 const ClientId &explicitOwnerPrivate,
1454 const Name &namePublic,
1455 const ClientId &explicitOwnerPublic,
1456 const PolicySerializable &policyPrivate,
1457 const PolicySerializable &policyPublic)
1459 int retCode = CKM_API_SUCCESS;
1462 retCode = createKeyPairHelper(
1466 explicitOwnerPrivate,
1468 explicitOwnerPublic,
1471 } catch (const Exc::Exception &e) {
1472 retCode = e.error();
1473 } catch (const CKM::Exception &e) {
1474 LogError("CKM::Exception: " << e.GetMessage());
1475 retCode = CKM_API_ERROR_SERVER_ERROR;
1478 return MessageBuffer::Serialize(msgId, retCode).Pop();
1481 RawBuffer CKMLogic::createKeyAES(
1482 const Credentials &cred,
1486 const ClientId &explicitOwner,
1487 const PolicySerializable &policy)
1489 int retCode = CKM_API_SUCCESS;
1492 retCode = createKeyAESHelper(cred, size, name, explicitOwner, policy);
1493 } catch (const Exc::Exception &e) {
1494 retCode = e.error();
1495 } catch (std::invalid_argument &e) {
1496 LogDebug("invalid argument error: " << e.what());
1497 retCode = CKM_API_ERROR_INPUT_PARAM;
1498 } catch (const CKM::Exception &e) {
1499 LogError("CKM::Exception: " << e.GetMessage());
1500 retCode = CKM_API_ERROR_SERVER_ERROR;
1503 return MessageBuffer::Serialize(msgId, retCode).Pop();
1506 int CKMLogic::readCertificateHelper(
1507 const Credentials &cred,
1508 const OwnerNameVector &ownerNameVector,
1509 CertificateImplVector &certVector)
1511 for (auto &i : ownerNameVector) {
1512 // certificates can't be protected with custom user password
1513 Crypto::GObjUPtr obj;
1515 ec = readDataHelper(true,
1517 DataType::CERTIFICATE,
1523 if (ec != CKM_API_SUCCESS)
1526 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1528 // try to read chain certificates (if present)
1529 Crypto::GObjUPtrVector caChainObjs;
1530 ec = readDataHelper(true,
1532 DataType::DB_CHAIN_FIRST,
1538 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1541 for (auto &caCertObj : caChainObjs)
1542 certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1545 return CKM_API_SUCCESS;
1548 int CKMLogic::getCertificateChainHelper(
1549 const CertificateImpl &cert,
1550 const RawBufferVector &untrustedCertificates,
1551 const RawBufferVector &trustedCertificates,
1552 bool useTrustedSystemCertificates,
1553 RawBufferVector &chainRawVector)
1555 CertificateImplVector untrustedCertVector;
1556 CertificateImplVector trustedCertVector;
1557 CertificateImplVector chainVector;
1560 return CKM_API_ERROR_INPUT_PARAM;
1562 for (auto &e : untrustedCertificates) {
1563 CertificateImpl c(e, DataFormat::FORM_DER);
1566 return CKM_API_ERROR_INPUT_PARAM;
1568 untrustedCertVector.push_back(std::move(c));
1571 for (auto &e : trustedCertificates) {
1572 CertificateImpl c(e, DataFormat::FORM_DER);
1575 return CKM_API_ERROR_INPUT_PARAM;
1577 trustedCertVector.push_back(std::move(c));
1580 CertificateStore store;
1581 int retCode = store.verifyCertificate(cert,
1582 untrustedCertVector,
1584 useTrustedSystemCertificates,
1585 m_accessControl.isCCMode(),
1588 if (retCode != CKM_API_SUCCESS)
1591 for (auto &e : chainVector)
1592 chainRawVector.push_back(e.getDER());
1594 return CKM_API_SUCCESS;
1597 int CKMLogic::getCertificateChainHelper(
1598 const Credentials &cred,
1599 const CertificateImpl &cert,
1600 const OwnerNameVector &untrusted,
1601 const OwnerNameVector &trusted,
1602 bool useTrustedSystemCertificates,
1603 RawBufferVector &chainRawVector)
1605 CertificateImplVector untrustedCertVector;
1606 CertificateImplVector trustedCertVector;
1607 CertificateImplVector chainVector;
1610 return CKM_API_ERROR_INPUT_PARAM;
1612 int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1614 if (retCode != CKM_API_SUCCESS)
1617 retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1619 if (retCode != CKM_API_SUCCESS)
1622 CertificateStore store;
1623 retCode = store.verifyCertificate(cert,
1624 untrustedCertVector,
1626 useTrustedSystemCertificates,
1627 m_accessControl.isCCMode(),
1630 if (retCode != CKM_API_SUCCESS)
1633 for (auto &i : chainVector)
1634 chainRawVector.push_back(i.getDER());
1636 return CKM_API_SUCCESS;
1639 RawBuffer CKMLogic::getCertificateChain(
1640 const Credentials & /*cred*/,
1642 const RawBuffer &certificate,
1643 const RawBufferVector &untrustedCertificates,
1644 const RawBufferVector &trustedCertificates,
1645 bool useTrustedSystemCertificates)
1647 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1648 RawBufferVector chainRawVector;
1649 int retCode = CKM_API_ERROR_UNKNOWN;
1652 retCode = getCertificateChainHelper(cert,
1653 untrustedCertificates,
1654 trustedCertificates,
1655 useTrustedSystemCertificates,
1657 } catch (const Exc::Exception &e) {
1658 retCode = e.error();
1659 } catch (const std::exception &e) {
1660 LogError("STD exception " << e.what());
1661 retCode = CKM_API_ERROR_SERVER_ERROR;
1663 LogError("Unknown error.");
1666 auto response = MessageBuffer::Serialize(msgId, retCode, chainRawVector);
1667 return response.Pop();
1670 RawBuffer CKMLogic::getCertificateChain(
1671 const Credentials &cred,
1673 const RawBuffer &certificate,
1674 const OwnerNameVector &untrustedCertificates,
1675 const OwnerNameVector &trustedCertificates,
1676 bool useTrustedSystemCertificates)
1678 int retCode = CKM_API_ERROR_UNKNOWN;
1679 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1680 RawBufferVector chainRawVector;
1683 retCode = getCertificateChainHelper(cred,
1685 untrustedCertificates,
1686 trustedCertificates,
1687 useTrustedSystemCertificates,
1689 } catch (const Exc::Exception &e) {
1690 retCode = e.error();
1691 } catch (const std::exception &e) {
1692 LogError("STD exception " << e.what());
1693 retCode = CKM_API_ERROR_SERVER_ERROR;
1695 LogError("Unknown error.");
1698 auto response = MessageBuffer::Serialize(msgId, retCode, chainRawVector);
1699 return response.Pop();
1702 RawBuffer CKMLogic::createSignature(
1703 const Credentials &cred,
1705 const Name &privateKeyName,
1706 const ClientId &explicitOwner,
1707 const Password &password, // password for private_key
1708 const RawBuffer &message,
1709 const CryptoAlgorithm &cryptoAlg)
1711 RawBuffer signature;
1713 int retCode = CKM_API_SUCCESS;
1716 Crypto::GObjUPtr obj;
1717 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1718 explicitOwner, password, obj);
1720 if (retCode == CKM_API_SUCCESS)
1721 signature = obj->sign(cryptoAlg, message);
1722 } catch (const Exc::Exception &e) {
1723 retCode = e.error();
1724 } catch (const CKM::Exception &e) {
1725 LogError("Unknown CKM::Exception: " << e.GetMessage());
1726 retCode = CKM_API_ERROR_SERVER_ERROR;
1727 } catch (const std::exception &e) {
1728 LogError("STD exception " << e.what());
1729 retCode = CKM_API_ERROR_SERVER_ERROR;
1732 auto response = MessageBuffer::Serialize(msgId, retCode, signature);
1733 return response.Pop();
1736 RawBuffer CKMLogic::verifySignature(
1737 const Credentials &cred,
1739 const Name &publicKeyOrCertName,
1740 const ClientId &explicitOwner,
1741 const Password &password, // password for public_key (optional)
1742 const RawBuffer &message,
1743 const RawBuffer &signature,
1744 const CryptoAlgorithm ¶ms)
1746 int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1749 // try certificate first - looking for a public key.
1750 // in case of PKCS, pub key from certificate will be found first
1751 // rather than private key from the same PKCS.
1752 Crypto::GObjUPtr obj;
1753 retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
1754 publicKeyOrCertName, explicitOwner, password, obj);
1756 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1757 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1758 publicKeyOrCertName, explicitOwner, password, obj);
1760 if (retCode == CKM_API_SUCCESS)
1761 retCode = obj->verify(params, message, signature);
1762 } catch (const Exc::Exception &e) {
1763 retCode = e.error();
1764 } catch (const CKM::Exception &e) {
1765 LogError("Unknown CKM::Exception: " << e.GetMessage());
1766 retCode = CKM_API_ERROR_SERVER_ERROR;
1769 auto response = MessageBuffer::Serialize(msgId, retCode);
1770 return response.Pop();
1773 int CKMLogic::setPermissionHelper(
1774 const Credentials &cred, // who's the client
1776 const ClientId &explicitOwner, // who's the owner
1777 const ClientId &accessor, // who will get the access
1778 const PermissionMask permissionMask)
1780 auto &handler = selectDatabase(cred, explicitOwner);
1782 // we don't know the client
1783 if (cred.client.empty() || !isClientValid(cred.client))
1784 return CKM_API_ERROR_INPUT_PARAM;
1786 // use client id if not explicitly provided
1787 const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;
1789 // verify name and owner are correct
1790 if (!isNameValid(name) || !isClientValid(owner) ||
1791 !isClientValid(accessor))
1792 return CKM_API_ERROR_INPUT_PARAM;
1794 // currently we don't support modification of owner's permissions to his own rows
1795 if (owner == accessor)
1796 return CKM_API_ERROR_INPUT_PARAM;
1798 // system database does not support write/remove permissions
1799 if ((0 == owner.compare(CLIENT_ID_SYSTEM)) &&
1800 (permissionMask & Permission::REMOVE))
1801 return CKM_API_ERROR_INPUT_PARAM;
1803 // can the client modify permissions to owner's row?
1804 int retCode = m_accessControl.canModify(cred, owner);
1806 if (retCode != CKM_API_SUCCESS)
1809 DB::Crypto::Transaction transaction(&handler.database);
1811 if (!handler.database.isNameOwnerPresent(name, owner))
1812 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1814 // set permissions to the row owned by owner for accessor
1815 handler.database.setPermission(name, owner, accessor, permissionMask);
1816 transaction.commit();
1818 return CKM_API_SUCCESS;
1821 RawBuffer CKMLogic::setPermission(
1822 const Credentials &cred,
1825 const ClientId &explicitOwner,
1826 const ClientId &accessor,
1827 const PermissionMask permissionMask)
1832 retCode = setPermissionHelper(cred, name, explicitOwner, accessor, permissionMask);
1833 } catch (const Exc::Exception &e) {
1834 retCode = e.error();
1835 } catch (const CKM::Exception &e) {
1836 LogError("Error: " << e.GetMessage());
1837 retCode = CKM_API_ERROR_DB_ERROR;
1840 return MessageBuffer::Serialize(msgID, retCode).Pop();
1843 int CKMLogic::loadAppKey(UserData &handle, const ClientId &owner)
1845 if (!handle.crypto.haveKey(owner)) {
1847 auto key_optional = handle.database.getKey(owner);
1849 if (!key_optional) {
1850 LogError("No key for given owner in database");
1851 return CKM_API_ERROR_DB_ERROR;
1854 key = *key_optional;
1855 key = handle.keyProvider.getPureDEK(key);
1856 handle.crypto.pushKey(owner, key);
1859 return CKM_API_SUCCESS;