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.extractable);
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)
493 // Key is for internal service use. It won't be exported to the client
494 Crypto::GObjUPtr obj;
495 int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, label,
498 if (retCode == CKM_API_SUCCESS)
499 key = std::move(obj);
502 } catch (const Exc::Exception &e) {
504 } catch (const CKM::Exception &e) {
505 LogError("CKM::Exception: " << e.GetMessage());
506 return CKM_API_ERROR_SERVER_ERROR;
510 RawBuffer CKMLogic::saveData(
511 const Credentials &cred,
515 const Crypto::Data &data,
516 const PolicySerializable &policy)
518 int retCode = verifyAndSaveDataHelper(cred, name, label, data, policy);
519 auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
522 static_cast<int>(data.type));
523 return response.Pop();
526 int CKMLogic::extractPKCS12Data(
529 const Label &ownerLabel,
530 const PKCS12Serializable &pkcs,
531 const PolicySerializable &keyPolicy,
532 const PolicySerializable &certPolicy,
533 DB::RowVector &output) const
535 // private key is mandatory
536 auto key = pkcs.getKey();
539 LogError("Failed to get private key from pkcs");
540 return CKM_API_ERROR_INVALID_FORMAT;
543 Crypto::Data keyData(DataType(key->getType()), key->getDER());
544 int retCode = verifyBinaryData(keyData);
546 if (retCode != CKM_API_SUCCESS)
549 output.push_back(createEncryptedRow(crypto, name, ownerLabel, keyData,
552 // certificate is mandatory
553 auto cert = pkcs.getCertificate();
556 LogError("Failed to get certificate from pkcs");
557 return CKM_API_ERROR_INVALID_FORMAT;
560 Crypto::Data certData(DataType::CERTIFICATE, cert->getDER());
561 retCode = verifyBinaryData(certData);
563 if (retCode != CKM_API_SUCCESS)
566 output.push_back(createEncryptedRow(crypto, name, ownerLabel, certData,
570 unsigned int cert_index = 0;
572 for (const auto &ca : pkcs.getCaCertificateShPtrVector()) {
573 Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++),
575 int retCode = verifyBinaryData(caCertData);
577 if (retCode != CKM_API_SUCCESS)
580 output.push_back(createEncryptedRow(crypto, name, ownerLabel, caCertData,
584 return CKM_API_SUCCESS;
587 RawBuffer CKMLogic::savePKCS12(
588 const Credentials &cred,
592 const PKCS12Serializable &pkcs,
593 const PolicySerializable &keyPolicy,
594 const PolicySerializable &certPolicy)
596 int retCode = CKM_API_ERROR_UNKNOWN;
599 retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy);
600 } catch (const Exc::Exception &e) {
602 } catch (const CKM::Exception &e) {
603 LogError("CKM::Exception: " << e.GetMessage());
604 retCode = CKM_API_ERROR_SERVER_ERROR;
607 auto response = MessageBuffer::Serialize(static_cast<int>
608 (LogicCommand::SAVE_PKCS12),
611 return response.Pop();
615 int CKMLogic::removeDataHelper(
616 const Credentials &cred,
620 auto &handler = selectDatabase(cred, label);
622 // use client label if not explicitly provided
623 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
625 if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
626 LogDebug("Invalid label or name format");
627 return CKM_API_ERROR_INPUT_PARAM;
630 DB::Crypto::Transaction transaction(&handler.database);
632 // read and check permissions
633 PermissionMaskOptional permissionRowOpt =
634 handler.database.getPermissionRow(name, ownerLabel, cred.smackLabel);
635 int retCode = m_accessControl.canDelete(cred,
636 PermissionForLabel(cred.smackLabel, permissionRowOpt));
638 if (retCode != CKM_API_SUCCESS) {
639 LogWarning("access control check result: " << retCode);
643 // get all matching rows
645 handler.database.getRows(name, ownerLabel, DataType::DB_FIRST,
646 DataType::DB_LAST, rows);
649 LogDebug("No row for given name and label");
650 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
653 // load app key if needed
654 retCode = loadAppKey(handler, rows.front().ownerLabel);
656 if (CKM_API_SUCCESS != retCode)
659 // destroy it in store
660 for (auto &r : rows) {
662 handler.crypto.decryptRow(Password(), r);
663 m_decider.getStore(r).destroy(r);
664 } catch (const Exc::AuthenticationFailed &) {
665 LogDebug("Authentication failed when removing data. Ignored.");
670 handler.database.deleteRow(name, ownerLabel);
671 transaction.commit();
673 return CKM_API_SUCCESS;
676 RawBuffer CKMLogic::removeData(
677 const Credentials &cred,
682 int retCode = CKM_API_ERROR_UNKNOWN;
685 retCode = removeDataHelper(cred, name, label);
686 } catch (const Exc::Exception &e) {
688 } catch (const CKM::Exception &e) {
689 LogError("Error: " << e.GetMessage());
690 retCode = CKM_API_ERROR_DB_ERROR;
693 auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::REMOVE),
696 return response.Pop();
699 int CKMLogic::readSingleRow(const Name &name,
700 const Label &ownerLabel,
702 DB::Crypto &database,
705 DB::Crypto::RowOptional row_optional;
707 if (dataType.isKey()) {
708 // read all key types
709 row_optional = database.getRow(name,
711 DataType::DB_KEY_FIRST,
712 DataType::DB_KEY_LAST);
714 // read anything else
715 row_optional = database.getRow(name,
721 LogDebug("No row for given name, label and type");
722 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
727 return CKM_API_SUCCESS;
731 int CKMLogic::readMultiRow(const Name &name,
732 const Label &ownerLabel,
734 DB::Crypto &database,
735 DB::RowVector &output)
737 if (dataType.isKey())
738 // read all key types
739 database.getRows(name,
741 DataType::DB_KEY_FIRST,
742 DataType::DB_KEY_LAST,
744 else if (dataType.isChainCert())
745 // read all key types
746 database.getRows(name,
748 DataType::DB_CHAIN_FIRST,
749 DataType::DB_CHAIN_LAST,
752 // read anything else
753 database.getRows(name,
758 if (!output.size()) {
759 LogDebug("No row for given name, label and type");
760 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
763 return CKM_API_SUCCESS;
766 int CKMLogic::checkDataPermissionsHelper(const Credentials &cred,
768 const Label &ownerLabel,
769 const Label &accessorLabel,
772 DB::Crypto &database)
774 PermissionMaskOptional permissionRowOpt =
775 database.getPermissionRow(name, ownerLabel, accessorLabel);
778 return m_accessControl.canExport(cred, row, PermissionForLabel(accessorLabel,
781 return m_accessControl.canRead(cred, PermissionForLabel(accessorLabel,
785 Crypto::GObjUPtr CKMLogic::rowToObject(
788 const Password &password)
790 Crypto::GStore &store = m_decider.getStore(row);
792 Password pass = m_accessControl.isCCMode() ? "" : password;
795 Crypto::GObjUPtr obj;
797 if (CryptoLogic::getSchemeVersion(row.encryptionScheme) ==
798 CryptoLogic::ENCRYPTION_V2) {
799 handler.crypto.decryptRow(Password(), row);
801 obj = store.getObject(row, pass);
803 // decrypt entirely with old scheme: b64(pass(appkey(data))) -> data
804 handler.crypto.decryptRow(pass, row);
805 // destroy it in store
808 // import it to store with new scheme: data -> pass(data)
809 Token token = store.import(Crypto::Data(row.dataType, row.data), pass);
811 // get it from the store (it can be different than the data we imported into store)
812 obj = store.getObject(token, pass);
814 // update row with new token
815 *static_cast<Token *>(&row) = std::move(token);
817 // encrypt it with app key: pass(data) -> b64(appkey(pass(data))
818 handler.crypto.encryptRow(row);
821 handler.database.updateRow(row);
827 int CKMLogic::readDataHelper(
829 const Credentials &cred,
833 const Password &password,
834 Crypto::GObjUPtrVector &objs)
836 auto &handler = selectDatabase(cred, label);
838 // use client label if not explicitly provided
839 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
841 if (!isNameValid(name) || !isLabelValid(ownerLabel))
842 return CKM_API_ERROR_INPUT_PARAM;
845 DB::Crypto::Transaction transaction(&handler.database);
847 int retCode = readMultiRow(name, ownerLabel, dataType, handler.database, rows);
849 if (CKM_API_SUCCESS != retCode)
852 // all read rows belong to the same owner
853 DB::Row &firstRow = rows.at(0);
855 // check access rights
856 retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
857 firstRow, exportFlag, handler.database);
859 if (CKM_API_SUCCESS != retCode)
862 // load app key if needed
863 retCode = loadAppKey(handler, firstRow.ownerLabel);
865 if (CKM_API_SUCCESS != retCode)
869 for (auto &row : rows)
870 objs.push_back(rowToObject(handler, std::move(row), password));
872 // rowToObject may modify db
873 transaction.commit();
875 return CKM_API_SUCCESS;
878 int CKMLogic::readDataHelper(
880 const Credentials &cred,
884 const Password &password,
885 Crypto::GObjUPtr &obj)
887 DataType objDataType;
888 return readDataHelper(exportFlag, cred, dataType, name, label, password, obj,
892 int CKMLogic::readDataHelper(
894 const Credentials &cred,
898 const Password &password,
899 Crypto::GObjUPtr &obj,
900 DataType &objDataType)
902 auto &handler = selectDatabase(cred, label);
904 // use client label if not explicitly provided
905 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
907 if (!isNameValid(name) || !isLabelValid(ownerLabel))
908 return CKM_API_ERROR_INPUT_PARAM;
911 DB::Crypto::Transaction transaction(&handler.database);
913 int retCode = readSingleRow(name, ownerLabel, dataType, handler.database, row);
915 if (CKM_API_SUCCESS != retCode)
918 objDataType = row.dataType;
920 // check access rights
921 retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
922 row, exportFlag, handler.database);
924 if (CKM_API_SUCCESS != retCode)
927 // load app key if needed
928 retCode = loadAppKey(handler, row.ownerLabel);
930 if (CKM_API_SUCCESS != retCode)
933 obj = rowToObject(handler, std::move(row), password);
934 // rowToObject may modify db
935 transaction.commit();
937 return CKM_API_SUCCESS;
940 RawBuffer CKMLogic::getData(
941 const Credentials &cred,
946 const Password &password)
948 int retCode = CKM_API_SUCCESS;
950 DataType objDataType;
953 Crypto::GObjUPtr obj;
954 retCode = readDataHelper(true, cred, dataType, name, label, password, obj,
957 if (retCode == CKM_API_SUCCESS)
958 row.data = std::move(obj->getBinary());
959 } catch (const Exc::Exception &e) {
961 } catch (const CKM::Exception &e) {
962 LogError("CKM::Exception: " << e.GetMessage());
963 retCode = CKM_API_ERROR_SERVER_ERROR;
966 if (CKM_API_SUCCESS != retCode) {
968 row.dataType = dataType;
971 auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET),
974 static_cast<int>(objDataType),
976 return response.Pop();
979 int CKMLogic::getPKCS12Helper(
980 const Credentials &cred,
983 const Password &keyPassword,
984 const Password &certPassword,
986 CertificateShPtr &cert,
987 CertificateShPtrVector &caChain)
991 // read private key (mandatory)
992 Crypto::GObjUPtr keyObj;
993 retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, label,
994 keyPassword, keyObj);
996 if (retCode != CKM_API_SUCCESS) {
997 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1000 privKey = CKM::Key::create(keyObj->getBinary());
1003 // read certificate (mandatory)
1004 Crypto::GObjUPtr certObj;
1005 retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, label,
1006 certPassword, certObj);
1008 if (retCode != CKM_API_SUCCESS) {
1009 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1012 cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER);
1015 // read CA cert chain (optional)
1016 Crypto::GObjUPtrVector caChainObjs;
1017 retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, label,
1018 certPassword, caChainObjs);
1020 if (retCode != CKM_API_SUCCESS && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
1021 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1024 for (auto &caCertObj : caChainObjs)
1025 caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(),
1026 DataFormat::FORM_DER));
1029 // if anything found, return it
1030 if (privKey || cert || caChain.size() > 0)
1031 retCode = CKM_API_SUCCESS;
1036 RawBuffer CKMLogic::getPKCS12(
1037 const Credentials &cred,
1041 const Password &keyPassword,
1042 const Password &certPassword)
1044 int retCode = CKM_API_ERROR_UNKNOWN;
1046 PKCS12Serializable output;
1050 CertificateShPtr cert;
1051 CertificateShPtrVector caChain;
1052 retCode = getPKCS12Helper(cred, name, label, keyPassword, certPassword, privKey,
1056 if (retCode == CKM_API_SUCCESS)
1057 output = PKCS12Serializable(std::move(privKey), std::move(cert),
1058 std::move(caChain));
1059 } catch (const Exc::Exception &e) {
1060 retCode = e.error();
1061 } catch (const CKM::Exception &e) {
1062 LogError("CKM::Exception: " << e.GetMessage());
1063 retCode = CKM_API_ERROR_SERVER_ERROR;
1066 auto response = MessageBuffer::Serialize(static_cast<int>
1067 (LogicCommand::GET_PKCS12),
1071 return response.Pop();
1074 int CKMLogic::getDataListHelper(const Credentials &cred,
1075 const DataType dataType,
1076 LabelNameVector &labelNameVector)
1078 int retCode = CKM_API_ERROR_DB_LOCKED;
1080 if (0 < m_userDataMap.count(cred.clientUid)) {
1081 auto &database = m_userDataMap[cred.clientUid].database;
1084 LabelNameVector tmpVector;
1086 if (dataType.isKey()) {
1087 // list all key types
1088 database.listNames(cred.smackLabel,
1090 DataType::DB_KEY_FIRST,
1091 DataType::DB_KEY_LAST);
1093 // list anything else
1094 database.listNames(cred.smackLabel,
1099 labelNameVector.insert(labelNameVector.end(), tmpVector.begin(),
1101 retCode = CKM_API_SUCCESS;
1102 } catch (const CKM::Exception &e) {
1103 LogError("Error: " << e.GetMessage());
1104 retCode = CKM_API_ERROR_DB_ERROR;
1105 } catch (const Exc::Exception &e) {
1106 retCode = e.error();
1113 RawBuffer CKMLogic::getDataList(
1114 const Credentials &cred,
1118 LabelNameVector systemVector;
1119 LabelNameVector userVector;
1120 LabelNameVector labelNameVector;
1122 int retCode = unlockSystemDB();
1124 if (CKM_API_SUCCESS == retCode) {
1126 if (m_accessControl.isSystemService(cred)) {
1128 retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1133 // user - lookup system, then client DB
1134 retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1140 if (retCode == CKM_API_SUCCESS) {
1141 retCode = getDataListHelper(cred,
1148 if (retCode == CKM_API_SUCCESS) {
1149 labelNameVector.insert(labelNameVector.end(), systemVector.begin(),
1150 systemVector.end());
1151 labelNameVector.insert(labelNameVector.end(), userVector.begin(),
1155 auto response = MessageBuffer::Serialize(static_cast<int>
1156 (LogicCommand::GET_LIST),
1159 static_cast<int>(dataType),
1161 return response.Pop();
1164 int CKMLogic::importInitialData(
1166 const Crypto::Data &data,
1167 const Crypto::DataEncryption &enc,
1168 const Policy &policy)
1171 // Inital values are always imported with root credentials. Label is not important.
1172 Credentials rootCred(0, "");
1174 auto &handler = selectDatabase(rootCred, OWNER_ID_SYSTEM);
1176 // check if save is possible
1177 DB::Crypto::Transaction transaction(&handler.database);
1178 int retCode = checkSaveConditions(rootCred, handler, name, OWNER_ID_SYSTEM);
1180 if (retCode != CKM_API_SUCCESS)
1183 Crypto::GStore &store =
1184 m_decider.getStore(data.type, policy.extractable, !enc.encryptedKey.empty());
1188 if (enc.encryptedKey.empty()) {
1189 Crypto::Data binaryData;
1191 if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
1194 token = store.import(binaryData,
1195 m_accessControl.isCCMode() ? "" : policy.password);
1197 token = store.importEncrypted(data,
1198 m_accessControl.isCCMode() ? "" : policy.password, enc);
1201 DB::Row row(std::move(token), name, OWNER_ID_SYSTEM,
1202 static_cast<int>(policy.extractable));
1203 handler.crypto.encryptRow(row);
1205 handler.database.saveRow(row);
1206 transaction.commit();
1207 } catch (const Exc::Exception &e) {
1209 } catch (const CKM::Exception &e) {
1210 LogError("CKM::Exception: " << e.GetMessage());
1211 return CKM_API_ERROR_SERVER_ERROR;
1212 } catch (const std::exception &e) {
1213 LogError("Std::exception: " << e.what());
1214 return CKM_API_ERROR_SERVER_ERROR;
1217 return CKM_API_SUCCESS;
1220 int CKMLogic::saveDataHelper(
1221 const Credentials &cred,
1224 const Crypto::Data &data,
1225 const PolicySerializable &policy)
1227 auto &handler = selectDatabase(cred, label);
1229 // use client label if not explicitly provided
1230 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1232 if (m_accessControl.isSystemService(cred) &&
1233 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1234 return CKM_API_ERROR_INPUT_PARAM;
1236 // check if save is possible
1237 DB::Crypto::Transaction transaction(&handler.database);
1238 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1240 if (retCode != CKM_API_SUCCESS)
1244 DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, ownerLabel,
1246 handler.database.saveRow(encryptedRow);
1248 transaction.commit();
1249 return CKM_API_SUCCESS;
1252 int CKMLogic::saveDataHelper(
1253 const Credentials &cred,
1256 const PKCS12Serializable &pkcs,
1257 const PolicySerializable &keyPolicy,
1258 const PolicySerializable &certPolicy)
1260 auto &handler = selectDatabase(cred, label);
1262 // use client label if not explicitly provided
1263 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1265 if (m_accessControl.isSystemService(cred) &&
1266 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1267 return CKM_API_ERROR_INPUT_PARAM;
1269 // check if save is possible
1270 DB::Crypto::Transaction transaction(&handler.database);
1271 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1273 if (retCode != CKM_API_SUCCESS)
1276 // extract and encrypt the data
1277 DB::RowVector encryptedRows;
1278 retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy,
1279 certPolicy, encryptedRows);
1281 if (retCode != CKM_API_SUCCESS)
1285 handler.database.saveRows(name, ownerLabel, encryptedRows);
1286 transaction.commit();
1288 return CKM_API_SUCCESS;
1292 int CKMLogic::createKeyAESHelper(
1293 const Credentials &cred,
1297 const PolicySerializable &policy)
1299 auto &handler = selectDatabase(cred, label);
1301 // use client label if not explicitly provided
1302 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1304 if (m_accessControl.isSystemService(cred) &&
1305 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1306 return CKM_API_ERROR_INPUT_PARAM;
1308 // check if save is possible
1309 DB::Crypto::Transaction transaction(&handler.database);
1310 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1312 if (retCode != CKM_API_SUCCESS)
1315 // create key in store
1316 CryptoAlgorithm keyGenAlgorithm;
1317 keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::AES_GEN);
1318 keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, size);
1319 Token key = m_decider.getStore(DataType::KEY_AES,
1320 policy.extractable).generateSKey(keyGenAlgorithm, policy.password);
1323 DB::Row row(std::move(key), name, ownerLabel,
1324 static_cast<int>(policy.extractable));
1325 handler.crypto.encryptRow(row);
1327 handler.database.saveRow(row);
1329 transaction.commit();
1330 return CKM_API_SUCCESS;
1333 int CKMLogic::createKeyPairHelper(
1334 const Credentials &cred,
1335 const CryptoAlgorithmSerializable &keyGenParams,
1336 const Name &namePrivate,
1337 const Label &labelPrivate,
1338 const Name &namePublic,
1339 const Label &labelPublic,
1340 const PolicySerializable &policyPrivate,
1341 const PolicySerializable &policyPublic)
1343 auto &handlerPriv = selectDatabase(cred, labelPrivate);
1344 auto &handlerPub = selectDatabase(cred, labelPublic);
1346 AlgoType keyType = AlgoType::RSA_GEN;
1348 if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
1349 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
1351 DataType dt(keyType);
1354 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
1356 // use client label if not explicitly provided
1357 const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel :
1360 if (m_accessControl.isSystemService(cred) &&
1361 ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0)
1362 return CKM_API_ERROR_INPUT_PARAM;
1364 const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel :
1367 if (m_accessControl.isSystemService(cred) &&
1368 ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0)
1369 return CKM_API_ERROR_INPUT_PARAM;
1371 bool exportable = policyPrivate.extractable || policyPublic.extractable;
1372 TokenPair keys = m_decider.getStore(dt, exportable).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)
1475 for (auto &i : labelNameVector) {
1476 // certificates can't be protected with custom user password
1477 Crypto::GObjUPtr obj;
1479 ec = readDataHelper(true,
1481 DataType::CERTIFICATE,
1487 if (ec != CKM_API_SUCCESS)
1490 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1492 // try to read chain certificates (if present)
1493 Crypto::GObjUPtrVector caChainObjs;
1494 ec = readDataHelper(true,
1496 DataType::DB_CHAIN_FIRST,
1502 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1505 for (auto &caCertObj : caChainObjs)
1506 certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1509 return CKM_API_SUCCESS;
1512 int CKMLogic::getCertificateChainHelper(
1513 const CertificateImpl &cert,
1514 const RawBufferVector &untrustedCertificates,
1515 const RawBufferVector &trustedCertificates,
1516 bool useTrustedSystemCertificates,
1517 RawBufferVector &chainRawVector)
1519 CertificateImplVector untrustedCertVector;
1520 CertificateImplVector trustedCertVector;
1521 CertificateImplVector chainVector;
1524 return CKM_API_ERROR_INPUT_PARAM;
1526 for (auto &e : untrustedCertificates) {
1527 CertificateImpl c(e, DataFormat::FORM_DER);
1530 return CKM_API_ERROR_INPUT_PARAM;
1532 untrustedCertVector.push_back(std::move(c));
1535 for (auto &e : trustedCertificates) {
1536 CertificateImpl c(e, DataFormat::FORM_DER);
1539 return CKM_API_ERROR_INPUT_PARAM;
1541 trustedCertVector.push_back(std::move(c));
1544 CertificateStore store;
1545 int retCode = store.verifyCertificate(cert,
1546 untrustedCertVector,
1548 useTrustedSystemCertificates,
1549 m_accessControl.isCCMode(),
1552 if (retCode != CKM_API_SUCCESS)
1555 for (auto &e : chainVector)
1556 chainRawVector.push_back(e.getDER());
1558 return CKM_API_SUCCESS;
1561 int CKMLogic::getCertificateChainHelper(
1562 const Credentials &cred,
1563 const CertificateImpl &cert,
1564 const LabelNameVector &untrusted,
1565 const LabelNameVector &trusted,
1566 bool useTrustedSystemCertificates,
1567 RawBufferVector &chainRawVector)
1569 CertificateImplVector untrustedCertVector;
1570 CertificateImplVector trustedCertVector;
1571 CertificateImplVector chainVector;
1575 return CKM_API_ERROR_INPUT_PARAM;
1577 int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1579 if (retCode != CKM_API_SUCCESS)
1582 retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1584 if (retCode != CKM_API_SUCCESS)
1587 CertificateStore store;
1588 retCode = store.verifyCertificate(cert,
1589 untrustedCertVector,
1591 useTrustedSystemCertificates,
1592 m_accessControl.isCCMode(),
1595 if (retCode != CKM_API_SUCCESS)
1598 for (auto &i : chainVector)
1599 chainRawVector.push_back(i.getDER());
1601 return CKM_API_SUCCESS;
1604 RawBuffer CKMLogic::getCertificateChain(
1605 const Credentials & /*cred*/,
1607 const RawBuffer &certificate,
1608 const RawBufferVector &untrustedCertificates,
1609 const RawBufferVector &trustedCertificates,
1610 bool useTrustedSystemCertificates)
1612 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1613 RawBufferVector chainRawVector;
1614 int retCode = CKM_API_ERROR_UNKNOWN;
1617 retCode = getCertificateChainHelper(cert,
1618 untrustedCertificates,
1619 trustedCertificates,
1620 useTrustedSystemCertificates,
1622 } catch (const Exc::Exception &e) {
1623 retCode = e.error();
1624 } catch (const std::exception &e) {
1625 LogError("STD exception " << e.what());
1626 retCode = CKM_API_ERROR_SERVER_ERROR;
1628 LogError("Unknown error.");
1631 auto response = MessageBuffer::Serialize(static_cast<int>
1632 (LogicCommand::GET_CHAIN_CERT),
1636 return response.Pop();
1639 RawBuffer CKMLogic::getCertificateChain(
1640 const Credentials &cred,
1642 const RawBuffer &certificate,
1643 const LabelNameVector &untrustedCertificates,
1644 const LabelNameVector &trustedCertificates,
1645 bool useTrustedSystemCertificates)
1647 int retCode = CKM_API_ERROR_UNKNOWN;
1648 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1649 RawBufferVector chainRawVector;
1652 retCode = getCertificateChainHelper(cred,
1654 untrustedCertificates,
1655 trustedCertificates,
1656 useTrustedSystemCertificates,
1658 } catch (const Exc::Exception &e) {
1659 retCode = e.error();
1660 } catch (const std::exception &e) {
1661 LogError("STD exception " << e.what());
1662 retCode = CKM_API_ERROR_SERVER_ERROR;
1664 LogError("Unknown error.");
1667 auto response = MessageBuffer::Serialize(static_cast<int>
1668 (LogicCommand::GET_CHAIN_ALIAS),
1672 return response.Pop();
1675 RawBuffer CKMLogic::createSignature(
1676 const Credentials &cred,
1678 const Name &privateKeyName,
1679 const Label &ownerLabel,
1680 const Password &password, // password for private_key
1681 const RawBuffer &message,
1682 const CryptoAlgorithm &cryptoAlg)
1685 RawBuffer signature;
1687 int retCode = CKM_API_SUCCESS;
1690 Crypto::GObjUPtr obj;
1691 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1692 ownerLabel, password, obj);
1694 if (retCode == CKM_API_SUCCESS)
1695 signature = obj->sign(cryptoAlg, message);
1696 } catch (const Exc::Exception &e) {
1697 retCode = e.error();
1698 } catch (const CKM::Exception &e) {
1699 LogError("Unknown CKM::Exception: " << e.GetMessage());
1700 retCode = CKM_API_ERROR_SERVER_ERROR;
1701 } catch (const std::exception &e) {
1702 LogError("STD exception " << e.what());
1703 retCode = CKM_API_ERROR_SERVER_ERROR;
1706 auto response = MessageBuffer::Serialize(static_cast<int>
1707 (LogicCommand::CREATE_SIGNATURE),
1711 return response.Pop();
1714 RawBuffer CKMLogic::verifySignature(
1715 const Credentials &cred,
1717 const Name &publicKeyOrCertName,
1718 const Label &ownerLabel,
1719 const Password &password, // password for public_key (optional)
1720 const RawBuffer &message,
1721 const RawBuffer &signature,
1722 const CryptoAlgorithm ¶ms)
1724 int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1729 // try certificate first - looking for a public key.
1730 // in case of PKCS, pub key from certificate will be found first
1731 // rather than private key from the same PKCS.
1732 Crypto::GObjUPtr obj;
1733 retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
1734 publicKeyOrCertName, ownerLabel, password, obj);
1736 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1737 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1738 publicKeyOrCertName, ownerLabel, password, obj);
1740 if (retCode == CKM_API_SUCCESS)
1741 retCode = obj->verify(params, message, signature);
1742 } catch (const Exc::Exception &e) {
1743 retCode = e.error();
1744 } catch (const CKM::Exception &e) {
1745 LogError("Unknown CKM::Exception: " << e.GetMessage());
1746 retCode = CKM_API_ERROR_SERVER_ERROR;
1749 auto response = MessageBuffer::Serialize(static_cast<int>
1750 (LogicCommand::VERIFY_SIGNATURE),
1753 return response.Pop();
1756 int CKMLogic::setPermissionHelper(
1757 const Credentials &cred, // who's the client
1759 const Label &label, // who's the owner
1760 const Label &accessorLabel, // who will get the access
1761 const PermissionMask permissionMask)
1763 auto &handler = selectDatabase(cred, label);
1765 // we don't know the client
1766 if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel))
1767 return CKM_API_ERROR_INPUT_PARAM;
1769 // use client label if not explicitly provided
1770 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1772 // verify name and label are correct
1773 if (!isNameValid(name) || !isLabelValid(ownerLabel) ||
1774 !isLabelValid(accessorLabel))
1775 return CKM_API_ERROR_INPUT_PARAM;
1777 // currently we don't support modification of owner's permissions to his own rows
1778 if (ownerLabel == accessorLabel)
1779 return CKM_API_ERROR_INPUT_PARAM;
1781 // system database does not support write/remove permissions
1782 if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) &&
1783 (permissionMask & Permission::REMOVE))
1784 return CKM_API_ERROR_INPUT_PARAM;
1786 // can the client modify permissions to owner's row?
1787 int retCode = m_accessControl.canModify(cred, ownerLabel);
1789 if (retCode != CKM_API_SUCCESS)
1792 DB::Crypto::Transaction transaction(&handler.database);
1794 if (!handler.database.isNameLabelPresent(name, ownerLabel))
1795 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1797 // set permissions to the row owned by ownerLabel for accessorLabel
1798 handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask);
1799 transaction.commit();
1801 return CKM_API_SUCCESS;
1804 RawBuffer CKMLogic::setPermission(
1805 const Credentials &cred,
1810 const Label &accessorLabel,
1811 const PermissionMask permissionMask)
1816 retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
1817 } catch (const Exc::Exception &e) {
1818 retCode = e.error();
1819 } catch (const CKM::Exception &e) {
1820 LogError("Error: " << e.GetMessage());
1821 retCode = CKM_API_ERROR_DB_ERROR;
1824 return MessageBuffer::Serialize(command, msgID, retCode).Pop();
1827 int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel)
1829 if (!handle.crypto.haveKey(appLabel)) {
1831 auto key_optional = handle.database.getKey(appLabel);
1833 if (!key_optional) {
1834 LogError("No key for given label in database");
1835 return CKM_API_ERROR_DB_ERROR;
1838 key = *key_optional;
1839 key = handle.keyProvider.getPureDEK(key);
1840 handle.crypto.pushKey(appLabel, key);
1843 return CKM_API_SUCCESS;