Migrate ss data to both of system/admin user db
[platform/core/security/key-manager.git] / src / manager / service / ckm-logic.cpp
1 /*
2  *  Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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
15  *
16  *
17  * @file        ckm-logic.cpp
18  * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
19  * @version     1.0
20  * @brief       Sample service implementation.
21  */
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>
29 #include <key-impl.h>
30 #include <key-aes-impl.h>
31 #include <certificate-config.h>
32 #include <certificate-store.h>
33 #include <algorithm>
34 #include <sw-backend/store.h>
35 #include <generic-backend/exception.h>
36 #include <ss-migrate.h>
37
38 namespace {
39 const char *const CERT_SYSTEM_DIR          = CA_CERTS_DIR;
40 const char *const SYSTEM_DB_PASSWD         = "cAtRugU7";
41
42 bool isLabelValid(const CKM::Label &label)
43 {
44         // TODO: copy code from libprivilege control (for check smack label)
45         if (label.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Label::npos)
46                 return false;
47
48         return true;
49 }
50
51 bool isNameValid(const CKM::Name &name)
52 {
53         if (name.find(CKM::LABEL_NAME_SEPARATOR) != CKM::Name::npos)
54                 return false;
55
56         return true;
57 }
58
59 } // anonymous namespace
60
61 namespace CKM {
62
63 const uid_t CKMLogic::SYSTEM_DB_UID = 0;
64 const uid_t CKMLogic::ADMIN_USER_DB_UID = 5001;
65
66 CKMLogic::CKMLogic()
67 {
68         CertificateConfig::addSystemCertificateDir(CERT_SYSTEM_DIR);
69
70         m_accessControl.updateCCMode();
71 }
72
73 CKMLogic::~CKMLogic() {}
74
75 void CKMLogic::loadDKEKFile(uid_t user, const Password &password)
76 {
77         auto &handle = m_userDataMap[user];
78
79         FileSystem fs(user);
80
81         auto wrappedDKEK = fs.getDKEK();
82
83         if (wrappedDKEK.empty()) {
84                 wrappedDKEK = KeyProvider::generateDomainKEK(std::to_string(user), password);
85                 fs.saveDKEK(wrappedDKEK);
86         }
87
88         handle.keyProvider = KeyProvider(wrappedDKEK, password);
89 }
90
91 void CKMLogic::saveDKEKFile(uid_t user, const Password &password)
92 {
93         auto &handle = m_userDataMap[user];
94
95         FileSystem fs(user);
96         fs.saveDKEK(handle.keyProvider.getWrappedDomainKEK(password));
97 }
98
99 void CKMLogic::migrateSecureStorageData(bool isAdminUser)
100 {
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;
107
108                 int ret = verifyAndSaveDataHelper(Credentials(uid, ownerId), name, ownerId, data,
109                                                                                   PolicySerializable());
110
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 <<
115                                          " ret: " << ret);
116         });
117 }
118
119 int CKMLogic::unlockDatabase(uid_t user, const Password &password)
120 {
121         if (0 < m_userDataMap.count(user) &&
122                         m_userDataMap[user].keyProvider.isInitialized())
123                 return CKM_API_SUCCESS;
124
125         int retCode = CKM_API_SUCCESS;
126
127         try {
128                 auto &handle = m_userDataMap[user];
129
130                 FileSystem fs(user);
131                 loadDKEKFile(user, password);
132
133                 auto wrappedDatabaseDEK = fs.getDBDEK();
134
135                 if (wrappedDatabaseDEK.empty()) {
136                         wrappedDatabaseDEK = handle.keyProvider.generateDEK(std::to_string(user));
137                         fs.saveDBDEK(wrappedDatabaseDEK);
138                 }
139
140                 RawBuffer key = handle.keyProvider.getPureDEK(wrappedDatabaseDEK);
141
142                 handle.database = DB::Crypto(fs.getDBPath(), key);
143                 handle.crypto = CryptoLogic();
144
145                 if (!m_accessControl.isSystemService(user)) {
146                         // remove data of removed apps during locked state
147                         AppLabelVector removedApps = fs.clearRemovedsApps();
148
149                         for (auto &appSmackLabel : removedApps) {
150                                 handle.crypto.removeKey(appSmackLabel);
151                                 handle.database.deleteKey(appSmackLabel);
152                         }
153                 }
154
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) {
160                 retCode = e.error();
161         } catch (const CKM::Exception &e) {
162                 LogError("CKM::Exception: " << e.GetMessage());
163                 retCode = CKM_API_ERROR_SERVER_ERROR;
164         }
165
166         if (CKM_API_SUCCESS != retCode)
167                 m_userDataMap.erase(user);
168
169         return retCode;
170 }
171
172 int CKMLogic::unlockSystemDB()
173 {
174         return unlockDatabase(SYSTEM_DB_UID, SYSTEM_DB_PASSWD);
175 }
176
177 UserData &CKMLogic::selectDatabase(const Credentials &cred,
178                                                                    const Label &incoming_label)
179 {
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");
187
188                 if (0 != incoming_label.compare(OWNER_ID_SYSTEM))
189                         return m_userDataMap[cred.clientUid];
190         }
191
192         // system database selected, modify the label
193         if (CKM_API_SUCCESS != unlockSystemDB())
194                 ThrowErr(Exc::DatabaseLocked, "can not unlock system database");
195
196         return m_userDataMap[SYSTEM_DB_UID];
197 }
198
199 RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password)
200 {
201         int retCode = CKM_API_SUCCESS;
202
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;
207
208         return MessageBuffer::Serialize(retCode).Pop();
209 }
210
211 RawBuffer CKMLogic::updateCCMode()
212 {
213         m_accessControl.updateCCMode();
214         return MessageBuffer::Serialize(CKM_API_SUCCESS).Pop();
215 }
216
217 RawBuffer CKMLogic::lockUserKey(uid_t user)
218 {
219         int retCode = CKM_API_SUCCESS;
220
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;
225
226         return MessageBuffer::Serialize(retCode).Pop();
227 }
228
229 RawBuffer CKMLogic::removeUserData(uid_t user)
230 {
231         int retCode = CKM_API_SUCCESS;
232
233         if (m_accessControl.isSystemService(user))
234                 user = SYSTEM_DB_UID;
235
236         m_userDataMap.erase(user);
237
238         FileSystem fs(user);
239         fs.removeUserData();
240
241         return MessageBuffer::Serialize(retCode).Pop();
242 }
243
244 int CKMLogic::changeUserPasswordHelper(uid_t user,
245                                                                            const Password &oldPassword,
246                                                                            const Password &newPassword)
247 {
248         // do not allow to change system database password
249         if (m_accessControl.isSystemService(user))
250                 return CKM_API_ERROR_INPUT_PARAM;
251
252         loadDKEKFile(user, oldPassword);
253         saveDKEKFile(user, newPassword);
254
255         return CKM_API_SUCCESS;
256 }
257
258 RawBuffer CKMLogic::changeUserPassword(
259         uid_t user,
260         const Password &oldPassword,
261         const Password &newPassword)
262 {
263         int retCode = CKM_API_SUCCESS;
264
265         try {
266                 retCode = changeUserPasswordHelper(user, oldPassword, newPassword);
267         } catch (const Exc::Exception &e) {
268                 retCode = e.error();
269         } catch (const CKM::Exception &e) {
270                 LogError("CKM::Exception: " << e.GetMessage());
271                 retCode = CKM_API_ERROR_SERVER_ERROR;
272         }
273
274         return MessageBuffer::Serialize(retCode).Pop();
275 }
276
277 int CKMLogic::resetUserPasswordHelper(
278         uid_t user,
279         const Password &newPassword)
280 {
281         // do not allow to reset system database password
282         if (m_accessControl.isSystemService(user))
283                 return CKM_API_ERROR_INPUT_PARAM;
284
285         int retCode = CKM_API_SUCCESS;
286
287         if (0 == m_userDataMap.count(user)) {
288                 // Check if key exists. If exists we must return error
289                 FileSystem fs(user);
290                 auto wrappedDKEKMain = fs.getDKEK();
291
292                 if (!wrappedDKEKMain.empty())
293                         retCode = CKM_API_ERROR_BAD_REQUEST;
294         } else {
295                 saveDKEKFile(user, newPassword);
296         }
297
298         return retCode;
299 }
300
301 RawBuffer CKMLogic::resetUserPassword(
302         uid_t user,
303         const Password &newPassword)
304 {
305         int retCode = CKM_API_SUCCESS;
306
307         try {
308                 retCode = resetUserPasswordHelper(user, newPassword);
309         } catch (const Exc::Exception &e) {
310                 retCode = e.error();
311         } catch (const CKM::Exception &e) {
312                 LogError("CKM::Exception: " << e.GetMessage());
313                 retCode = CKM_API_ERROR_SERVER_ERROR;
314         }
315
316         return MessageBuffer::Serialize(retCode).Pop();
317 }
318
319 RawBuffer CKMLogic::removeApplicationData(const Label &smackLabel)
320 {
321         int retCode = CKM_API_SUCCESS;
322
323         try {
324                 if (smackLabel.empty()) {
325                         retCode = CKM_API_ERROR_INPUT_PARAM;
326                 } else {
327                         UidVector uids = FileSystem::getUIDsFromDBFile();
328
329                         for (auto userId : uids) {
330                                 if (0 == m_userDataMap.count(userId)) {
331                                         FileSystem fs(userId);
332                                         fs.addRemovedApp(smackLabel);
333                                 } else {
334                                         auto &handle = m_userDataMap[userId];
335                                         handle.crypto.removeKey(smackLabel);
336                                         handle.database.deleteKey(smackLabel);
337                                 }
338                         }
339                 }
340         } catch (const Exc::Exception &e) {
341                 retCode = e.error();
342         } catch (const CKM::Exception &e) {
343                 LogError("CKM::Exception: " << e.GetMessage());
344                 retCode = CKM_API_ERROR_SERVER_ERROR;
345         }
346
347         return MessageBuffer::Serialize(retCode).Pop();
348 }
349
350 int CKMLogic::checkSaveConditions(
351         const Credentials &cred,
352         UserData &handler,
353         const Name &name,
354         const Label &ownerLabel)
355 {
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;
360         }
361
362         // check if allowed to save using ownerLabel
363         int access_ec = m_accessControl.canSave(cred, ownerLabel);
364
365         if (access_ec != CKM_API_SUCCESS) {
366                 LogDebug("label " << cred.smackLabel << " can not save rows using label " <<
367                                  ownerLabel);
368                 return access_ec;
369         }
370
371         // check if not a duplicate
372         if (handler.database.isNameLabelPresent(name, ownerLabel))
373                 return CKM_API_ERROR_DB_ALIAS_EXISTS;
374
375         // encryption section
376         if (!handler.crypto.haveKey(ownerLabel)) {
377                 RawBuffer got_key;
378                 auto key_optional = handler.database.getKey(ownerLabel);
379
380                 if (!key_optional) {
381                         LogDebug("No Key in database found. Generating new one for label: " <<
382                                          ownerLabel);
383                         got_key = handler.keyProvider.generateDEK(ownerLabel);
384                         handler.database.saveKey(ownerLabel, got_key);
385                 } else {
386                         LogDebug("Key from DB");
387                         got_key = *key_optional;
388                 }
389
390                 got_key = handler.keyProvider.getPureDEK(got_key);
391                 handler.crypto.pushKey(ownerLabel, got_key);
392         }
393
394         return CKM_API_SUCCESS;
395 }
396
397 DB::Row CKMLogic::createEncryptedRow(
398         CryptoLogic &crypto,
399         const Name &name,
400         const Label &label,
401         const Crypto::Data &data,
402         const Policy &policy) const
403 {
404         Crypto::GStore &store = m_decider.getStore(data.type, policy.extractable);
405
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);
412         return row;
413 }
414
415 int CKMLogic::verifyBinaryData(Crypto::Data &input) const
416 {
417         Crypto::Data dummy;
418         return toBinaryData(input, dummy);
419 }
420
421 int CKMLogic::toBinaryData(const Crypto::Data &input,
422                                                    Crypto::Data &output) const
423 {
424         // verify the data integrity
425         if (input.type.isKey()) {
426                 KeyShPtr output_key;
427
428                 if (input.type.isSKey())
429                         output_key = CKM::Key::createAES(input.data);
430                 else
431                         output_key = CKM::Key::create(input.data);
432
433                 if (output_key.get() == NULL) {
434                         LogDebug("provided binary data is not valid key data");
435                         return CKM_API_ERROR_INPUT_PARAM;
436                 }
437
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);
442
443                 if (cert.get() == NULL) {
444                         LogDebug("provided binary data is not valid certificate data");
445                         return CKM_API_ERROR_INPUT_PARAM;
446                 }
447
448                 output = std::move(Crypto::Data(input.type, cert->getDER()));
449         } else {
450                 output = input;
451         }
452
453         // TODO: add here BINARY_DATA verification, i.e: max size etc.
454         return CKM_API_SUCCESS;
455 }
456
457 int CKMLogic::verifyAndSaveDataHelper(
458         const Credentials &cred,
459         const Name &name,
460         const Label &label,
461         const Crypto::Data &data,
462         const PolicySerializable &policy)
463 {
464         int retCode = CKM_API_ERROR_UNKNOWN;
465
466         try {
467                 // check if data is correct
468                 Crypto::Data binaryData;
469                 retCode = toBinaryData(data, binaryData);
470
471                 if (retCode != CKM_API_SUCCESS)
472                         return retCode;
473                 else
474                         return saveDataHelper(cred, name, label, binaryData, policy);
475         } catch (const Exc::Exception &e) {
476                 return e.error();
477         } catch (const CKM::Exception &e) {
478                 LogError("CKM::Exception: " << e.GetMessage());
479                 return CKM_API_ERROR_SERVER_ERROR;
480         }
481 }
482
483 int CKMLogic::getKeyForService(
484         const Credentials &cred,
485         const Name &name,
486         const Label &label,
487         const Password &pass,
488         Crypto::GObjShPtr &key)
489 {
490         DB::Row row;
491
492         try {
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,
496                                                                          pass, obj);
497
498                 if (retCode == CKM_API_SUCCESS)
499                         key = std::move(obj);
500
501                 return retCode;
502         } catch (const Exc::Exception &e) {
503                 return e.error();
504         } catch (const CKM::Exception &e) {
505                 LogError("CKM::Exception: " << e.GetMessage());
506                 return CKM_API_ERROR_SERVER_ERROR;
507         }
508 }
509
510 RawBuffer CKMLogic::saveData(
511         const Credentials &cred,
512         int commandId,
513         const Name &name,
514         const Label &label,
515         const Crypto::Data &data,
516         const PolicySerializable &policy)
517 {
518         int retCode = verifyAndSaveDataHelper(cred, name, label, data, policy);
519         auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
520                                         commandId,
521                                         retCode,
522                                         static_cast<int>(data.type));
523         return response.Pop();
524 }
525
526 int CKMLogic::extractPKCS12Data(
527         CryptoLogic &crypto,
528         const Name &name,
529         const Label &ownerLabel,
530         const PKCS12Serializable &pkcs,
531         const PolicySerializable &keyPolicy,
532         const PolicySerializable &certPolicy,
533         DB::RowVector &output) const
534 {
535         // private key is mandatory
536         auto key = pkcs.getKey();
537
538         if (!key) {
539                 LogError("Failed to get private key from pkcs");
540                 return CKM_API_ERROR_INVALID_FORMAT;
541         }
542
543         Crypto::Data keyData(DataType(key->getType()), key->getDER());
544         int retCode = verifyBinaryData(keyData);
545
546         if (retCode != CKM_API_SUCCESS)
547                 return retCode;
548
549         output.push_back(createEncryptedRow(crypto, name, ownerLabel, keyData,
550                                                                                 keyPolicy));
551
552         // certificate is mandatory
553         auto cert = pkcs.getCertificate();
554
555         if (!cert) {
556                 LogError("Failed to get certificate from pkcs");
557                 return CKM_API_ERROR_INVALID_FORMAT;
558         }
559
560         Crypto::Data certData(DataType::CERTIFICATE, cert->getDER());
561         retCode = verifyBinaryData(certData);
562
563         if (retCode != CKM_API_SUCCESS)
564                 return retCode;
565
566         output.push_back(createEncryptedRow(crypto, name, ownerLabel, certData,
567                                                                                 certPolicy));
568
569         // CA cert chain
570         unsigned int cert_index = 0;
571
572         for (const auto &ca : pkcs.getCaCertificateShPtrVector()) {
573                 Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++),
574                                                                 ca->getDER());
575                 int retCode = verifyBinaryData(caCertData);
576
577                 if (retCode != CKM_API_SUCCESS)
578                         return retCode;
579
580                 output.push_back(createEncryptedRow(crypto, name, ownerLabel, caCertData,
581                                                                                         certPolicy));
582         }
583
584         return CKM_API_SUCCESS;
585 }
586
587 RawBuffer CKMLogic::savePKCS12(
588         const Credentials &cred,
589         int commandId,
590         const Name &name,
591         const Label &label,
592         const PKCS12Serializable &pkcs,
593         const PolicySerializable &keyPolicy,
594         const PolicySerializable &certPolicy)
595 {
596         int retCode = CKM_API_ERROR_UNKNOWN;
597
598         try {
599                 retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy);
600         } catch (const Exc::Exception &e) {
601                 retCode = e.error();
602         } catch (const CKM::Exception &e) {
603                 LogError("CKM::Exception: " << e.GetMessage());
604                 retCode = CKM_API_ERROR_SERVER_ERROR;
605         }
606
607         auto response = MessageBuffer::Serialize(static_cast<int>
608                                         (LogicCommand::SAVE_PKCS12),
609                                         commandId,
610                                         retCode);
611         return response.Pop();
612 }
613
614
615 int CKMLogic::removeDataHelper(
616         const Credentials &cred,
617         const Name &name,
618         const Label &label)
619 {
620         auto &handler = selectDatabase(cred, label);
621
622         // use client label if not explicitly provided
623         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
624
625         if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
626                 LogDebug("Invalid label or name format");
627                 return CKM_API_ERROR_INPUT_PARAM;
628         }
629
630         DB::Crypto::Transaction transaction(&handler.database);
631
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));
637
638         if (retCode != CKM_API_SUCCESS) {
639                 LogWarning("access control check result: " << retCode);
640                 return retCode;
641         }
642
643         // get all matching rows
644         DB::RowVector rows;
645         handler.database.getRows(name, ownerLabel, DataType::DB_FIRST,
646                                                          DataType::DB_LAST, rows);
647
648         if (rows.empty()) {
649                 LogDebug("No row for given name and label");
650                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
651         }
652
653         // load app key if needed
654         retCode = loadAppKey(handler, rows.front().ownerLabel);
655
656         if (CKM_API_SUCCESS != retCode)
657                 return retCode;
658
659         // destroy it in store
660         for (auto &r : rows) {
661                 try {
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.");
666                 }
667         }
668
669         // delete row in db
670         handler.database.deleteRow(name, ownerLabel);
671         transaction.commit();
672
673         return CKM_API_SUCCESS;
674 }
675
676 RawBuffer CKMLogic::removeData(
677         const Credentials &cred,
678         int commandId,
679         const Name &name,
680         const Label &label)
681 {
682         int retCode = CKM_API_ERROR_UNKNOWN;
683
684         try {
685                 retCode = removeDataHelper(cred, name, label);
686         } catch (const Exc::Exception &e) {
687                 retCode = e.error();
688         } catch (const CKM::Exception &e) {
689                 LogError("Error: " << e.GetMessage());
690                 retCode = CKM_API_ERROR_DB_ERROR;
691         }
692
693         auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::REMOVE),
694                                         commandId,
695                                         retCode);
696         return response.Pop();
697 }
698
699 int CKMLogic::readSingleRow(const Name &name,
700                                                         const Label &ownerLabel,
701                                                         DataType dataType,
702                                                         DB::Crypto &database,
703                                                         DB::Row &row)
704 {
705         DB::Crypto::RowOptional row_optional;
706
707         if (dataType.isKey()) {
708                 // read all key types
709                 row_optional = database.getRow(name,
710                                                                            ownerLabel,
711                                                                            DataType::DB_KEY_FIRST,
712                                                                            DataType::DB_KEY_LAST);
713         } else {
714                 // read anything else
715                 row_optional = database.getRow(name,
716                                                                            ownerLabel,
717                                                                            dataType);
718         }
719
720         if (!row_optional) {
721                 LogDebug("No row for given name, label and type");
722                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
723         } else {
724                 row = *row_optional;
725         }
726
727         return CKM_API_SUCCESS;
728 }
729
730
731 int CKMLogic::readMultiRow(const Name &name,
732                                                    const Label &ownerLabel,
733                                                    DataType dataType,
734                                                    DB::Crypto &database,
735                                                    DB::RowVector &output)
736 {
737         if (dataType.isKey())
738                 // read all key types
739                 database.getRows(name,
740                                                  ownerLabel,
741                                                  DataType::DB_KEY_FIRST,
742                                                  DataType::DB_KEY_LAST,
743                                                  output);
744         else if (dataType.isChainCert())
745                 // read all key types
746                 database.getRows(name,
747                                                  ownerLabel,
748                                                  DataType::DB_CHAIN_FIRST,
749                                                  DataType::DB_CHAIN_LAST,
750                                                  output);
751         else
752                 // read anything else
753                 database.getRows(name,
754                                                  ownerLabel,
755                                                  dataType,
756                                                  output);
757
758         if (!output.size()) {
759                 LogDebug("No row for given name, label and type");
760                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
761         }
762
763         return CKM_API_SUCCESS;
764 }
765
766 int CKMLogic::checkDataPermissionsHelper(const Credentials &cred,
767                 const Name &name,
768                 const Label &ownerLabel,
769                 const Label &accessorLabel,
770                 const DB::Row &row,
771                 bool exportFlag,
772                 DB::Crypto &database)
773 {
774         PermissionMaskOptional permissionRowOpt =
775                 database.getPermissionRow(name, ownerLabel, accessorLabel);
776
777         if (exportFlag)
778                 return m_accessControl.canExport(cred, row, PermissionForLabel(accessorLabel,
779                                                                                  permissionRowOpt));
780
781         return m_accessControl.canRead(cred, PermissionForLabel(accessorLabel,
782                                                                    permissionRowOpt));
783 }
784
785 Crypto::GObjUPtr CKMLogic::rowToObject(
786         UserData &handler,
787         DB::Row row,
788         const Password &password)
789 {
790         Crypto::GStore &store = m_decider.getStore(row);
791
792         Password pass = m_accessControl.isCCMode() ? "" : password;
793
794         // decrypt row
795         Crypto::GObjUPtr obj;
796
797         if (CryptoLogic::getSchemeVersion(row.encryptionScheme) ==
798                         CryptoLogic::ENCRYPTION_V2) {
799                 handler.crypto.decryptRow(Password(), row);
800
801                 obj = store.getObject(row, pass);
802         } else {
803                 // decrypt entirely with old scheme: b64(pass(appkey(data))) -> data
804                 handler.crypto.decryptRow(pass, row);
805                 // destroy it in store
806                 store.destroy(row);
807
808                 // import it to store with new scheme: data -> pass(data)
809                 Token token = store.import(Crypto::Data(row.dataType, row.data), pass);
810
811                 // get it from the store (it can be different than the data we imported into store)
812                 obj = store.getObject(token, pass);
813
814                 // update row with new token
815                 *static_cast<Token *>(&row) = std::move(token);
816
817                 // encrypt it with app key: pass(data) -> b64(appkey(pass(data))
818                 handler.crypto.encryptRow(row);
819
820                 // update it in db
821                 handler.database.updateRow(row);
822         }
823
824         return obj;
825 }
826
827 int CKMLogic::readDataHelper(
828         bool exportFlag,
829         const Credentials &cred,
830         DataType dataType,
831         const Name &name,
832         const Label &label,
833         const Password &password,
834         Crypto::GObjUPtrVector &objs)
835 {
836         auto &handler = selectDatabase(cred, label);
837
838         // use client label if not explicitly provided
839         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
840
841         if (!isNameValid(name) || !isLabelValid(ownerLabel))
842                 return CKM_API_ERROR_INPUT_PARAM;
843
844         // read rows
845         DB::Crypto::Transaction transaction(&handler.database);
846         DB::RowVector rows;
847         int retCode = readMultiRow(name, ownerLabel, dataType, handler.database, rows);
848
849         if (CKM_API_SUCCESS != retCode)
850                 return retCode;
851
852         // all read rows belong to the same owner
853         DB::Row &firstRow = rows.at(0);
854
855         // check access rights
856         retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
857                                                                                  firstRow, exportFlag, handler.database);
858
859         if (CKM_API_SUCCESS != retCode)
860                 return retCode;
861
862         // load app key if needed
863         retCode = loadAppKey(handler, firstRow.ownerLabel);
864
865         if (CKM_API_SUCCESS != retCode)
866                 return retCode;
867
868         // decrypt row
869         for (auto &row : rows)
870                 objs.push_back(rowToObject(handler, std::move(row), password));
871
872         // rowToObject may modify db
873         transaction.commit();
874
875         return CKM_API_SUCCESS;
876 }
877
878 int CKMLogic::readDataHelper(
879         bool exportFlag,
880         const Credentials &cred,
881         DataType dataType,
882         const Name &name,
883         const Label &label,
884         const Password &password,
885         Crypto::GObjUPtr &obj)
886 {
887         DataType objDataType;
888         return readDataHelper(exportFlag, cred, dataType, name, label, password, obj,
889                                                   objDataType);
890 }
891
892 int CKMLogic::readDataHelper(
893         bool exportFlag,
894         const Credentials &cred,
895         DataType dataType,
896         const Name &name,
897         const Label &label,
898         const Password &password,
899         Crypto::GObjUPtr &obj,
900         DataType &objDataType)
901 {
902         auto &handler = selectDatabase(cred, label);
903
904         // use client label if not explicitly provided
905         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
906
907         if (!isNameValid(name) || !isLabelValid(ownerLabel))
908                 return CKM_API_ERROR_INPUT_PARAM;
909
910         // read row
911         DB::Crypto::Transaction transaction(&handler.database);
912         DB::Row row;
913         int retCode = readSingleRow(name, ownerLabel, dataType, handler.database, row);
914
915         if (CKM_API_SUCCESS != retCode)
916                 return retCode;
917
918         objDataType = row.dataType;
919
920         // check access rights
921         retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
922                                                                                  row, exportFlag, handler.database);
923
924         if (CKM_API_SUCCESS != retCode)
925                 return retCode;
926
927         // load app key if needed
928         retCode = loadAppKey(handler, row.ownerLabel);
929
930         if (CKM_API_SUCCESS != retCode)
931                 return retCode;
932
933         obj = rowToObject(handler, std::move(row), password);
934         // rowToObject may modify db
935         transaction.commit();
936
937         return CKM_API_SUCCESS;
938 }
939
940 RawBuffer CKMLogic::getData(
941         const Credentials &cred,
942         int commandId,
943         DataType dataType,
944         const Name &name,
945         const Label &label,
946         const Password &password)
947 {
948         int retCode = CKM_API_SUCCESS;
949         DB::Row row;
950         DataType objDataType;
951
952         try {
953                 Crypto::GObjUPtr obj;
954                 retCode = readDataHelper(true, cred, dataType, name, label, password, obj,
955                                                                  objDataType);
956
957                 if (retCode == CKM_API_SUCCESS)
958                         row.data = std::move(obj->getBinary());
959         } catch (const Exc::Exception &e) {
960                 retCode = e.error();
961         } catch (const CKM::Exception &e) {
962                 LogError("CKM::Exception: " << e.GetMessage());
963                 retCode = CKM_API_ERROR_SERVER_ERROR;
964         }
965
966         if (CKM_API_SUCCESS != retCode) {
967                 row.data.clear();
968                 row.dataType = dataType;
969         }
970
971         auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET),
972                                         commandId,
973                                         retCode,
974                                         static_cast<int>(objDataType),
975                                         row.data);
976         return response.Pop();
977 }
978
979 int CKMLogic::getPKCS12Helper(
980         const Credentials &cred,
981         const Name &name,
982         const Label &label,
983         const Password &keyPassword,
984         const Password &certPassword,
985         KeyShPtr &privKey,
986         CertificateShPtr &cert,
987         CertificateShPtrVector &caChain)
988 {
989         int retCode;
990
991         // read private key (mandatory)
992         Crypto::GObjUPtr keyObj;
993         retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, label,
994                                                          keyPassword, keyObj);
995
996         if (retCode != CKM_API_SUCCESS)
997                 return retCode;
998
999         privKey = CKM::Key::create(keyObj->getBinary());
1000
1001         // read certificate (mandatory)
1002         Crypto::GObjUPtr certObj;
1003         retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, label,
1004                                                          certPassword, certObj);
1005
1006         if (retCode != CKM_API_SUCCESS)
1007                 return retCode;
1008
1009         cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER);
1010
1011         // read CA cert chain (optional)
1012         Crypto::GObjUPtrVector caChainObjs;
1013         retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, label,
1014                                                          certPassword, caChainObjs);
1015
1016         if (retCode != CKM_API_SUCCESS &&
1017                         retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1018                 return retCode;
1019
1020         for (auto &caCertObj : caChainObjs)
1021                 caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(),
1022                                                   DataFormat::FORM_DER));
1023
1024         // if anything found, return it
1025         if (privKey || cert || caChain.size() > 0)
1026                 retCode = CKM_API_SUCCESS;
1027
1028         return retCode;
1029 }
1030
1031 RawBuffer CKMLogic::getPKCS12(
1032         const Credentials &cred,
1033         int commandId,
1034         const Name &name,
1035         const Label &label,
1036         const Password &keyPassword,
1037         const Password &certPassword)
1038 {
1039         int retCode = CKM_API_ERROR_UNKNOWN;
1040
1041         PKCS12Serializable output;
1042
1043         try {
1044                 KeyShPtr privKey;
1045                 CertificateShPtr cert;
1046                 CertificateShPtrVector caChain;
1047                 retCode = getPKCS12Helper(cred, name, label, keyPassword, certPassword, privKey,
1048                                                                   cert, caChain);
1049
1050                 // prepare response
1051                 if (retCode == CKM_API_SUCCESS)
1052                         output = PKCS12Serializable(std::move(privKey), std::move(cert),
1053                                                                                 std::move(caChain));
1054         } catch (const Exc::Exception &e) {
1055                 retCode = e.error();
1056         } catch (const CKM::Exception &e) {
1057                 LogError("CKM::Exception: " << e.GetMessage());
1058                 retCode = CKM_API_ERROR_SERVER_ERROR;
1059         }
1060
1061         auto response = MessageBuffer::Serialize(static_cast<int>
1062                                         (LogicCommand::GET_PKCS12),
1063                                         commandId,
1064                                         retCode,
1065                                         output);
1066         return response.Pop();
1067 }
1068
1069 int CKMLogic::getDataListHelper(const Credentials &cred,
1070                                                                 const DataType dataType,
1071                                                                 LabelNameVector &labelNameVector)
1072 {
1073         int retCode = CKM_API_ERROR_DB_LOCKED;
1074
1075         if (0 < m_userDataMap.count(cred.clientUid)) {
1076                 auto &database = m_userDataMap[cred.clientUid].database;
1077
1078                 try {
1079                         LabelNameVector tmpVector;
1080
1081                         if (dataType.isKey()) {
1082                                 // list all key types
1083                                 database.listNames(cred.smackLabel,
1084                                                                    tmpVector,
1085                                                                    DataType::DB_KEY_FIRST,
1086                                                                    DataType::DB_KEY_LAST);
1087                         } else {
1088                                 // list anything else
1089                                 database.listNames(cred.smackLabel,
1090                                                                    tmpVector,
1091                                                                    dataType);
1092                         }
1093
1094                         labelNameVector.insert(labelNameVector.end(), tmpVector.begin(),
1095                                                                    tmpVector.end());
1096                         retCode = CKM_API_SUCCESS;
1097                 } catch (const CKM::Exception &e) {
1098                         LogError("Error: " << e.GetMessage());
1099                         retCode = CKM_API_ERROR_DB_ERROR;
1100                 } catch (const Exc::Exception &e) {
1101                         retCode = e.error();
1102                 }
1103         }
1104
1105         return retCode;
1106 }
1107
1108 RawBuffer CKMLogic::getDataList(
1109         const Credentials &cred,
1110         int commandId,
1111         DataType dataType)
1112 {
1113         LabelNameVector systemVector;
1114         LabelNameVector userVector;
1115         LabelNameVector labelNameVector;
1116
1117         int retCode = unlockSystemDB();
1118
1119         if (CKM_API_SUCCESS == retCode) {
1120                 // system database
1121                 if (m_accessControl.isSystemService(cred)) {
1122                         // lookup system DB
1123                         retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1124                                                                                                         OWNER_ID_SYSTEM),
1125                                                                                 dataType,
1126                                                                                 systemVector);
1127                 } else {
1128                         // user - lookup system, then client DB
1129                         retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1130                                                                                                         cred.smackLabel),
1131                                                                                 dataType,
1132                                                                                 systemVector);
1133
1134                         // private database
1135                         if (retCode == CKM_API_SUCCESS) {
1136                                 retCode = getDataListHelper(cred,
1137                                                                                         dataType,
1138                                                                                         userVector);
1139                         }
1140                 }
1141         }
1142
1143         if (retCode == CKM_API_SUCCESS) {
1144                 labelNameVector.insert(labelNameVector.end(), systemVector.begin(),
1145                                                            systemVector.end());
1146                 labelNameVector.insert(labelNameVector.end(), userVector.begin(),
1147                                                            userVector.end());
1148         }
1149
1150         auto response = MessageBuffer::Serialize(static_cast<int>
1151                                         (LogicCommand::GET_LIST),
1152                                         commandId,
1153                                         retCode,
1154                                         static_cast<int>(dataType),
1155                                         labelNameVector);
1156         return response.Pop();
1157 }
1158
1159 int CKMLogic::importInitialData(
1160         const Name &name,
1161         const Crypto::Data &data,
1162         const Crypto::DataEncryption &enc,
1163         const Policy &policy)
1164 {
1165         try {
1166                 // Inital values are always imported with root credentials. Label is not important.
1167                 Credentials rootCred(0, "");
1168
1169                 auto &handler = selectDatabase(rootCred, OWNER_ID_SYSTEM);
1170
1171                 // check if save is possible
1172                 DB::Crypto::Transaction transaction(&handler.database);
1173                 int retCode = checkSaveConditions(rootCred, handler, name, OWNER_ID_SYSTEM);
1174
1175                 if (retCode != CKM_API_SUCCESS)
1176                         return retCode;
1177
1178                 Crypto::GStore &store =
1179                         m_decider.getStore(data.type, policy.extractable, !enc.encryptedKey.empty());
1180
1181                 Token token;
1182
1183                 if (enc.encryptedKey.empty()) {
1184                         Crypto::Data binaryData;
1185
1186                         if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
1187                                 return retCode;
1188
1189                         token = store.import(binaryData,
1190                                                                  m_accessControl.isCCMode() ? "" : policy.password);
1191                 } else {
1192                         token = store.importEncrypted(data,
1193                                                                                   m_accessControl.isCCMode() ? "" : policy.password, enc);
1194                 }
1195
1196                 DB::Row row(std::move(token), name, OWNER_ID_SYSTEM,
1197                                         static_cast<int>(policy.extractable));
1198                 handler.crypto.encryptRow(row);
1199
1200                 handler.database.saveRow(row);
1201                 transaction.commit();
1202         } catch (const Exc::Exception &e) {
1203                 return e.error();
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;
1210         }
1211
1212         return CKM_API_SUCCESS;
1213 }
1214
1215 int CKMLogic::saveDataHelper(
1216         const Credentials &cred,
1217         const Name &name,
1218         const Label &label,
1219         const Crypto::Data &data,
1220         const PolicySerializable &policy)
1221 {
1222         auto &handler = selectDatabase(cred, label);
1223
1224         // use client label if not explicitly provided
1225         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1226
1227         if (m_accessControl.isSystemService(cred) &&
1228                         ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1229                 return CKM_API_ERROR_INPUT_PARAM;
1230
1231         // check if save is possible
1232         DB::Crypto::Transaction transaction(&handler.database);
1233         int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1234
1235         if (retCode != CKM_API_SUCCESS)
1236                 return retCode;
1237
1238         // save the data
1239         DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, ownerLabel,
1240                                                    data, policy);
1241         handler.database.saveRow(encryptedRow);
1242
1243         transaction.commit();
1244         return CKM_API_SUCCESS;
1245 }
1246
1247 int CKMLogic::saveDataHelper(
1248         const Credentials &cred,
1249         const Name &name,
1250         const Label &label,
1251         const PKCS12Serializable &pkcs,
1252         const PolicySerializable &keyPolicy,
1253         const PolicySerializable &certPolicy)
1254 {
1255         auto &handler = selectDatabase(cred, label);
1256
1257         // use client label if not explicitly provided
1258         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1259
1260         if (m_accessControl.isSystemService(cred) &&
1261                         ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1262                 return CKM_API_ERROR_INPUT_PARAM;
1263
1264         // check if save is possible
1265         DB::Crypto::Transaction transaction(&handler.database);
1266         int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1267
1268         if (retCode != CKM_API_SUCCESS)
1269                 return retCode;
1270
1271         // extract and encrypt the data
1272         DB::RowVector encryptedRows;
1273         retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy,
1274                                                                 certPolicy, encryptedRows);
1275
1276         if (retCode != CKM_API_SUCCESS)
1277                 return retCode;
1278
1279         // save the data
1280         handler.database.saveRows(name, ownerLabel, encryptedRows);
1281         transaction.commit();
1282
1283         return CKM_API_SUCCESS;
1284 }
1285
1286
1287 int CKMLogic::createKeyAESHelper(
1288         const Credentials &cred,
1289         const int size,
1290         const Name &name,
1291         const Label &label,
1292         const PolicySerializable &policy)
1293 {
1294         auto &handler = selectDatabase(cred, label);
1295
1296         // use client label if not explicitly provided
1297         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1298
1299         if (m_accessControl.isSystemService(cred) &&
1300                         ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1301                 return CKM_API_ERROR_INPUT_PARAM;
1302
1303         // check if save is possible
1304         DB::Crypto::Transaction transaction(&handler.database);
1305         int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1306
1307         if (retCode != CKM_API_SUCCESS)
1308                 return retCode;
1309
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.extractable).generateSKey(keyGenAlgorithm, policy.password);
1316
1317         // save the data
1318         DB::Row row(std::move(key), name, ownerLabel,
1319                                 static_cast<int>(policy.extractable));
1320         handler.crypto.encryptRow(row);
1321
1322         handler.database.saveRow(row);
1323
1324         transaction.commit();
1325         return CKM_API_SUCCESS;
1326 }
1327
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)
1337 {
1338         auto &handlerPriv = selectDatabase(cred, labelPrivate);
1339         auto &handlerPub = selectDatabase(cred, labelPublic);
1340
1341         AlgoType keyType = AlgoType::RSA_GEN;
1342
1343         if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
1344                 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
1345
1346         DataType dt(keyType);
1347
1348         if (!dt.isKey())
1349                 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
1350
1351         // use client label if not explicitly provided
1352         const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel :
1353                                                                  labelPrivate;
1354
1355         if (m_accessControl.isSystemService(cred) &&
1356                         ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0)
1357                 return CKM_API_ERROR_INPUT_PARAM;
1358
1359         const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel :
1360                                                                  labelPublic;
1361
1362         if (m_accessControl.isSystemService(cred) &&
1363                         ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0)
1364                 return CKM_API_ERROR_INPUT_PARAM;
1365
1366         bool exportable = policyPrivate.extractable || policyPublic.extractable;
1367         TokenPair keys = m_decider.getStore(dt, exportable).generateAKey(keyGenParams,
1368                                          policyPrivate.password,
1369                                          policyPublic.password);
1370
1371         DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
1372         // in case the same database is used for private and public - the second
1373         // transaction will not be executed
1374         DB::Crypto::Transaction transactionPub(&handlerPub.database);
1375
1376         int retCode;
1377         retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerLabelPrv);
1378
1379         if (CKM_API_SUCCESS != retCode)
1380                 return retCode;
1381
1382         retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerLabelPub);
1383
1384         if (CKM_API_SUCCESS != retCode)
1385                 return retCode;
1386
1387         // save the data
1388         DB::Row rowPrv(std::move(keys.first), namePrivate, ownerLabelPrv,
1389                                    static_cast<int>(policyPrivate.extractable));
1390         handlerPriv.crypto.encryptRow(rowPrv);
1391         handlerPriv.database.saveRow(rowPrv);
1392
1393         DB::Row rowPub(std::move(keys.second), namePublic, ownerLabelPub,
1394                                    static_cast<int>(policyPublic.extractable));
1395         handlerPub.crypto.encryptRow(rowPub);
1396         handlerPub.database.saveRow(rowPub);
1397
1398         transactionPub.commit();
1399         transactionPriv.commit();
1400         return CKM_API_SUCCESS;
1401 }
1402
1403 RawBuffer CKMLogic::createKeyPair(
1404         const Credentials &cred,
1405         int commandId,
1406         const CryptoAlgorithmSerializable &keyGenParams,
1407         const Name &namePrivate,
1408         const Label &labelPrivate,
1409         const Name &namePublic,
1410         const Label &labelPublic,
1411         const PolicySerializable &policyPrivate,
1412         const PolicySerializable &policyPublic)
1413 {
1414         int retCode = CKM_API_SUCCESS;
1415
1416         try {
1417                 retCode = createKeyPairHelper(
1418                                           cred,
1419                                           keyGenParams,
1420                                           namePrivate,
1421                                           labelPrivate,
1422                                           namePublic,
1423                                           labelPublic,
1424                                           policyPrivate,
1425                                           policyPublic);
1426         } catch (const Exc::Exception &e) {
1427                 retCode = e.error();
1428         } catch (const CKM::Exception &e) {
1429                 LogError("CKM::Exception: " << e.GetMessage());
1430                 retCode = CKM_API_ERROR_SERVER_ERROR;
1431         }
1432
1433         return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
1434                                                                         commandId, retCode).Pop();
1435 }
1436
1437 RawBuffer CKMLogic::createKeyAES(
1438         const Credentials &cred,
1439         int commandId,
1440         const int size,
1441         const Name &name,
1442         const Label &label,
1443         const PolicySerializable &policy)
1444 {
1445         int retCode = CKM_API_SUCCESS;
1446
1447         try {
1448                 retCode = createKeyAESHelper(cred, size, name, label, policy);
1449         } catch (const Exc::Exception &e) {
1450                 retCode = e.error();
1451         } catch (std::invalid_argument &e) {
1452                 LogDebug("invalid argument error: " << e.what());
1453                 retCode = CKM_API_ERROR_INPUT_PARAM;
1454         } catch (const CKM::Exception &e) {
1455                 LogError("CKM::Exception: " << e.GetMessage());
1456                 retCode = CKM_API_ERROR_SERVER_ERROR;
1457         }
1458
1459         return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
1460                                                                         commandId, retCode).Pop();
1461 }
1462
1463 int CKMLogic::readCertificateHelper(
1464         const Credentials &cred,
1465         const LabelNameVector &labelNameVector,
1466         CertificateImplVector &certVector)
1467 {
1468         DB::Row row;
1469
1470         for (auto &i : labelNameVector) {
1471                 // certificates can't be protected with custom user password
1472                 Crypto::GObjUPtr obj;
1473                 int ec;
1474                 ec = readDataHelper(true,
1475                                                         cred,
1476                                                         DataType::CERTIFICATE,
1477                                                         i.second,
1478                                                         i.first,
1479                                                         Password(),
1480                                                         obj);
1481
1482                 if (ec != CKM_API_SUCCESS)
1483                         return ec;
1484
1485                 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1486
1487                 // try to read chain certificates (if present)
1488                 Crypto::GObjUPtrVector caChainObjs;
1489                 ec = readDataHelper(true,
1490                                                         cred,
1491                                                         DataType::DB_CHAIN_FIRST,
1492                                                         i.second,
1493                                                         i.first,
1494                                                         CKM::Password(),
1495                                                         caChainObjs);
1496
1497                 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1498                         return ec;
1499
1500                 for (auto &caCertObj : caChainObjs)
1501                         certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1502         }
1503
1504         return CKM_API_SUCCESS;
1505 }
1506
1507 int CKMLogic::getCertificateChainHelper(
1508         const CertificateImpl &cert,
1509         const RawBufferVector &untrustedCertificates,
1510         const RawBufferVector &trustedCertificates,
1511         bool useTrustedSystemCertificates,
1512         RawBufferVector &chainRawVector)
1513 {
1514         CertificateImplVector untrustedCertVector;
1515         CertificateImplVector trustedCertVector;
1516         CertificateImplVector chainVector;
1517
1518         if (cert.empty())
1519                 return CKM_API_ERROR_INPUT_PARAM;
1520
1521         for (auto &e : untrustedCertificates) {
1522                 CertificateImpl c(e, DataFormat::FORM_DER);
1523
1524                 if (c.empty())
1525                         return CKM_API_ERROR_INPUT_PARAM;
1526
1527                 untrustedCertVector.push_back(std::move(c));
1528         }
1529
1530         for (auto &e : trustedCertificates) {
1531                 CertificateImpl c(e, DataFormat::FORM_DER);
1532
1533                 if (c.empty())
1534                         return CKM_API_ERROR_INPUT_PARAM;
1535
1536                 trustedCertVector.push_back(std::move(c));
1537         }
1538
1539         CertificateStore store;
1540         int retCode = store.verifyCertificate(cert,
1541                                                                                   untrustedCertVector,
1542                                                                                   trustedCertVector,
1543                                                                                   useTrustedSystemCertificates,
1544                                                                                   m_accessControl.isCCMode(),
1545                                                                                   chainVector);
1546
1547         if (retCode != CKM_API_SUCCESS)
1548                 return retCode;
1549
1550         for (auto &e : chainVector)
1551                 chainRawVector.push_back(e.getDER());
1552
1553         return CKM_API_SUCCESS;
1554 }
1555
1556 int CKMLogic::getCertificateChainHelper(
1557         const Credentials &cred,
1558         const CertificateImpl &cert,
1559         const LabelNameVector &untrusted,
1560         const LabelNameVector &trusted,
1561         bool useTrustedSystemCertificates,
1562         RawBufferVector &chainRawVector)
1563 {
1564         CertificateImplVector untrustedCertVector;
1565         CertificateImplVector trustedCertVector;
1566         CertificateImplVector chainVector;
1567         DB::Row row;
1568
1569         if (cert.empty())
1570                 return CKM_API_ERROR_INPUT_PARAM;
1571
1572         int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1573
1574         if (retCode != CKM_API_SUCCESS)
1575                 return retCode;
1576
1577         retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1578
1579         if (retCode != CKM_API_SUCCESS)
1580                 return retCode;
1581
1582         CertificateStore store;
1583         retCode = store.verifyCertificate(cert,
1584                                                                           untrustedCertVector,
1585                                                                           trustedCertVector,
1586                                                                           useTrustedSystemCertificates,
1587                                                                           m_accessControl.isCCMode(),
1588                                                                           chainVector);
1589
1590         if (retCode != CKM_API_SUCCESS)
1591                 return retCode;
1592
1593         for (auto &i : chainVector)
1594                 chainRawVector.push_back(i.getDER());
1595
1596         return CKM_API_SUCCESS;
1597 }
1598
1599 RawBuffer CKMLogic::getCertificateChain(
1600         const Credentials & /*cred*/,
1601         int commandId,
1602         const RawBuffer &certificate,
1603         const RawBufferVector &untrustedCertificates,
1604         const RawBufferVector &trustedCertificates,
1605         bool useTrustedSystemCertificates)
1606 {
1607         CertificateImpl cert(certificate, DataFormat::FORM_DER);
1608         RawBufferVector chainRawVector;
1609         int retCode = CKM_API_ERROR_UNKNOWN;
1610
1611         try {
1612                 retCode = getCertificateChainHelper(cert,
1613                                                                                         untrustedCertificates,
1614                                                                                         trustedCertificates,
1615                                                                                         useTrustedSystemCertificates,
1616                                                                                         chainRawVector);
1617         } catch (const Exc::Exception &e) {
1618                 retCode = e.error();
1619         } catch (const std::exception &e) {
1620                 LogError("STD exception " << e.what());
1621                 retCode = CKM_API_ERROR_SERVER_ERROR;
1622         } catch (...) {
1623                 LogError("Unknown error.");
1624         }
1625
1626         auto response = MessageBuffer::Serialize(static_cast<int>
1627                                         (LogicCommand::GET_CHAIN_CERT),
1628                                         commandId,
1629                                         retCode,
1630                                         chainRawVector);
1631         return response.Pop();
1632 }
1633
1634 RawBuffer CKMLogic::getCertificateChain(
1635         const Credentials &cred,
1636         int commandId,
1637         const RawBuffer &certificate,
1638         const LabelNameVector &untrustedCertificates,
1639         const LabelNameVector &trustedCertificates,
1640         bool useTrustedSystemCertificates)
1641 {
1642         int retCode = CKM_API_ERROR_UNKNOWN;
1643         CertificateImpl cert(certificate, DataFormat::FORM_DER);
1644         RawBufferVector chainRawVector;
1645
1646         try {
1647                 retCode = getCertificateChainHelper(cred,
1648                                                                                         cert,
1649                                                                                         untrustedCertificates,
1650                                                                                         trustedCertificates,
1651                                                                                         useTrustedSystemCertificates,
1652                                                                                         chainRawVector);
1653         } catch (const Exc::Exception &e) {
1654                 retCode = e.error();
1655         } catch (const std::exception &e) {
1656                 LogError("STD exception " << e.what());
1657                 retCode = CKM_API_ERROR_SERVER_ERROR;
1658         } catch (...) {
1659                 LogError("Unknown error.");
1660         }
1661
1662         auto response = MessageBuffer::Serialize(static_cast<int>
1663                                         (LogicCommand::GET_CHAIN_ALIAS),
1664                                         commandId,
1665                                         retCode,
1666                                         chainRawVector);
1667         return response.Pop();
1668 }
1669
1670 RawBuffer CKMLogic::createSignature(
1671         const Credentials &cred,
1672         int commandId,
1673         const Name &privateKeyName,
1674         const Label &ownerLabel,
1675         const Password &password,           // password for private_key
1676         const RawBuffer &message,
1677         const CryptoAlgorithm &cryptoAlg)
1678 {
1679         DB::Row row;
1680         RawBuffer signature;
1681
1682         int retCode = CKM_API_SUCCESS;
1683
1684         try {
1685                 Crypto::GObjUPtr obj;
1686                 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1687                                                                  ownerLabel, password, obj);
1688
1689                 if (retCode == CKM_API_SUCCESS)
1690                         signature = obj->sign(cryptoAlg, message);
1691         } catch (const Exc::Exception &e) {
1692                 retCode = e.error();
1693         } catch (const CKM::Exception &e) {
1694                 LogError("Unknown CKM::Exception: " << e.GetMessage());
1695                 retCode = CKM_API_ERROR_SERVER_ERROR;
1696         } catch (const std::exception &e) {
1697                 LogError("STD exception " << e.what());
1698                 retCode = CKM_API_ERROR_SERVER_ERROR;
1699         }
1700
1701         auto response = MessageBuffer::Serialize(static_cast<int>
1702                                         (LogicCommand::CREATE_SIGNATURE),
1703                                         commandId,
1704                                         retCode,
1705                                         signature);
1706         return response.Pop();
1707 }
1708
1709 RawBuffer CKMLogic::verifySignature(
1710         const Credentials &cred,
1711         int commandId,
1712         const Name &publicKeyOrCertName,
1713         const Label &ownerLabel,
1714         const Password &password,           // password for public_key (optional)
1715         const RawBuffer &message,
1716         const RawBuffer &signature,
1717         const CryptoAlgorithm &params)
1718 {
1719         int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1720
1721         try {
1722                 DB::Row row;
1723
1724                 // try certificate first - looking for a public key.
1725                 // in case of PKCS, pub key from certificate will be found first
1726                 // rather than private key from the same PKCS.
1727                 Crypto::GObjUPtr obj;
1728                 retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
1729                                                                  publicKeyOrCertName, ownerLabel, password, obj);
1730
1731                 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1732                         retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1733                                                                          publicKeyOrCertName, ownerLabel, password, obj);
1734
1735                 if (retCode == CKM_API_SUCCESS)
1736                         retCode = obj->verify(params, message, signature);
1737         } catch (const Exc::Exception &e) {
1738                 retCode = e.error();
1739         } catch (const CKM::Exception &e) {
1740                 LogError("Unknown CKM::Exception: " << e.GetMessage());
1741                 retCode = CKM_API_ERROR_SERVER_ERROR;
1742         }
1743
1744         auto response = MessageBuffer::Serialize(static_cast<int>
1745                                         (LogicCommand::VERIFY_SIGNATURE),
1746                                         commandId,
1747                                         retCode);
1748         return response.Pop();
1749 }
1750
1751 int CKMLogic::setPermissionHelper(
1752         const Credentials &cred,                // who's the client
1753         const Name &name,
1754         const Label &label,                     // who's the owner
1755         const Label &accessorLabel,             // who will get the access
1756         const PermissionMask permissionMask)
1757 {
1758         auto &handler = selectDatabase(cred, label);
1759
1760         // we don't know the client
1761         if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel))
1762                 return CKM_API_ERROR_INPUT_PARAM;
1763
1764         // use client label if not explicitly provided
1765         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1766
1767         // verify name and label are correct
1768         if (!isNameValid(name) || !isLabelValid(ownerLabel) ||
1769                         !isLabelValid(accessorLabel))
1770                 return CKM_API_ERROR_INPUT_PARAM;
1771
1772         // currently we don't support modification of owner's permissions to his own rows
1773         if (ownerLabel == accessorLabel)
1774                 return CKM_API_ERROR_INPUT_PARAM;
1775
1776         // system database does not support write/remove permissions
1777         if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) &&
1778                         (permissionMask & Permission::REMOVE))
1779                 return CKM_API_ERROR_INPUT_PARAM;
1780
1781         // can the client modify permissions to owner's row?
1782         int retCode = m_accessControl.canModify(cred, ownerLabel);
1783
1784         if (retCode != CKM_API_SUCCESS)
1785                 return retCode;
1786
1787         DB::Crypto::Transaction transaction(&handler.database);
1788
1789         if (!handler.database.isNameLabelPresent(name, ownerLabel))
1790                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1791
1792         // removing non-existing permissions: fail
1793         if (permissionMask == Permission::NONE) {
1794                 if (!handler.database.getPermissionRow(name, ownerLabel, accessorLabel))
1795                         return CKM_API_ERROR_INPUT_PARAM;
1796         }
1797
1798         // set permissions to the row owned by ownerLabel for accessorLabel
1799         handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask);
1800         transaction.commit();
1801
1802         return CKM_API_SUCCESS;
1803 }
1804
1805 RawBuffer CKMLogic::setPermission(
1806         const Credentials &cred,
1807         const int command,
1808         const int msgID,
1809         const Name &name,
1810         const Label &label,
1811         const Label &accessorLabel,
1812         const PermissionMask permissionMask)
1813 {
1814         int retCode;
1815
1816         try {
1817                 retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
1818         } catch (const Exc::Exception &e) {
1819                 retCode = e.error();
1820         } catch (const CKM::Exception &e) {
1821                 LogError("Error: " << e.GetMessage());
1822                 retCode = CKM_API_ERROR_DB_ERROR;
1823         }
1824
1825         return MessageBuffer::Serialize(command, msgID, retCode).Pop();
1826 }
1827
1828 int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel)
1829 {
1830         if (!handle.crypto.haveKey(appLabel)) {
1831                 RawBuffer key;
1832                 auto key_optional = handle.database.getKey(appLabel);
1833
1834                 if (!key_optional) {
1835                         LogError("No key for given label in database");
1836                         return CKM_API_ERROR_DB_ERROR;
1837                 }
1838
1839                 key = *key_optional;
1840                 key = handle.keyProvider.getPureDEK(key);
1841                 handle.crypto.pushKey(appLabel, key);
1842         }
1843
1844         return CKM_API_SUCCESS;
1845 }
1846
1847 } // namespace CKM
1848