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)
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 =
1180 m_decider.getStore(data.type, policy.extractable, !enc.encryptedKey.empty());
1184 if (enc.encryptedKey.empty()) {
1185 Crypto::Data binaryData;
1187 if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
1190 token = store.import(binaryData,
1191 m_accessControl.isCCMode() ? "" : policy.password);
1193 token = store.importEncrypted(data,
1194 m_accessControl.isCCMode() ? "" : policy.password, enc);
1197 DB::Row row(std::move(token), name, OWNER_ID_SYSTEM,
1198 static_cast<int>(policy.extractable));
1199 handler.crypto.encryptRow(row);
1201 handler.database.saveRow(row);
1202 transaction.commit();
1203 } catch (const Exc::Exception &e) {
1205 } catch (const CKM::Exception &e) {
1206 LogError("CKM::Exception: " << e.GetMessage());
1207 return CKM_API_ERROR_SERVER_ERROR;
1208 } catch (const std::exception &e) {
1209 LogError("Std::exception: " << e.what());
1210 return CKM_API_ERROR_SERVER_ERROR;
1213 return CKM_API_SUCCESS;
1216 int CKMLogic::saveDataHelper(
1217 const Credentials &cred,
1220 const Crypto::Data &data,
1221 const PolicySerializable &policy)
1223 auto &handler = selectDatabase(cred, label);
1225 // use client label if not explicitly provided
1226 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1228 if (m_accessControl.isSystemService(cred) &&
1229 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1230 return CKM_API_ERROR_INPUT_PARAM;
1232 // check if save is possible
1233 DB::Crypto::Transaction transaction(&handler.database);
1234 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1236 if (retCode != CKM_API_SUCCESS)
1240 DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, ownerLabel,
1242 handler.database.saveRow(encryptedRow);
1244 transaction.commit();
1245 return CKM_API_SUCCESS;
1248 int CKMLogic::saveDataHelper(
1249 const Credentials &cred,
1252 const PKCS12Serializable &pkcs,
1253 const PolicySerializable &keyPolicy,
1254 const PolicySerializable &certPolicy)
1256 auto &handler = selectDatabase(cred, label);
1258 // use client label if not explicitly provided
1259 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1261 if (m_accessControl.isSystemService(cred) &&
1262 ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1263 return CKM_API_ERROR_INPUT_PARAM;
1265 // check if save is possible
1266 DB::Crypto::Transaction transaction(&handler.database);
1267 int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1269 if (retCode != CKM_API_SUCCESS)
1272 // extract and encrypt the data
1273 DB::RowVector encryptedRows;
1274 retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy,
1275 certPolicy, encryptedRows);
1277 if (retCode != CKM_API_SUCCESS)
1281 handler.database.saveRows(name, ownerLabel, encryptedRows);
1282 transaction.commit();
1284 return CKM_API_SUCCESS;
1288 int CKMLogic::createKeyAESHelper(
1289 const Credentials &cred,
1293 const PolicySerializable &policy)
1295 auto &handler = selectDatabase(cred, label);
1297 // use client label if not explicitly provided
1298 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1300 if (m_accessControl.isSystemService(cred) &&
1301 ownerLabel.compare(OWNER_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, ownerLabel);
1308 if (retCode != CKM_API_SUCCESS)
1311 // create key in store
1312 CryptoAlgorithm keyGenAlgorithm;
1313 keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::AES_GEN);
1314 keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, size);
1315 Token key = m_decider.getStore(DataType::KEY_AES,
1316 policy.extractable).generateSKey(keyGenAlgorithm, policy.password);
1319 DB::Row row(std::move(key), name, ownerLabel,
1320 static_cast<int>(policy.extractable));
1321 handler.crypto.encryptRow(row);
1323 handler.database.saveRow(row);
1325 transaction.commit();
1326 return CKM_API_SUCCESS;
1329 int CKMLogic::createKeyPairHelper(
1330 const Credentials &cred,
1331 const CryptoAlgorithmSerializable &keyGenParams,
1332 const Name &namePrivate,
1333 const Label &labelPrivate,
1334 const Name &namePublic,
1335 const Label &labelPublic,
1336 const PolicySerializable &policyPrivate,
1337 const PolicySerializable &policyPublic)
1339 auto &handlerPriv = selectDatabase(cred, labelPrivate);
1340 auto &handlerPub = selectDatabase(cred, labelPublic);
1342 AlgoType keyType = AlgoType::RSA_GEN;
1344 if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
1345 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
1347 DataType dt(keyType);
1350 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
1352 // use client label if not explicitly provided
1353 const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel :
1356 if (m_accessControl.isSystemService(cred) &&
1357 ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0)
1358 return CKM_API_ERROR_INPUT_PARAM;
1360 const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel :
1363 if (m_accessControl.isSystemService(cred) &&
1364 ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0)
1365 return CKM_API_ERROR_INPUT_PARAM;
1367 bool exportable = policyPrivate.extractable || policyPublic.extractable;
1368 TokenPair keys = m_decider.getStore(dt, exportable).generateAKey(keyGenParams,
1369 policyPrivate.password,
1370 policyPublic.password);
1372 DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
1373 // in case the same database is used for private and public - the second
1374 // transaction will not be executed
1375 DB::Crypto::Transaction transactionPub(&handlerPub.database);
1378 retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerLabelPrv);
1380 if (CKM_API_SUCCESS != retCode)
1383 retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerLabelPub);
1385 if (CKM_API_SUCCESS != retCode)
1389 DB::Row rowPrv(std::move(keys.first), namePrivate, ownerLabelPrv,
1390 static_cast<int>(policyPrivate.extractable));
1391 handlerPriv.crypto.encryptRow(rowPrv);
1392 handlerPriv.database.saveRow(rowPrv);
1394 DB::Row rowPub(std::move(keys.second), namePublic, ownerLabelPub,
1395 static_cast<int>(policyPublic.extractable));
1396 handlerPub.crypto.encryptRow(rowPub);
1397 handlerPub.database.saveRow(rowPub);
1399 transactionPub.commit();
1400 transactionPriv.commit();
1401 return CKM_API_SUCCESS;
1404 RawBuffer CKMLogic::createKeyPair(
1405 const Credentials &cred,
1407 const CryptoAlgorithmSerializable &keyGenParams,
1408 const Name &namePrivate,
1409 const Label &labelPrivate,
1410 const Name &namePublic,
1411 const Label &labelPublic,
1412 const PolicySerializable &policyPrivate,
1413 const PolicySerializable &policyPublic)
1415 int retCode = CKM_API_SUCCESS;
1418 retCode = createKeyPairHelper(
1427 } catch (const Exc::Exception &e) {
1428 retCode = e.error();
1429 } catch (const CKM::Exception &e) {
1430 LogError("CKM::Exception: " << e.GetMessage());
1431 retCode = CKM_API_ERROR_SERVER_ERROR;
1434 return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
1435 commandId, retCode).Pop();
1438 RawBuffer CKMLogic::createKeyAES(
1439 const Credentials &cred,
1444 const PolicySerializable &policy)
1446 int retCode = CKM_API_SUCCESS;
1449 retCode = createKeyAESHelper(cred, size, name, label, policy);
1450 } catch (const Exc::Exception &e) {
1451 retCode = e.error();
1452 } catch (std::invalid_argument &e) {
1453 LogDebug("invalid argument error: " << e.what());
1454 retCode = CKM_API_ERROR_INPUT_PARAM;
1455 } catch (const CKM::Exception &e) {
1456 LogError("CKM::Exception: " << e.GetMessage());
1457 retCode = CKM_API_ERROR_SERVER_ERROR;
1460 return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
1461 commandId, retCode).Pop();
1464 int CKMLogic::readCertificateHelper(
1465 const Credentials &cred,
1466 const LabelNameVector &labelNameVector,
1467 CertificateImplVector &certVector)
1469 for (auto &i : labelNameVector) {
1470 // certificates can't be protected with custom user password
1471 Crypto::GObjUPtr obj;
1473 ec = readDataHelper(true,
1475 DataType::CERTIFICATE,
1481 if (ec != CKM_API_SUCCESS)
1484 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1486 // try to read chain certificates (if present)
1487 Crypto::GObjUPtrVector caChainObjs;
1488 ec = readDataHelper(true,
1490 DataType::DB_CHAIN_FIRST,
1496 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1499 for (auto &caCertObj : caChainObjs)
1500 certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1503 return CKM_API_SUCCESS;
1506 int CKMLogic::getCertificateChainHelper(
1507 const CertificateImpl &cert,
1508 const RawBufferVector &untrustedCertificates,
1509 const RawBufferVector &trustedCertificates,
1510 bool useTrustedSystemCertificates,
1511 RawBufferVector &chainRawVector)
1513 CertificateImplVector untrustedCertVector;
1514 CertificateImplVector trustedCertVector;
1515 CertificateImplVector chainVector;
1518 return CKM_API_ERROR_INPUT_PARAM;
1520 for (auto &e : untrustedCertificates) {
1521 CertificateImpl c(e, DataFormat::FORM_DER);
1524 return CKM_API_ERROR_INPUT_PARAM;
1526 untrustedCertVector.push_back(std::move(c));
1529 for (auto &e : trustedCertificates) {
1530 CertificateImpl c(e, DataFormat::FORM_DER);
1533 return CKM_API_ERROR_INPUT_PARAM;
1535 trustedCertVector.push_back(std::move(c));
1538 CertificateStore store;
1539 int retCode = store.verifyCertificate(cert,
1540 untrustedCertVector,
1542 useTrustedSystemCertificates,
1543 m_accessControl.isCCMode(),
1546 if (retCode != CKM_API_SUCCESS)
1549 for (auto &e : chainVector)
1550 chainRawVector.push_back(e.getDER());
1552 return CKM_API_SUCCESS;
1555 int CKMLogic::getCertificateChainHelper(
1556 const Credentials &cred,
1557 const CertificateImpl &cert,
1558 const LabelNameVector &untrusted,
1559 const LabelNameVector &trusted,
1560 bool useTrustedSystemCertificates,
1561 RawBufferVector &chainRawVector)
1563 CertificateImplVector untrustedCertVector;
1564 CertificateImplVector trustedCertVector;
1565 CertificateImplVector chainVector;
1568 return CKM_API_ERROR_INPUT_PARAM;
1570 int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1572 if (retCode != CKM_API_SUCCESS)
1575 retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1577 if (retCode != CKM_API_SUCCESS)
1580 CertificateStore store;
1581 retCode = store.verifyCertificate(cert,
1582 untrustedCertVector,
1584 useTrustedSystemCertificates,
1585 m_accessControl.isCCMode(),
1588 if (retCode != CKM_API_SUCCESS)
1591 for (auto &i : chainVector)
1592 chainRawVector.push_back(i.getDER());
1594 return CKM_API_SUCCESS;
1597 RawBuffer CKMLogic::getCertificateChain(
1598 const Credentials & /*cred*/,
1600 const RawBuffer &certificate,
1601 const RawBufferVector &untrustedCertificates,
1602 const RawBufferVector &trustedCertificates,
1603 bool useTrustedSystemCertificates)
1605 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1606 RawBufferVector chainRawVector;
1607 int retCode = CKM_API_ERROR_UNKNOWN;
1610 retCode = getCertificateChainHelper(cert,
1611 untrustedCertificates,
1612 trustedCertificates,
1613 useTrustedSystemCertificates,
1615 } catch (const Exc::Exception &e) {
1616 retCode = e.error();
1617 } catch (const std::exception &e) {
1618 LogError("STD exception " << e.what());
1619 retCode = CKM_API_ERROR_SERVER_ERROR;
1621 LogError("Unknown error.");
1624 auto response = MessageBuffer::Serialize(static_cast<int>
1625 (LogicCommand::GET_CHAIN_CERT),
1629 return response.Pop();
1632 RawBuffer CKMLogic::getCertificateChain(
1633 const Credentials &cred,
1635 const RawBuffer &certificate,
1636 const LabelNameVector &untrustedCertificates,
1637 const LabelNameVector &trustedCertificates,
1638 bool useTrustedSystemCertificates)
1640 int retCode = CKM_API_ERROR_UNKNOWN;
1641 CertificateImpl cert(certificate, DataFormat::FORM_DER);
1642 RawBufferVector chainRawVector;
1645 retCode = getCertificateChainHelper(cred,
1647 untrustedCertificates,
1648 trustedCertificates,
1649 useTrustedSystemCertificates,
1651 } catch (const Exc::Exception &e) {
1652 retCode = e.error();
1653 } catch (const std::exception &e) {
1654 LogError("STD exception " << e.what());
1655 retCode = CKM_API_ERROR_SERVER_ERROR;
1657 LogError("Unknown error.");
1660 auto response = MessageBuffer::Serialize(static_cast<int>
1661 (LogicCommand::GET_CHAIN_ALIAS),
1665 return response.Pop();
1668 RawBuffer CKMLogic::createSignature(
1669 const Credentials &cred,
1671 const Name &privateKeyName,
1672 const Label &ownerLabel,
1673 const Password &password, // password for private_key
1674 const RawBuffer &message,
1675 const CryptoAlgorithm &cryptoAlg)
1677 RawBuffer signature;
1679 int retCode = CKM_API_SUCCESS;
1682 Crypto::GObjUPtr obj;
1683 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1684 ownerLabel, password, obj);
1686 if (retCode == CKM_API_SUCCESS)
1687 signature = obj->sign(cryptoAlg, message);
1688 } catch (const Exc::Exception &e) {
1689 retCode = e.error();
1690 } catch (const CKM::Exception &e) {
1691 LogError("Unknown CKM::Exception: " << e.GetMessage());
1692 retCode = CKM_API_ERROR_SERVER_ERROR;
1693 } catch (const std::exception &e) {
1694 LogError("STD exception " << e.what());
1695 retCode = CKM_API_ERROR_SERVER_ERROR;
1698 auto response = MessageBuffer::Serialize(static_cast<int>
1699 (LogicCommand::CREATE_SIGNATURE),
1703 return response.Pop();
1706 RawBuffer CKMLogic::verifySignature(
1707 const Credentials &cred,
1709 const Name &publicKeyOrCertName,
1710 const Label &ownerLabel,
1711 const Password &password, // password for public_key (optional)
1712 const RawBuffer &message,
1713 const RawBuffer &signature,
1714 const CryptoAlgorithm ¶ms)
1716 int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1719 // try certificate first - looking for a public key.
1720 // in case of PKCS, pub key from certificate will be found first
1721 // rather than private key from the same PKCS.
1722 Crypto::GObjUPtr obj;
1723 retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
1724 publicKeyOrCertName, ownerLabel, password, obj);
1726 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1727 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1728 publicKeyOrCertName, ownerLabel, password, obj);
1730 if (retCode == CKM_API_SUCCESS)
1731 retCode = obj->verify(params, message, signature);
1732 } catch (const Exc::Exception &e) {
1733 retCode = e.error();
1734 } catch (const CKM::Exception &e) {
1735 LogError("Unknown CKM::Exception: " << e.GetMessage());
1736 retCode = CKM_API_ERROR_SERVER_ERROR;
1739 auto response = MessageBuffer::Serialize(static_cast<int>
1740 (LogicCommand::VERIFY_SIGNATURE),
1743 return response.Pop();
1746 int CKMLogic::setPermissionHelper(
1747 const Credentials &cred, // who's the client
1749 const Label &label, // who's the owner
1750 const Label &accessorLabel, // who will get the access
1751 const PermissionMask permissionMask)
1753 auto &handler = selectDatabase(cred, label);
1755 // we don't know the client
1756 if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel))
1757 return CKM_API_ERROR_INPUT_PARAM;
1759 // use client label if not explicitly provided
1760 const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1762 // verify name and label are correct
1763 if (!isNameValid(name) || !isLabelValid(ownerLabel) ||
1764 !isLabelValid(accessorLabel))
1765 return CKM_API_ERROR_INPUT_PARAM;
1767 // currently we don't support modification of owner's permissions to his own rows
1768 if (ownerLabel == accessorLabel)
1769 return CKM_API_ERROR_INPUT_PARAM;
1771 // system database does not support write/remove permissions
1772 if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) &&
1773 (permissionMask & Permission::REMOVE))
1774 return CKM_API_ERROR_INPUT_PARAM;
1776 // can the client modify permissions to owner's row?
1777 int retCode = m_accessControl.canModify(cred, ownerLabel);
1779 if (retCode != CKM_API_SUCCESS)
1782 DB::Crypto::Transaction transaction(&handler.database);
1784 if (!handler.database.isNameLabelPresent(name, ownerLabel))
1785 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1787 // set permissions to the row owned by ownerLabel for accessorLabel
1788 handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask);
1789 transaction.commit();
1791 return CKM_API_SUCCESS;
1794 RawBuffer CKMLogic::setPermission(
1795 const Credentials &cred,
1800 const Label &accessorLabel,
1801 const PermissionMask permissionMask)
1806 retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
1807 } catch (const Exc::Exception &e) {
1808 retCode = e.error();
1809 } catch (const CKM::Exception &e) {
1810 LogError("Error: " << e.GetMessage());
1811 retCode = CKM_API_ERROR_DB_ERROR;
1814 return MessageBuffer::Serialize(command, msgID, retCode).Pop();
1817 int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel)
1819 if (!handle.crypto.haveKey(appLabel)) {
1821 auto key_optional = handle.database.getKey(appLabel);
1823 if (!key_optional) {
1824 LogError("No key for given label in database");
1825 return CKM_API_ERROR_DB_ERROR;
1828 key = *key_optional;
1829 key = handle.keyProvider.getPureDEK(key);
1830 handle.crypto.pushKey(appLabel, key);
1833 return CKM_API_SUCCESS;