2 * Copyright (c) 2000 - 2014 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 isLabelValid(const CKM::Label &label)
44 // TODO: copy code from libprivilege control (for check smack label)
45 if (label.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Label::npos)
51 bool isNameValid(const CKM::Name &name)
53 if (name.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Name::npos)
59 } // anonymous namespace
63 const uid_t CKMLogic::SYSTEM_DB_UID = 0;
64 const uid_t CKMLogic::ADMIN_USER_DB_UID = 5001;
68 CertificateConfig::addSystemCertificateDir(CERT_SYSTEM_DIR);
70 m_accessControl.updateCCMode();
73 CKMLogic::~CKMLogic() {}
75 void CKMLogic::loadDKEKFile(uid_t user, const Password &password)
77 auto &handle = m_userDataMap[user];
81 auto wrappedDKEK = fs.getDKEK();
83 if (wrappedDKEK.empty()) {
84 wrappedDKEK = KeyProvider::generateDomainKEK(std::to_string(user), password);
85 fs.saveDKEK(wrappedDKEK);
88 handle.keyProvider = KeyProvider(wrappedDKEK, password);
91 void CKMLogic::saveDKEKFile(uid_t user, const Password &password)
93 auto &handle = m_userDataMap[user];
96 fs.saveDKEK(handle.keyProvider.getWrappedDomainKEK(password));
99 void CKMLogic::migrateSecureStorageData(bool isAdminUser)
101 SsMigration::migrate(isAdminUser, [this](const std::string &name,
102 const Crypto::Data &data,
103 bool adminUserFlag) {
104 LogInfo("Migrate data called with name: " << name);
105 auto ownerId = adminUserFlag ? OWNER_ID_ADMIN_USER : OWNER_ID_SYSTEM;
106 auto uid = adminUserFlag ? ADMIN_USER_DB_UID : SYSTEM_DB_UID;
108 int ret = verifyAndSaveDataHelper(Credentials(uid, ownerId), name, ownerId, data,
109 PolicySerializable());
111 if (ret == CKM_API_ERROR_DB_ALIAS_EXISTS)
112 LogWarning("Alias already exist for migrated name: " << name);
113 else if (ret != CKM_API_SUCCESS)
114 LogError("Failed to migrate secure-storage data. name: " << name <<
119 int CKMLogic::unlockDatabase(uid_t user, const Password &password)
121 if (0 < m_userDataMap.count(user) &&
122 m_userDataMap[user].keyProvider.isInitialized())
123 return CKM_API_SUCCESS;
125 int retCode = CKM_API_SUCCESS;
128 auto &handle = m_userDataMap[user];
131 loadDKEKFile(user, password);
133 auto wrappedDatabaseDEK = fs.getDBDEK();
135 if (wrappedDatabaseDEK.empty()) {
136 wrappedDatabaseDEK = handle.keyProvider.generateDEK(std::to_string(user));
137 fs.saveDBDEK(wrappedDatabaseDEK);
140 RawBuffer key = handle.keyProvider.getPureDEK(wrappedDatabaseDEK);
142 handle.database = DB::Crypto(fs.getDBPath(), key);
143 handle.crypto = CryptoLogic();
145 if (!m_accessControl.isSystemService(user)) {
146 // remove data of removed apps during locked state
147 AppLabelVector removedApps = fs.clearRemovedsApps();
149 for (auto &appSmackLabel : removedApps) {
150 handle.crypto.removeKey(appSmackLabel);
151 handle.database.deleteKey(appSmackLabel);
155 if (user == SYSTEM_DB_UID && SsMigration::hasData())
156 migrateSecureStorageData(false);
157 else if (user == ADMIN_USER_DB_UID && SsMigration::hasData())
158 migrateSecureStorageData(true);
159 } catch (const Exc::Exception &e) {
161 } catch (const CKM::Exception &e) {
162 LogError("CKM::Exception: " << e.GetMessage());
163 retCode = CKM_API_ERROR_SERVER_ERROR;
166 if (CKM_API_SUCCESS != retCode)
167 m_userDataMap.erase(user);
172 int CKMLogic::unlockSystemDB()
174 return unlockDatabase(SYSTEM_DB_UID, SYSTEM_DB_PASSWD);
177 UserData &CKMLogic::selectDatabase(const Credentials &cred,
178 const Label &incoming_label)
180 // if user trying to access system service - check:
181 // * if user database is unlocked [mandatory]
182 // * if not - proceed with regular user database
183 // * if explicit system database label given -> switch to system DB
184 if (!m_accessControl.isSystemService(cred)) {
185 if (0 == m_userDataMap.count(cred.clientUid))
186 ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked");
188 if (0 != incoming_label.compare(OWNER_ID_SYSTEM))
189 return m_userDataMap[cred.clientUid];
192 // system database selected, modify the label
193 if (CKM_API_SUCCESS != unlockSystemDB())
194 ThrowErr(Exc::DatabaseLocked, "can not unlock system database");
196 return m_userDataMap[SYSTEM_DB_UID];
199 RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password)
201 int retCode = CKM_API_SUCCESS;
203 if (!m_accessControl.isSystemService(user))
204 retCode = unlockDatabase(user, password);
205 else // do not allow lock/unlock operations for system users
206 retCode = CKM_API_ERROR_INPUT_PARAM;
208 return MessageBuffer::Serialize(retCode).Pop();
211 RawBuffer CKMLogic::updateCCMode()
213 m_accessControl.updateCCMode();
214 return MessageBuffer::Serialize(CKM_API_SUCCESS).Pop();
217 RawBuffer CKMLogic::lockUserKey(uid_t user)
219 int retCode = CKM_API_SUCCESS;
221 if (!m_accessControl.isSystemService(user))
222 m_userDataMap.erase(user);
223 else // do not allow lock/unlock operations for system users
224 retCode = CKM_API_ERROR_INPUT_PARAM;
226 return MessageBuffer::Serialize(retCode).Pop();
229 RawBuffer CKMLogic::removeUserData(uid_t user)
231 int retCode = CKM_API_SUCCESS;
233 if (m_accessControl.isSystemService(user))
234 user = SYSTEM_DB_UID;
236 m_userDataMap.erase(user);
241 return MessageBuffer::Serialize(retCode).Pop();
244 int CKMLogic::changeUserPasswordHelper(uid_t user,
245 const Password &oldPassword,
246 const Password &newPassword)
248 // do not allow to change system database password
249 if (m_accessControl.isSystemService(user))
250 return CKM_API_ERROR_INPUT_PARAM;
252 loadDKEKFile(user, oldPassword);
253 saveDKEKFile(user, newPassword);
255 return CKM_API_SUCCESS;
258 RawBuffer CKMLogic::changeUserPassword(
260 const Password &oldPassword,
261 const Password &newPassword)
263 int retCode = CKM_API_SUCCESS;
266 retCode = changeUserPasswordHelper(user, oldPassword, newPassword);
267 } catch (const Exc::Exception &e) {
269 } catch (const CKM::Exception &e) {
270 LogError("CKM::Exception: " << e.GetMessage());
271 retCode = CKM_API_ERROR_SERVER_ERROR;
274 return MessageBuffer::Serialize(retCode).Pop();
277 int CKMLogic::resetUserPasswordHelper(
279 const Password &newPassword)
281 // do not allow to reset system database password
282 if (m_accessControl.isSystemService(user))
283 return CKM_API_ERROR_INPUT_PARAM;
285 int retCode = CKM_API_SUCCESS;
287 if (0 == m_userDataMap.count(user)) {
288 // Check if key exists. If exists we must return error
290 auto wrappedDKEKMain = fs.getDKEK();
292 if (!wrappedDKEKMain.empty())
293 retCode = CKM_API_ERROR_BAD_REQUEST;
295 saveDKEKFile(user, newPassword);
301 RawBuffer CKMLogic::resetUserPassword(
303 const Password &newPassword)
305 int retCode = CKM_API_SUCCESS;
308 retCode = resetUserPasswordHelper(user, newPassword);
309 } catch (const Exc::Exception &e) {
311 } catch (const CKM::Exception &e) {
312 LogError("CKM::Exception: " << e.GetMessage());
313 retCode = CKM_API_ERROR_SERVER_ERROR;
316 return MessageBuffer::Serialize(retCode).Pop();
319 RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel)
321 int retCode = CKM_API_SUCCESS;
324 if (smackLabel.empty()) {
325 retCode = CKM_API_ERROR_INPUT_PARAM;
327 UidVector uids = FileSystem::getUIDsFromDBFile();
329 for (auto userId : uids) {
330 if (0 == m_userDataMap.count(userId)) {
331 FileSystem fs(userId);
332 fs.addRemovedApp(smackLabel);
334 auto &handle = m_userDataMap[userId];
335 handle.crypto.removeKey(smackLabel);
336 handle.database.deleteKey(smackLabel);
340 } catch (const Exc::Exception &e) {
342 } catch (const CKM::Exception &e) {
343 LogError("CKM::Exception: " << e.GetMessage());
344 retCode = CKM_API_ERROR_SERVER_ERROR;
347 return MessageBuffer::Serialize(retCode).Pop();
350 int CKMLogic::checkSaveConditions(
351 const Credentials &cred,
354 const Label &ownerLabel)
356 // verify name and label are correct
357 if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
358 LogDebug("Invalid parameter passed to key-manager");
359 return CKM_API_ERROR_INPUT_PARAM;
362 // check if allowed to save using ownerLabel
363 int access_ec = m_accessControl.canSave(cred, ownerLabel);
365 if (access_ec != CKM_API_SUCCESS) {
366 LogDebug("label " << cred.smackLabel << " can not save rows using label " <<
371 // check if not a duplicate
372 if (handler.database.isNameLabelPresent(name, ownerLabel))
373 return CKM_API_ERROR_DB_ALIAS_EXISTS;
375 // encryption section
376 if (!handler.crypto.haveKey(ownerLabel)) {
378 auto key_optional = handler.database.getKey(ownerLabel);
381 LogDebug("No Key in database found. Generating new one for label: " <<
383 got_key = handler.keyProvider.generateDEK(ownerLabel);
384 handler.database.saveKey(ownerLabel, got_key);
386 LogDebug("Key from DB");
387 got_key = *key_optional;
390 got_key = handler.keyProvider.getPureDEK(got_key);
391 handler.crypto.pushKey(ownerLabel, got_key);
394 return CKM_API_SUCCESS;
397 DB::Row CKMLogic::createEncryptedRow(
401 const Crypto::Data &data,
402 const Policy &policy) const
404 Crypto::GStore &store = m_decider.getStore(data.type, policy);
406 // do not encrypt data with password during cc_mode on
407 Token token = store.import(data,
408 m_accessControl.isCCMode() ? "" : policy.password);
409 DB::Row row(std::move(token), name, label,
410 static_cast<int>(policy.extractable));
411 crypto.encryptRow(row);
415 int CKMLogic::verifyBinaryData(Crypto::Data &input) const
418 return toBinaryData(input, dummy);
421 int CKMLogic::toBinaryData(const Crypto::Data &input,
422 Crypto::Data &output) const
424 // verify the data integrity
425 if (input.type.isKey()) {
428 if (input.type.isSKey())
429 output_key = CKM::Key::createAES(input.data);
431 output_key = CKM::Key::create(input.data);
433 if (output_key.get() == NULL) {
434 LogDebug("provided binary data is not valid key data");
435 return CKM_API_ERROR_INPUT_PARAM;
438 output = std::move(Crypto::Data(input.type, output_key->getDER()));
439 } else if (input.type.isCertificate() || input.type.isChainCert()) {
440 CertificateShPtr cert = CKM::Certificate::create(input.data,
441 DataFormat::FORM_DER);
443 if (cert.get() == NULL) {
444 LogDebug("provided binary data is not valid certificate data");
445 return CKM_API_ERROR_INPUT_PARAM;
448 output = std::move(Crypto::Data(input.type, cert->getDER()));
453 // TODO: add here BINARY_DATA verification, i.e: max size etc.
454 return CKM_API_SUCCESS;
457 int CKMLogic::verifyAndSaveDataHelper(
458 const Credentials &cred,
461 const Crypto::Data &data,
462 const PolicySerializable &policy)
464 int retCode = CKM_API_ERROR_UNKNOWN;
467 // check if data is correct
468 Crypto::Data binaryData;
469 retCode = toBinaryData(data, binaryData);
471 if (retCode != CKM_API_SUCCESS)
474 return saveDataHelper(cred, name, label, binaryData, policy);
475 } catch (const Exc::Exception &e) {
477 } catch (const CKM::Exception &e) {
478 LogError("CKM::Exception: " << e.GetMessage());
479 return CKM_API_ERROR_SERVER_ERROR;
483 int CKMLogic::getKeyForService(
484 const Credentials &cred,
487 const Password &pass,
488 Crypto::GObjShPtr &key)
491 // Key is for internal service use. It won't be exported to the client
492 Crypto::GObjUPtr obj;
493 int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, label,
496 if (retCode == CKM_API_SUCCESS)
497 key = std::move(obj);
500 } catch (const Exc::Exception &e) {
502 } catch (const CKM::Exception &e) {
503 LogError("CKM::Exception: " << e.GetMessage());
504 return CKM_API_ERROR_SERVER_ERROR;
508 RawBuffer CKMLogic::saveData(
509 const Credentials &cred,
513 const Crypto::Data &data,
514 const PolicySerializable &policy)
516 int retCode = verifyAndSaveDataHelper(cred, name, label, data, policy);
517 auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
520 static_cast<int>(data.type));
521 return response.Pop();
524 int CKMLogic::extractPKCS12Data(
527 const Label &ownerLabel,
528 const PKCS12Serializable &pkcs,
529 const PolicySerializable &keyPolicy,
530 const PolicySerializable &certPolicy,
531 DB::RowVector &output) const
533 // private key is mandatory
534 auto key = pkcs.getKey();
537 LogError("Failed to get private key from pkcs");
538 return CKM_API_ERROR_INVALID_FORMAT;
541 Crypto::Data keyData(DataType(key->getType()), key->getDER());
542 int retCode = verifyBinaryData(keyData);
544 if (retCode != CKM_API_SUCCESS)
547 output.push_back(createEncryptedRow(crypto, name, ownerLabel, keyData,
550 // certificate is mandatory
551 auto cert = pkcs.getCertificate();
554 LogError("Failed to get certificate from pkcs");
555 return CKM_API_ERROR_INVALID_FORMAT;
558 Crypto::Data certData(DataType::CERTIFICATE, cert->getDER());
559 retCode = verifyBinaryData(certData);
561 if (retCode != CKM_API_SUCCESS)
564 output.push_back(createEncryptedRow(crypto, name, ownerLabel, certData,
568 unsigned int cert_index = 0;
570 for (const auto &ca : pkcs.getCaCertificateShPtrVector()) {
571 Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++),
573 int retCode = verifyBinaryData(caCertData);
575 if (retCode != CKM_API_SUCCESS)
578 output.push_back(createEncryptedRow(crypto, name, ownerLabel, caCertData,
582 return CKM_API_SUCCESS;
585 RawBuffer CKMLogic::savePKCS12(
586 const Credentials &cred,
590 const PKCS12Serializable &pkcs,
591 const PolicySerializable &keyPolicy,
592 const PolicySerializable &certPolicy)
594 int retCode = CKM_API_ERROR_UNKNOWN;
597 retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy);
598 } catch (const Exc::Exception &e) {
600 } catch (const CKM::Exception &e) {
601 LogError("CKM::Exception: " << e.GetMessage());
602 retCode = CKM_API_ERROR_SERVER_ERROR;
605 auto response = MessageBuffer::Serialize(static_cast<int>
606 (LogicCommand::SAVE_PKCS12),
609 return response.Pop();
613 int CKMLogic::removeDataHelper(
614 const Credentials &cred,
618 auto &handler = selectDatabase(cred, label);
620 // use client label if not explicitly provided
621 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
623 if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
624 LogDebug("Invalid label or name format");
625 return CKM_API_ERROR_INPUT_PARAM;
628 DB::Crypto::Transaction transaction(&handler.database);
630 // read and check permissions
631 PermissionMaskOptional permissionRowOpt =
632 handler.database.getPermissionRow(name, ownerLabel, cred.smackLabel);
633 int retCode = m_accessControl.canDelete(cred,
634 PermissionForLabel(cred.smackLabel, permissionRowOpt));
636 if (retCode != CKM_API_SUCCESS) {
637 LogWarning("access control check result: " << retCode);
641 // get all matching rows
643 handler.database.getRows(name, ownerLabel, DataType::DB_FIRST,
644 DataType::DB_LAST, rows);
647 LogDebug("No row for given name and label");
648 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
651 // load app key if needed
652 retCode = loadAppKey(handler, rows.front().ownerLabel);
654 if (CKM_API_SUCCESS != retCode)
657 // destroy it in store
658 for (auto &r : rows) {
660 handler.crypto.decryptRow(Password(), r);
661 m_decider.getStore(r).destroy(r);
662 } catch (const Exc::AuthenticationFailed &) {
663 LogDebug("Authentication failed when removing data. Ignored.");
668 handler.database.deleteRow(name, ownerLabel);
669 transaction.commit();
671 return CKM_API_SUCCESS;
674 RawBuffer CKMLogic::removeData(
675 const Credentials &cred,
680 int retCode = CKM_API_ERROR_UNKNOWN;
683 retCode = removeDataHelper(cred, name, label);
684 } catch (const Exc::Exception &e) {
686 } catch (const CKM::Exception &e) {
687 LogError("Error: " << e.GetMessage());
688 retCode = CKM_API_ERROR_DB_ERROR;
691 auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::REMOVE),
694 return response.Pop();
697 int CKMLogic::readSingleRow(const Name &name,
698 const Label &ownerLabel,
700 DB::Crypto &database,
703 DB::Crypto::RowOptional row_optional;
705 if (dataType.isKey()) {
706 // read all key types
707 row_optional = database.getRow(name,
709 DataType::DB_KEY_FIRST,
710 DataType::DB_KEY_LAST);
712 // read anything else
713 row_optional = database.getRow(name,
719 LogDebug("No row for given name, label and type");
720 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
725 return CKM_API_SUCCESS;
729 int CKMLogic::readMultiRow(const Name &name,
730 const Label &ownerLabel,
732 DB::Crypto &database,
733 DB::RowVector &output)
735 if (dataType.isKey())
736 // read all key types
737 database.getRows(name,
739 DataType::DB_KEY_FIRST,
740 DataType::DB_KEY_LAST,
742 else if (dataType.isChainCert())
743 // read all key types
744 database.getRows(name,
746 DataType::DB_CHAIN_FIRST,
747 DataType::DB_CHAIN_LAST,
750 // read anything else
751 database.getRows(name,
756 if (!output.size()) {
757 LogDebug("No row for given name, label and type");
758 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
761 return CKM_API_SUCCESS;
764 int CKMLogic::checkDataPermissionsHelper(const Credentials &cred,
766 const Label &ownerLabel,
767 const Label &accessorLabel,
770 DB::Crypto &database)
772 PermissionMaskOptional permissionRowOpt =
773 database.getPermissionRow(name, ownerLabel, accessorLabel);
776 return m_accessControl.canExport(cred, row, PermissionForLabel(accessorLabel,
779 return m_accessControl.canRead(cred, PermissionForLabel(accessorLabel,
783 Crypto::GObjUPtr CKMLogic::rowToObject(
786 const Password &password)
788 Crypto::GStore &store = m_decider.getStore(row);
790 Password pass = m_accessControl.isCCMode() ? "" : password;
793 Crypto::GObjUPtr obj;
795 if (CryptoLogic::getSchemeVersion(row.encryptionScheme) ==
796 CryptoLogic::ENCRYPTION_V2) {
797 handler.crypto.decryptRow(Password(), row);
799 obj = store.getObject(row, pass);
801 // decrypt entirely with old scheme: b64(pass(appkey(data))) -> data
802 handler.crypto.decryptRow(pass, row);
803 // destroy it in store
806 // import it to store with new scheme: data -> pass(data)
807 Token token = store.import(Crypto::Data(row.dataType, row.data), pass);
809 // get it from the store (it can be different than the data we imported into store)
810 obj = store.getObject(token, pass);
812 // update row with new token
813 *static_cast<Token *>(&row) = std::move(token);
815 // encrypt it with app key: pass(data) -> b64(appkey(pass(data))
816 handler.crypto.encryptRow(row);
819 handler.database.updateRow(row);
825 int CKMLogic::readDataHelper(
827 const Credentials &cred,
831 const Password &password,
832 Crypto::GObjUPtrVector &objs)
834 auto &handler = selectDatabase(cred, label);
836 // use client label if not explicitly provided
837 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
839 if (!isNameValid(name) || !isLabelValid(ownerLabel))
840 return CKM_API_ERROR_INPUT_PARAM;
843 DB::Crypto::Transaction transaction(&handler.database);
845 int retCode = readMultiRow(name, ownerLabel, dataType, handler.database, rows);
847 if (CKM_API_SUCCESS != retCode)
850 // all read rows belong to the same owner
851 DB::Row &firstRow = rows.at(0);
853 // check access rights
854 retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
855 firstRow, exportFlag, handler.database);
857 if (CKM_API_SUCCESS != retCode)
860 // load app key if needed
861 retCode = loadAppKey(handler, firstRow.ownerLabel);
863 if (CKM_API_SUCCESS != retCode)
867 for (auto &row : rows)
868 objs.push_back(rowToObject(handler, std::move(row), password));
870 // rowToObject may modify db
871 transaction.commit();
873 return CKM_API_SUCCESS;
876 int CKMLogic::readDataHelper(
878 const Credentials &cred,
882 const Password &password,
883 Crypto::GObjUPtr &obj)
885 DataType objDataType;
886 return readDataHelper(exportFlag, cred, dataType, name, label, password, obj,
890 int CKMLogic::readDataHelper(
892 const Credentials &cred,
896 const Password &password,
897 Crypto::GObjUPtr &obj,
898 DataType &objDataType)
900 auto &handler = selectDatabase(cred, label);
902 // use client label if not explicitly provided
903 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
905 if (!isNameValid(name) || !isLabelValid(ownerLabel))
906 return CKM_API_ERROR_INPUT_PARAM;
909 DB::Crypto::Transaction transaction(&handler.database);
911 int retCode = readSingleRow(name, ownerLabel, dataType, handler.database, row);
913 if (CKM_API_SUCCESS != retCode)
916 objDataType = row.dataType;
918 // check access rights
919 retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
920 row, exportFlag, handler.database);
922 if (CKM_API_SUCCESS != retCode)
925 // load app key if needed
926 retCode = loadAppKey(handler, row.ownerLabel);
928 if (CKM_API_SUCCESS != retCode)
931 obj = rowToObject(handler, std::move(row), password);
932 // rowToObject may modify db
933 transaction.commit();
935 return CKM_API_SUCCESS;
938 RawBuffer CKMLogic::getData(
939 const Credentials &cred,
944 const Password &password)
946 int retCode = CKM_API_SUCCESS;
948 DataType objDataType;
951 Crypto::GObjUPtr obj;
952 retCode = readDataHelper(true, cred, dataType, name, label, password, obj,
955 if (retCode == CKM_API_SUCCESS)
956 rowData = obj->getBinary();
957 } catch (const Exc::Exception &e) {
959 } catch (const CKM::Exception &e) {
960 LogError("CKM::Exception: " << e.GetMessage());
961 retCode = CKM_API_ERROR_SERVER_ERROR;
964 if (CKM_API_SUCCESS != retCode)
967 auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET),
970 static_cast<int>(objDataType),
972 return response.Pop();
975 int CKMLogic::getPKCS12Helper(
976 const Credentials &cred,
979 const Password &keyPassword,
980 const Password &certPassword,
982 CertificateShPtr &cert,
983 CertificateShPtrVector &caChain)
987 // read private key (mandatory)
988 Crypto::GObjUPtr keyObj;
989 retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, label,
990 keyPassword, keyObj);
992 if (retCode != CKM_API_SUCCESS) {
993 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
996 privKey = CKM::Key::create(keyObj->getBinary());
999 // read certificate (mandatory)
1000 Crypto::GObjUPtr certObj;
1001 retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, label,
1002 certPassword, certObj);
1004 if (retCode != CKM_API_SUCCESS) {
1005 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1008 cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER);
1011 // read CA cert chain (optional)
1012 Crypto::GObjUPtrVector caChainObjs;
1013 retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, label,
1014 certPassword, caChainObjs);
1016 if (retCode != CKM_API_SUCCESS && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
1017 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1020 for (auto &caCertObj : caChainObjs)
1021 caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(),
1022 DataFormat::FORM_DER));
1025 // if anything found, return it
1026 if (privKey || cert || caChain.size() > 0)
1027 retCode = CKM_API_SUCCESS;
1032 RawBuffer CKMLogic::getPKCS12(
1033 const Credentials &cred,
1037 const Password &keyPassword,
1038 const Password &certPassword)
1040 int retCode = CKM_API_ERROR_UNKNOWN;
1042 PKCS12Serializable output;
1046 CertificateShPtr cert;
1047 CertificateShPtrVector caChain;
1048 retCode = getPKCS12Helper(cred, name, label, keyPassword, certPassword, privKey,
1052 if (retCode == CKM_API_SUCCESS)
1053 output = PKCS12Serializable(std::move(privKey), std::move(cert),
1054 std::move(caChain));
1055 } catch (const Exc::Exception &e) {
1056 retCode = e.error();
1057 } catch (const CKM::Exception &e) {
1058 LogError("CKM::Exception: " << e.GetMessage());
1059 retCode = CKM_API_ERROR_SERVER_ERROR;
1062 auto response = MessageBuffer::Serialize(static_cast<int>
1063 (LogicCommand::GET_PKCS12),
1067 return response.Pop();
1070 int CKMLogic::getDataListHelper(const Credentials &cred,
1071 const DataType dataType,
1072 LabelNameVector &labelNameVector)
1074 int retCode = CKM_API_ERROR_DB_LOCKED;
1076 if (0 < m_userDataMap.count(cred.clientUid)) {
1077 auto &database = m_userDataMap[cred.clientUid].database;
1080 LabelNameVector tmpVector;
1082 if (dataType.isKey()) {
1083 // list all key types
1084 database.listNames(cred.smackLabel,
1086 DataType::DB_KEY_FIRST,
1087 DataType::DB_KEY_LAST);
1089 // list anything else
1090 database.listNames(cred.smackLabel,
1095 labelNameVector.insert(labelNameVector.end(), tmpVector.begin(),
1097 retCode = CKM_API_SUCCESS;
1098 } catch (const CKM::Exception &e) {
1099 LogError("Error: " << e.GetMessage());
1100 retCode = CKM_API_ERROR_DB_ERROR;
1101 } catch (const Exc::Exception &e) {
1102 retCode = e.error();
1109 RawBuffer CKMLogic::getDataList(
1110 const Credentials &cred,
1114 LabelNameVector systemVector;
1115 LabelNameVector userVector;
1116 LabelNameVector labelNameVector;
1118 int retCode = unlockSystemDB();
1120 if (CKM_API_SUCCESS == retCode) {
1122 if (m_accessControl.isSystemService(cred)) {
1124 retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1129 // user - lookup system, then client DB
1130 retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1136 if (retCode == CKM_API_SUCCESS) {
1137 retCode = getDataListHelper(cred,
1144 if (retCode == CKM_API_SUCCESS) {
1145 labelNameVector.insert(labelNameVector.end(), systemVector.begin(),
1146 systemVector.end());
1147 labelNameVector.insert(labelNameVector.end(), userVector.begin(),
1151 auto response = MessageBuffer::Serialize(static_cast<int>
1152 (LogicCommand::GET_LIST),
1155 static_cast<int>(dataType),
1157 return response.Pop();
1160 int CKMLogic::importInitialData(
1162 const Crypto::Data &data,
1163 const Crypto::DataEncryption &enc,
1164 const Policy &policy)
1167 // Inital values are always imported with root credentials. Label is not important.
1168 Credentials rootCred(0, "");
1170 auto &handler = selectDatabase(rootCred, OWNER_ID_SYSTEM);
1172 // check if save is possible
1173 DB::Crypto::Transaction transaction(&handler.database);
1174 int retCode = checkSaveConditions(rootCred, handler, name, OWNER_ID_SYSTEM);
1176 if (retCode != CKM_API_SUCCESS)
1179 Crypto::GStore &store = m_decider.getStore(data.type, policy, !enc.encryptedKey.empty());
1183 if (enc.encryptedKey.empty()) {
1184 Crypto::Data binaryData;
1186 if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
1189 token = store.import(binaryData,
1190 m_accessControl.isCCMode() ? "" : policy.password);
1192 token = store.importEncrypted(data,
1193 m_accessControl.isCCMode() ? "" : policy.password, enc);
1196 DB::Row row(std::move(token), name, OWNER_ID_SYSTEM,
1197 static_cast<int>(policy.extractable));
1198 handler.crypto.encryptRow(row);
1200 handler.database.saveRow(row);
1201 transaction.commit();
1202 } catch (const Exc::Exception &e) {
1204 } catch (const CKM::Exception &e) {
1205 LogError("CKM::Exception: " << e.GetMessage());
1206 return CKM_API_ERROR_SERVER_ERROR;
1207 } catch (const std::exception &e) {
1208 LogError("Std::exception: " << e.what());
1209 return CKM_API_ERROR_SERVER_ERROR;
1212 return CKM_API_SUCCESS;
1215 int CKMLogic::saveDataHelper(
1216 const Credentials &cred,
1219 const Crypto::Data &data,
1220 const PolicySerializable &policy)
1222 auto &handler = selectDatabase(cred, label);
1224 // use client label if not explicitly provided
1225 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1227 if (m_accessControl.isSystemService(cred) &&
1228 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1229 return CKM_API_ERROR_INPUT_PARAM;
1231 // check if save is possible
1232 DB::Crypto::Transaction transaction(&handler.database);
1233 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1235 if (retCode != CKM_API_SUCCESS)
1239 DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, ownerLabel,
1241 handler.database.saveRow(encryptedRow);
1243 transaction.commit();
1244 return CKM_API_SUCCESS;
1247 int CKMLogic::saveDataHelper(
1248 const Credentials &cred,
1251 const PKCS12Serializable &pkcs,
1252 const PolicySerializable &keyPolicy,
1253 const PolicySerializable &certPolicy)
1255 auto &handler = selectDatabase(cred, label);
1257 // use client label if not explicitly provided
1258 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1260 if (m_accessControl.isSystemService(cred) &&
1261 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1262 return CKM_API_ERROR_INPUT_PARAM;
1264 // check if save is possible
1265 DB::Crypto::Transaction transaction(&handler.database);
1266 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1268 if (retCode != CKM_API_SUCCESS)
1271 // extract and encrypt the data
1272 DB::RowVector encryptedRows;
1273 retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy,
1274 certPolicy, encryptedRows);
1276 if (retCode != CKM_API_SUCCESS)
1280 handler.database.saveRows(name, ownerLabel, encryptedRows);
1281 transaction.commit();
1283 return CKM_API_SUCCESS;
1287 int CKMLogic::createKeyAESHelper(
1288 const Credentials &cred,
1292 const PolicySerializable &policy)
1294 auto &handler = selectDatabase(cred, label);
1296 // use client label if not explicitly provided
1297 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1299 if (m_accessControl.isSystemService(cred) &&
1300 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1301 return CKM_API_ERROR_INPUT_PARAM;
1303 // check if save is possible
1304 DB::Crypto::Transaction transaction(&handler.database);
1305 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1307 if (retCode != CKM_API_SUCCESS)
1310 // create key in store
1311 CryptoAlgorithm keyGenAlgorithm;
1312 keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::AES_GEN);
1313 keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, size);
1314 Token key = m_decider.getStore(DataType::KEY_AES,
1315 policy).generateSKey(keyGenAlgorithm, policy.password);
1318 DB::Row row(std::move(key), name, ownerLabel,
1319 static_cast<int>(policy.extractable));
1320 handler.crypto.encryptRow(row);
1322 handler.database.saveRow(row);
1324 transaction.commit();
1325 return CKM_API_SUCCESS;
1328 int CKMLogic::createKeyPairHelper(
1329 const Credentials &cred,
1330 const CryptoAlgorithmSerializable &keyGenParams,
1331 const Name &namePrivate,
1332 const Label &labelPrivate,
1333 const Name &namePublic,
1334 const Label &labelPublic,
1335 const PolicySerializable &policyPrivate,
1336 const PolicySerializable &policyPublic)
1338 auto &handlerPriv = selectDatabase(cred, labelPrivate);
1339 auto &handlerPub = selectDatabase(cred, labelPublic);
1341 AlgoType keyType = AlgoType::RSA_GEN;
1343 if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
1344 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
1346 DataType dt(keyType);
1349 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
1351 if (policyPrivate.backend != policyPublic.backend)
1352 ThrowErr(Exc::InputParam, "Error, key pair must be supported with the same backend.");
1354 // use client label if not explicitly provided
1355 const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel :
1358 if (m_accessControl.isSystemService(cred) &&
1359 ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0)
1360 return CKM_API_ERROR_INPUT_PARAM;
1362 const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel :
1365 if (m_accessControl.isSystemService(cred) &&
1366 ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0)
1367 return CKM_API_ERROR_INPUT_PARAM;
1369 bool exportable = policyPrivate.extractable || policyPublic.extractable;
1370 Policy lessRestricted(Password(), exportable, policyPrivate.backend);
1372 TokenPair keys = m_decider.getStore(dt, lessRestricted).generateAKey(keyGenParams,
1373 policyPrivate.password,
1374 policyPublic.password);
1376 DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
1377 // in case the same database is used for private and public - the second
1378 // transaction will not be executed
1379 DB::Crypto::Transaction transactionPub(&handlerPub.database);
1382 retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerLabelPrv);
1384 if (CKM_API_SUCCESS != retCode)
1387 retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerLabelPub);
1389 if (CKM_API_SUCCESS != retCode)
1393 DB::Row rowPrv(std::move(keys.first), namePrivate, ownerLabelPrv,
1394 static_cast<int>(policyPrivate.extractable));
1395 handlerPriv.crypto.encryptRow(rowPrv);
1396 handlerPriv.database.saveRow(rowPrv);
1398 DB::Row rowPub(std::move(keys.second), namePublic, ownerLabelPub,
1399 static_cast<int>(policyPublic.extractable));
1400 handlerPub.crypto.encryptRow(rowPub);
1401 handlerPub.database.saveRow(rowPub);
1403 transactionPub.commit();
1404 transactionPriv.commit();
1405 return CKM_API_SUCCESS;
1408 RawBuffer CKMLogic::createKeyPair(
1409 const Credentials &cred,
1411 const CryptoAlgorithmSerializable &keyGenParams,
1412 const Name &namePrivate,
1413 const Label &labelPrivate,
1414 const Name &namePublic,
1415 const Label &labelPublic,
1416 const PolicySerializable &policyPrivate,
1417 const PolicySerializable &policyPublic)
1419 int retCode = CKM_API_SUCCESS;
1422 retCode = createKeyPairHelper(
1431 } catch (const Exc::Exception &e) {
1432 retCode = e.error();
1433 } catch (const CKM::Exception &e) {
1434 LogError("CKM::Exception: " << e.GetMessage());
1435 retCode = CKM_API_ERROR_SERVER_ERROR;
1438 return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
1439 commandId, retCode).Pop();
1442 RawBuffer CKMLogic::createKeyAES(
1443 const Credentials &cred,
1448 const PolicySerializable &policy)
1450 int retCode = CKM_API_SUCCESS;
1453 retCode = createKeyAESHelper(cred, size, name, label, policy);
1454 } catch (const Exc::Exception &e) {
1455 retCode = e.error();
1456 } catch (std::invalid_argument &e) {
1457 LogDebug("invalid argument error: " << e.what());
1458 retCode = CKM_API_ERROR_INPUT_PARAM;
1459 } catch (const CKM::Exception &e) {
1460 LogError("CKM::Exception: " << e.GetMessage());
1461 retCode = CKM_API_ERROR_SERVER_ERROR;
1464 return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
1465 commandId, retCode).Pop();
1468 int CKMLogic::readCertificateHelper(
1469 const Credentials &cred,
1470 const LabelNameVector &labelNameVector,
1471 CertificateImplVector &certVector)
1473 for (auto &i : labelNameVector) {
1474 // certificates can't be protected with custom user password
1475 Crypto::GObjUPtr obj;
1477 ec = readDataHelper(true,
1479 DataType::CERTIFICATE,
1485 if (ec != CKM_API_SUCCESS)
1488 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1490 // try to read chain certificates (if present)
1491 Crypto::GObjUPtrVector caChainObjs;
1492 ec = readDataHelper(true,
1494 DataType::DB_CHAIN_FIRST,
1500 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1503 for (auto &caCertObj : caChainObjs)
1504 certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1507 return CKM_API_SUCCESS;
1510 int CKMLogic::getCertificateChainHelper(
1511 const CertificateImpl &cert,
1512 const RawBufferVector &untrustedCertificates,
1513 const RawBufferVector &trustedCertificates,
1514 bool useTrustedSystemCertificates,
1515 RawBufferVector &chainRawVector)
1517 CertificateImplVector untrustedCertVector;
1518 CertificateImplVector trustedCertVector;
1519 CertificateImplVector chainVector;
1522 return CKM_API_ERROR_INPUT_PARAM;
1524 for (auto &e : untrustedCertificates) {
1525 CertificateImpl c(e, DataFormat::FORM_DER);
1528 return CKM_API_ERROR_INPUT_PARAM;
1530 untrustedCertVector.push_back(std::move(c));
1533 for (auto &e : trustedCertificates) {
1534 CertificateImpl c(e, DataFormat::FORM_DER);
1537 return CKM_API_ERROR_INPUT_PARAM;
1539 trustedCertVector.push_back(std::move(c));
1542 CertificateStore store;
1543 int retCode = store.verifyCertificate(cert,
1544 untrustedCertVector,
1546 useTrustedSystemCertificates,
1547 m_accessControl.isCCMode(),
1550 if (retCode != CKM_API_SUCCESS)
1553 for (auto &e : chainVector)
1554 chainRawVector.push_back(e.getDER());
1556 return CKM_API_SUCCESS;
1559 int CKMLogic::getCertificateChainHelper(
1560 const Credentials &cred,
1561 const CertificateImpl &cert,
1562 const LabelNameVector &untrusted,
1563 const LabelNameVector &trusted,
1564 bool useTrustedSystemCertificates,
1565 RawBufferVector &chainRawVector)
1567 CertificateImplVector untrustedCertVector;
1568 CertificateImplVector trustedCertVector;
1569 CertificateImplVector chainVector;
1572 return CKM_API_ERROR_INPUT_PARAM;
1574 int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1576 if (retCode != CKM_API_SUCCESS)
1579 retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1581 if (retCode != CKM_API_SUCCESS)
1584 CertificateStore store;
1585 retCode = store.verifyCertificate(cert,
1586 untrustedCertVector,
1588 useTrustedSystemCertificates,
1589 m_accessControl.isCCMode(),
1592 if (retCode != CKM_API_SUCCESS)
1595 for (auto &i : chainVector)
1596 chainRawVector.push_back(i.getDER());
1598 return CKM_API_SUCCESS;
1601 RawBuffer CKMLogic::getCertificateChain(
1602 const Credentials & /*cred*/,
1604 const RawBuffer &certificate,
1605 const RawBufferVector &untrustedCertificates,
1606 const RawBufferVector &trustedCertificates,
1607 bool useTrustedSystemCertificates)
1609 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1610 RawBufferVector chainRawVector;
1611 int retCode = CKM_API_ERROR_UNKNOWN;
1614 retCode = getCertificateChainHelper(cert,
1615 untrustedCertificates,
1616 trustedCertificates,
1617 useTrustedSystemCertificates,
1619 } catch (const Exc::Exception &e) {
1620 retCode = e.error();
1621 } catch (const std::exception &e) {
1622 LogError("STD exception " << e.what());
1623 retCode = CKM_API_ERROR_SERVER_ERROR;
1625 LogError("Unknown error.");
1628 auto response = MessageBuffer::Serialize(static_cast<int>
1629 (LogicCommand::GET_CHAIN_CERT),
1633 return response.Pop();
1636 RawBuffer CKMLogic::getCertificateChain(
1637 const Credentials &cred,
1639 const RawBuffer &certificate,
1640 const LabelNameVector &untrustedCertificates,
1641 const LabelNameVector &trustedCertificates,
1642 bool useTrustedSystemCertificates)
1644 int retCode = CKM_API_ERROR_UNKNOWN;
1645 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1646 RawBufferVector chainRawVector;
1649 retCode = getCertificateChainHelper(cred,
1651 untrustedCertificates,
1652 trustedCertificates,
1653 useTrustedSystemCertificates,
1655 } catch (const Exc::Exception &e) {
1656 retCode = e.error();
1657 } catch (const std::exception &e) {
1658 LogError("STD exception " << e.what());
1659 retCode = CKM_API_ERROR_SERVER_ERROR;
1661 LogError("Unknown error.");
1664 auto response = MessageBuffer::Serialize(static_cast<int>
1665 (LogicCommand::GET_CHAIN_ALIAS),
1669 return response.Pop();
1672 RawBuffer CKMLogic::createSignature(
1673 const Credentials &cred,
1675 const Name &privateKeyName,
1676 const Label &ownerLabel,
1677 const Password &password, // password for private_key
1678 const RawBuffer &message,
1679 const CryptoAlgorithm &cryptoAlg)
1681 RawBuffer signature;
1683 int retCode = CKM_API_SUCCESS;
1686 Crypto::GObjUPtr obj;
1687 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1688 ownerLabel, password, obj);
1690 if (retCode == CKM_API_SUCCESS)
1691 signature = obj->sign(cryptoAlg, message);
1692 } catch (const Exc::Exception &e) {
1693 retCode = e.error();
1694 } catch (const CKM::Exception &e) {
1695 LogError("Unknown CKM::Exception: " << e.GetMessage());
1696 retCode = CKM_API_ERROR_SERVER_ERROR;
1697 } catch (const std::exception &e) {
1698 LogError("STD exception " << e.what());
1699 retCode = CKM_API_ERROR_SERVER_ERROR;
1702 auto response = MessageBuffer::Serialize(static_cast<int>
1703 (LogicCommand::CREATE_SIGNATURE),
1707 return response.Pop();
1710 RawBuffer CKMLogic::verifySignature(
1711 const Credentials &cred,
1713 const Name &publicKeyOrCertName,
1714 const Label &ownerLabel,
1715 const Password &password, // password for public_key (optional)
1716 const RawBuffer &message,
1717 const RawBuffer &signature,
1718 const CryptoAlgorithm ¶ms)
1720 int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1723 // try certificate first - looking for a public key.
1724 // in case of PKCS, pub key from certificate will be found first
1725 // rather than private key from the same PKCS.
1726 Crypto::GObjUPtr obj;
1727 retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
1728 publicKeyOrCertName, ownerLabel, password, obj);
1730 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1731 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1732 publicKeyOrCertName, ownerLabel, password, obj);
1734 if (retCode == CKM_API_SUCCESS)
1735 retCode = obj->verify(params, message, signature);
1736 } catch (const Exc::Exception &e) {
1737 retCode = e.error();
1738 } catch (const CKM::Exception &e) {
1739 LogError("Unknown CKM::Exception: " << e.GetMessage());
1740 retCode = CKM_API_ERROR_SERVER_ERROR;
1743 auto response = MessageBuffer::Serialize(static_cast<int>
1744 (LogicCommand::VERIFY_SIGNATURE),
1747 return response.Pop();
1750 int CKMLogic::setPermissionHelper(
1751 const Credentials &cred, // who's the client
1753 const Label &label, // who's the owner
1754 const Label &accessorLabel, // who will get the access
1755 const PermissionMask permissionMask)
1757 auto &handler = selectDatabase(cred, label);
1759 // we don't know the client
1760 if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel))
1761 return CKM_API_ERROR_INPUT_PARAM;
1763 // use client label if not explicitly provided
1764 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1766 // verify name and label are correct
1767 if (!isNameValid(name) || !isLabelValid(ownerLabel) ||
1768 !isLabelValid(accessorLabel))
1769 return CKM_API_ERROR_INPUT_PARAM;
1771 // currently we don't support modification of owner's permissions to his own rows
1772 if (ownerLabel == accessorLabel)
1773 return CKM_API_ERROR_INPUT_PARAM;
1775 // system database does not support write/remove permissions
1776 if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) &&
1777 (permissionMask & Permission::REMOVE))
1778 return CKM_API_ERROR_INPUT_PARAM;
1780 // can the client modify permissions to owner's row?
1781 int retCode = m_accessControl.canModify(cred, ownerLabel);
1783 if (retCode != CKM_API_SUCCESS)
1786 DB::Crypto::Transaction transaction(&handler.database);
1788 if (!handler.database.isNameLabelPresent(name, ownerLabel))
1789 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1791 // set permissions to the row owned by ownerLabel for accessorLabel
1792 handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask);
1793 transaction.commit();
1795 return CKM_API_SUCCESS;
1798 RawBuffer CKMLogic::setPermission(
1799 const Credentials &cred,
1804 const Label &accessorLabel,
1805 const PermissionMask permissionMask)
1810 retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
1811 } catch (const Exc::Exception &e) {
1812 retCode = e.error();
1813 } catch (const CKM::Exception &e) {
1814 LogError("Error: " << e.GetMessage());
1815 retCode = CKM_API_ERROR_DB_ERROR;
1818 return MessageBuffer::Serialize(command, msgID, retCode).Pop();
1821 int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel)
1823 if (!handle.crypto.haveKey(appLabel)) {
1825 auto key_optional = handle.database.getKey(appLabel);
1827 if (!key_optional) {
1828 LogError("No key for given label in database");
1829 return CKM_API_ERROR_DB_ERROR;
1832 key = *key_optional;
1833 key = handle.keyProvider.getPureDEK(key);
1834 handle.crypto.pushKey(appLabel, key);
1837 return CKM_API_SUCCESS;