Merge branches 'tizen' and 'tizen_4.0'
[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         try {
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,
494                                                                          pass, obj);
495
496                 if (retCode == CKM_API_SUCCESS)
497                         key = std::move(obj);
498
499                 return retCode;
500         } catch (const Exc::Exception &e) {
501                 return e.error();
502         } catch (const CKM::Exception &e) {
503                 LogError("CKM::Exception: " << e.GetMessage());
504                 return CKM_API_ERROR_SERVER_ERROR;
505         }
506 }
507
508 RawBuffer CKMLogic::saveData(
509         const Credentials &cred,
510         int commandId,
511         const Name &name,
512         const Label &label,
513         const Crypto::Data &data,
514         const PolicySerializable &policy)
515 {
516         int retCode = verifyAndSaveDataHelper(cred, name, label, data, policy);
517         auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
518                                         commandId,
519                                         retCode,
520                                         static_cast<int>(data.type));
521         return response.Pop();
522 }
523
524 int CKMLogic::extractPKCS12Data(
525         CryptoLogic &crypto,
526         const Name &name,
527         const Label &ownerLabel,
528         const PKCS12Serializable &pkcs,
529         const PolicySerializable &keyPolicy,
530         const PolicySerializable &certPolicy,
531         DB::RowVector &output) const
532 {
533         // private key is mandatory
534         auto key = pkcs.getKey();
535
536         if (!key) {
537                 LogError("Failed to get private key from pkcs");
538                 return CKM_API_ERROR_INVALID_FORMAT;
539         }
540
541         Crypto::Data keyData(DataType(key->getType()), key->getDER());
542         int retCode = verifyBinaryData(keyData);
543
544         if (retCode != CKM_API_SUCCESS)
545                 return retCode;
546
547         output.push_back(createEncryptedRow(crypto, name, ownerLabel, keyData,
548                                                                                 keyPolicy));
549
550         // certificate is mandatory
551         auto cert = pkcs.getCertificate();
552
553         if (!cert) {
554                 LogError("Failed to get certificate from pkcs");
555                 return CKM_API_ERROR_INVALID_FORMAT;
556         }
557
558         Crypto::Data certData(DataType::CERTIFICATE, cert->getDER());
559         retCode = verifyBinaryData(certData);
560
561         if (retCode != CKM_API_SUCCESS)
562                 return retCode;
563
564         output.push_back(createEncryptedRow(crypto, name, ownerLabel, certData,
565                                                                                 certPolicy));
566
567         // CA cert chain
568         unsigned int cert_index = 0;
569
570         for (const auto &ca : pkcs.getCaCertificateShPtrVector()) {
571                 Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++),
572                                                                 ca->getDER());
573                 int retCode = verifyBinaryData(caCertData);
574
575                 if (retCode != CKM_API_SUCCESS)
576                         return retCode;
577
578                 output.push_back(createEncryptedRow(crypto, name, ownerLabel, caCertData,
579                                                                                         certPolicy));
580         }
581
582         return CKM_API_SUCCESS;
583 }
584
585 RawBuffer CKMLogic::savePKCS12(
586         const Credentials &cred,
587         int commandId,
588         const Name &name,
589         const Label &label,
590         const PKCS12Serializable &pkcs,
591         const PolicySerializable &keyPolicy,
592         const PolicySerializable &certPolicy)
593 {
594         int retCode = CKM_API_ERROR_UNKNOWN;
595
596         try {
597                 retCode = saveDataHelper(cred, name, label, pkcs, keyPolicy, certPolicy);
598         } catch (const Exc::Exception &e) {
599                 retCode = e.error();
600         } catch (const CKM::Exception &e) {
601                 LogError("CKM::Exception: " << e.GetMessage());
602                 retCode = CKM_API_ERROR_SERVER_ERROR;
603         }
604
605         auto response = MessageBuffer::Serialize(static_cast<int>
606                                         (LogicCommand::SAVE_PKCS12),
607                                         commandId,
608                                         retCode);
609         return response.Pop();
610 }
611
612
613 int CKMLogic::removeDataHelper(
614         const Credentials &cred,
615         const Name &name,
616         const Label &label)
617 {
618         auto &handler = selectDatabase(cred, label);
619
620         // use client label if not explicitly provided
621         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
622
623         if (!isNameValid(name) || !isLabelValid(ownerLabel)) {
624                 LogDebug("Invalid label or name format");
625                 return CKM_API_ERROR_INPUT_PARAM;
626         }
627
628         DB::Crypto::Transaction transaction(&handler.database);
629
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));
635
636         if (retCode != CKM_API_SUCCESS) {
637                 LogWarning("access control check result: " << retCode);
638                 return retCode;
639         }
640
641         // get all matching rows
642         DB::RowVector rows;
643         handler.database.getRows(name, ownerLabel, DataType::DB_FIRST,
644                                                          DataType::DB_LAST, rows);
645
646         if (rows.empty()) {
647                 LogDebug("No row for given name and label");
648                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
649         }
650
651         // load app key if needed
652         retCode = loadAppKey(handler, rows.front().ownerLabel);
653
654         if (CKM_API_SUCCESS != retCode)
655                 return retCode;
656
657         // destroy it in store
658         for (auto &r : rows) {
659                 try {
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.");
664                 }
665         }
666
667         // delete row in db
668         handler.database.deleteRow(name, ownerLabel);
669         transaction.commit();
670
671         return CKM_API_SUCCESS;
672 }
673
674 RawBuffer CKMLogic::removeData(
675         const Credentials &cred,
676         int commandId,
677         const Name &name,
678         const Label &label)
679 {
680         int retCode = CKM_API_ERROR_UNKNOWN;
681
682         try {
683                 retCode = removeDataHelper(cred, name, label);
684         } catch (const Exc::Exception &e) {
685                 retCode = e.error();
686         } catch (const CKM::Exception &e) {
687                 LogError("Error: " << e.GetMessage());
688                 retCode = CKM_API_ERROR_DB_ERROR;
689         }
690
691         auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::REMOVE),
692                                         commandId,
693                                         retCode);
694         return response.Pop();
695 }
696
697 int CKMLogic::readSingleRow(const Name &name,
698                                                         const Label &ownerLabel,
699                                                         DataType dataType,
700                                                         DB::Crypto &database,
701                                                         DB::Row &row)
702 {
703         DB::Crypto::RowOptional row_optional;
704
705         if (dataType.isKey()) {
706                 // read all key types
707                 row_optional = database.getRow(name,
708                                                                            ownerLabel,
709                                                                            DataType::DB_KEY_FIRST,
710                                                                            DataType::DB_KEY_LAST);
711         } else {
712                 // read anything else
713                 row_optional = database.getRow(name,
714                                                                            ownerLabel,
715                                                                            dataType);
716         }
717
718         if (!row_optional) {
719                 LogDebug("No row for given name, label and type");
720                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
721         } else {
722                 row = *row_optional;
723         }
724
725         return CKM_API_SUCCESS;
726 }
727
728
729 int CKMLogic::readMultiRow(const Name &name,
730                                                    const Label &ownerLabel,
731                                                    DataType dataType,
732                                                    DB::Crypto &database,
733                                                    DB::RowVector &output)
734 {
735         if (dataType.isKey())
736                 // read all key types
737                 database.getRows(name,
738                                                  ownerLabel,
739                                                  DataType::DB_KEY_FIRST,
740                                                  DataType::DB_KEY_LAST,
741                                                  output);
742         else if (dataType.isChainCert())
743                 // read all key types
744                 database.getRows(name,
745                                                  ownerLabel,
746                                                  DataType::DB_CHAIN_FIRST,
747                                                  DataType::DB_CHAIN_LAST,
748                                                  output);
749         else
750                 // read anything else
751                 database.getRows(name,
752                                                  ownerLabel,
753                                                  dataType,
754                                                  output);
755
756         if (!output.size()) {
757                 LogDebug("No row for given name, label and type");
758                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
759         }
760
761         return CKM_API_SUCCESS;
762 }
763
764 int CKMLogic::checkDataPermissionsHelper(const Credentials &cred,
765                 const Name &name,
766                 const Label &ownerLabel,
767                 const Label &accessorLabel,
768                 const DB::Row &row,
769                 bool exportFlag,
770                 DB::Crypto &database)
771 {
772         PermissionMaskOptional permissionRowOpt =
773                 database.getPermissionRow(name, ownerLabel, accessorLabel);
774
775         if (exportFlag)
776                 return m_accessControl.canExport(cred, row, PermissionForLabel(accessorLabel,
777                                                                                  permissionRowOpt));
778
779         return m_accessControl.canRead(cred, PermissionForLabel(accessorLabel,
780                                                                    permissionRowOpt));
781 }
782
783 Crypto::GObjUPtr CKMLogic::rowToObject(
784         UserData &handler,
785         DB::Row row,
786         const Password &password)
787 {
788         Crypto::GStore &store = m_decider.getStore(row);
789
790         Password pass = m_accessControl.isCCMode() ? "" : password;
791
792         // decrypt row
793         Crypto::GObjUPtr obj;
794
795         if (CryptoLogic::getSchemeVersion(row.encryptionScheme) ==
796                         CryptoLogic::ENCRYPTION_V2) {
797                 handler.crypto.decryptRow(Password(), row);
798
799                 obj = store.getObject(row, pass);
800         } else {
801                 // decrypt entirely with old scheme: b64(pass(appkey(data))) -> data
802                 handler.crypto.decryptRow(pass, row);
803                 // destroy it in store
804                 store.destroy(row);
805
806                 // import it to store with new scheme: data -> pass(data)
807                 Token token = store.import(Crypto::Data(row.dataType, row.data), pass);
808
809                 // get it from the store (it can be different than the data we imported into store)
810                 obj = store.getObject(token, pass);
811
812                 // update row with new token
813                 *static_cast<Token *>(&row) = std::move(token);
814
815                 // encrypt it with app key: pass(data) -> b64(appkey(pass(data))
816                 handler.crypto.encryptRow(row);
817
818                 // update it in db
819                 handler.database.updateRow(row);
820         }
821
822         return obj;
823 }
824
825 int CKMLogic::readDataHelper(
826         bool exportFlag,
827         const Credentials &cred,
828         DataType dataType,
829         const Name &name,
830         const Label &label,
831         const Password &password,
832         Crypto::GObjUPtrVector &objs)
833 {
834         auto &handler = selectDatabase(cred, label);
835
836         // use client label if not explicitly provided
837         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
838
839         if (!isNameValid(name) || !isLabelValid(ownerLabel))
840                 return CKM_API_ERROR_INPUT_PARAM;
841
842         // read rows
843         DB::Crypto::Transaction transaction(&handler.database);
844         DB::RowVector rows;
845         int retCode = readMultiRow(name, ownerLabel, dataType, handler.database, rows);
846
847         if (CKM_API_SUCCESS != retCode)
848                 return retCode;
849
850         // all read rows belong to the same owner
851         DB::Row &firstRow = rows.at(0);
852
853         // check access rights
854         retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
855                                                                                  firstRow, exportFlag, handler.database);
856
857         if (CKM_API_SUCCESS != retCode)
858                 return retCode;
859
860         // load app key if needed
861         retCode = loadAppKey(handler, firstRow.ownerLabel);
862
863         if (CKM_API_SUCCESS != retCode)
864                 return retCode;
865
866         // decrypt row
867         for (auto &row : rows)
868                 objs.push_back(rowToObject(handler, std::move(row), password));
869
870         // rowToObject may modify db
871         transaction.commit();
872
873         return CKM_API_SUCCESS;
874 }
875
876 int CKMLogic::readDataHelper(
877         bool exportFlag,
878         const Credentials &cred,
879         DataType dataType,
880         const Name &name,
881         const Label &label,
882         const Password &password,
883         Crypto::GObjUPtr &obj)
884 {
885         DataType objDataType;
886         return readDataHelper(exportFlag, cred, dataType, name, label, password, obj,
887                                                   objDataType);
888 }
889
890 int CKMLogic::readDataHelper(
891         bool exportFlag,
892         const Credentials &cred,
893         DataType dataType,
894         const Name &name,
895         const Label &label,
896         const Password &password,
897         Crypto::GObjUPtr &obj,
898         DataType &objDataType)
899 {
900         auto &handler = selectDatabase(cred, label);
901
902         // use client label if not explicitly provided
903         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
904
905         if (!isNameValid(name) || !isLabelValid(ownerLabel))
906                 return CKM_API_ERROR_INPUT_PARAM;
907
908         // read row
909         DB::Crypto::Transaction transaction(&handler.database);
910         DB::Row row;
911         int retCode = readSingleRow(name, ownerLabel, dataType, handler.database, row);
912
913         if (CKM_API_SUCCESS != retCode)
914                 return retCode;
915
916         objDataType = row.dataType;
917
918         // check access rights
919         retCode = checkDataPermissionsHelper(cred, name, ownerLabel, cred.smackLabel,
920                                                                                  row, exportFlag, handler.database);
921
922         if (CKM_API_SUCCESS != retCode)
923                 return retCode;
924
925         // load app key if needed
926         retCode = loadAppKey(handler, row.ownerLabel);
927
928         if (CKM_API_SUCCESS != retCode)
929                 return retCode;
930
931         obj = rowToObject(handler, std::move(row), password);
932         // rowToObject may modify db
933         transaction.commit();
934
935         return CKM_API_SUCCESS;
936 }
937
938 RawBuffer CKMLogic::getData(
939         const Credentials &cred,
940         int commandId,
941         DataType dataType,
942         const Name &name,
943         const Label &label,
944         const Password &password)
945 {
946         int retCode = CKM_API_SUCCESS;
947         RawBuffer rowData;
948         DataType objDataType;
949
950         try {
951                 Crypto::GObjUPtr obj;
952                 retCode = readDataHelper(true, cred, dataType, name, label, password, obj,
953                                                                  objDataType);
954
955                 if (retCode == CKM_API_SUCCESS)
956                         rowData = obj->getBinary();
957         } catch (const Exc::Exception &e) {
958                 retCode = e.error();
959         } catch (const CKM::Exception &e) {
960                 LogError("CKM::Exception: " << e.GetMessage());
961                 retCode = CKM_API_ERROR_SERVER_ERROR;
962         }
963
964         if (CKM_API_SUCCESS != retCode)
965                 rowData.clear();
966
967         auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET),
968                                         commandId,
969                                         retCode,
970                                         static_cast<int>(objDataType),
971                                         rowData);
972         return response.Pop();
973 }
974
975 int CKMLogic::getPKCS12Helper(
976         const Credentials &cred,
977         const Name &name,
978         const Label &label,
979         const Password &keyPassword,
980         const Password &certPassword,
981         KeyShPtr &privKey,
982         CertificateShPtr &cert,
983         CertificateShPtrVector &caChain)
984 {
985         int retCode;
986
987         // read private key (mandatory)
988         Crypto::GObjUPtr keyObj;
989         retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, label,
990                                                          keyPassword, keyObj);
991
992         if (retCode != CKM_API_SUCCESS) {
993                 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
994                         return retCode;
995         } else {
996                 privKey = CKM::Key::create(keyObj->getBinary());
997         }
998
999         // read certificate (mandatory)
1000         Crypto::GObjUPtr certObj;
1001         retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, label,
1002                                                          certPassword, certObj);
1003
1004         if (retCode != CKM_API_SUCCESS) {
1005                 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1006                         return retCode;
1007         } else {
1008                 cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER);
1009         }
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 && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
1017                 if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
1018                         return retCode;
1019         } else {
1020                 for (auto &caCertObj : caChainObjs)
1021                         caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(),
1022                                                                                                            DataFormat::FORM_DER));
1023         }
1024
1025         // if anything found, return it
1026         if (privKey || cert || caChain.size() > 0)
1027                 retCode = CKM_API_SUCCESS;
1028
1029         return retCode;
1030 }
1031
1032 RawBuffer CKMLogic::getPKCS12(
1033         const Credentials &cred,
1034         int commandId,
1035         const Name &name,
1036         const Label &label,
1037         const Password &keyPassword,
1038         const Password &certPassword)
1039 {
1040         int retCode = CKM_API_ERROR_UNKNOWN;
1041
1042         PKCS12Serializable output;
1043
1044         try {
1045                 KeyShPtr privKey;
1046                 CertificateShPtr cert;
1047                 CertificateShPtrVector caChain;
1048                 retCode = getPKCS12Helper(cred, name, label, keyPassword, certPassword, privKey,
1049                                                                   cert, caChain);
1050
1051                 // prepare response
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;
1060         }
1061
1062         auto response = MessageBuffer::Serialize(static_cast<int>
1063                                         (LogicCommand::GET_PKCS12),
1064                                         commandId,
1065                                         retCode,
1066                                         output);
1067         return response.Pop();
1068 }
1069
1070 int CKMLogic::getDataListHelper(const Credentials &cred,
1071                                                                 const DataType dataType,
1072                                                                 LabelNameVector &labelNameVector)
1073 {
1074         int retCode = CKM_API_ERROR_DB_LOCKED;
1075
1076         if (0 < m_userDataMap.count(cred.clientUid)) {
1077                 auto &database = m_userDataMap[cred.clientUid].database;
1078
1079                 try {
1080                         LabelNameVector tmpVector;
1081
1082                         if (dataType.isKey()) {
1083                                 // list all key types
1084                                 database.listNames(cred.smackLabel,
1085                                                                    tmpVector,
1086                                                                    DataType::DB_KEY_FIRST,
1087                                                                    DataType::DB_KEY_LAST);
1088                         } else {
1089                                 // list anything else
1090                                 database.listNames(cred.smackLabel,
1091                                                                    tmpVector,
1092                                                                    dataType);
1093                         }
1094
1095                         labelNameVector.insert(labelNameVector.end(), tmpVector.begin(),
1096                                                                    tmpVector.end());
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();
1103                 }
1104         }
1105
1106         return retCode;
1107 }
1108
1109 RawBuffer CKMLogic::getDataList(
1110         const Credentials &cred,
1111         int commandId,
1112         DataType dataType)
1113 {
1114         LabelNameVector systemVector;
1115         LabelNameVector userVector;
1116         LabelNameVector labelNameVector;
1117
1118         int retCode = unlockSystemDB();
1119
1120         if (CKM_API_SUCCESS == retCode) {
1121                 // system database
1122                 if (m_accessControl.isSystemService(cred)) {
1123                         // lookup system DB
1124                         retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1125                                                                                                         OWNER_ID_SYSTEM),
1126                                                                                 dataType,
1127                                                                                 systemVector);
1128                 } else {
1129                         // user - lookup system, then client DB
1130                         retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
1131                                                                                                         cred.smackLabel),
1132                                                                                 dataType,
1133                                                                                 systemVector);
1134
1135                         // private database
1136                         if (retCode == CKM_API_SUCCESS) {
1137                                 retCode = getDataListHelper(cred,
1138                                                                                         dataType,
1139                                                                                         userVector);
1140                         }
1141                 }
1142         }
1143
1144         if (retCode == CKM_API_SUCCESS) {
1145                 labelNameVector.insert(labelNameVector.end(), systemVector.begin(),
1146                                                            systemVector.end());
1147                 labelNameVector.insert(labelNameVector.end(), userVector.begin(),
1148                                                            userVector.end());
1149         }
1150
1151         auto response = MessageBuffer::Serialize(static_cast<int>
1152                                         (LogicCommand::GET_LIST),
1153                                         commandId,
1154                                         retCode,
1155                                         static_cast<int>(dataType),
1156                                         labelNameVector);
1157         return response.Pop();
1158 }
1159
1160 int CKMLogic::importInitialData(
1161         const Name &name,
1162         const Crypto::Data &data,
1163         const Crypto::DataEncryption &enc,
1164         const Policy &policy)
1165 {
1166         try {
1167                 // Inital values are always imported with root credentials. Label is not important.
1168                 Credentials rootCred(0, "");
1169
1170                 auto &handler = selectDatabase(rootCred, OWNER_ID_SYSTEM);
1171
1172                 // check if save is possible
1173                 DB::Crypto::Transaction transaction(&handler.database);
1174                 int retCode = checkSaveConditions(rootCred, handler, name, OWNER_ID_SYSTEM);
1175
1176                 if (retCode != CKM_API_SUCCESS)
1177                         return retCode;
1178
1179                 Crypto::GStore &store =
1180                         m_decider.getStore(data.type, policy.extractable, !enc.encryptedKey.empty());
1181
1182                 Token token;
1183
1184                 if (enc.encryptedKey.empty()) {
1185                         Crypto::Data binaryData;
1186
1187                         if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
1188                                 return retCode;
1189
1190                         token = store.import(binaryData,
1191                                                                  m_accessControl.isCCMode() ? "" : policy.password);
1192                 } else {
1193                         token = store.importEncrypted(data,
1194                                                                                   m_accessControl.isCCMode() ? "" : policy.password, enc);
1195                 }
1196
1197                 DB::Row row(std::move(token), name, OWNER_ID_SYSTEM,
1198                                         static_cast<int>(policy.extractable));
1199                 handler.crypto.encryptRow(row);
1200
1201                 handler.database.saveRow(row);
1202                 transaction.commit();
1203         } catch (const Exc::Exception &e) {
1204                 return e.error();
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;
1211         }
1212
1213         return CKM_API_SUCCESS;
1214 }
1215
1216 int CKMLogic::saveDataHelper(
1217         const Credentials &cred,
1218         const Name &name,
1219         const Label &label,
1220         const Crypto::Data &data,
1221         const PolicySerializable &policy)
1222 {
1223         auto &handler = selectDatabase(cred, label);
1224
1225         // use client label if not explicitly provided
1226         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1227
1228         if (m_accessControl.isSystemService(cred) &&
1229                         ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1230                 return CKM_API_ERROR_INPUT_PARAM;
1231
1232         // check if save is possible
1233         DB::Crypto::Transaction transaction(&handler.database);
1234         int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1235
1236         if (retCode != CKM_API_SUCCESS)
1237                 return retCode;
1238
1239         // save the data
1240         DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, ownerLabel,
1241                                                    data, policy);
1242         handler.database.saveRow(encryptedRow);
1243
1244         transaction.commit();
1245         return CKM_API_SUCCESS;
1246 }
1247
1248 int CKMLogic::saveDataHelper(
1249         const Credentials &cred,
1250         const Name &name,
1251         const Label &label,
1252         const PKCS12Serializable &pkcs,
1253         const PolicySerializable &keyPolicy,
1254         const PolicySerializable &certPolicy)
1255 {
1256         auto &handler = selectDatabase(cred, label);
1257
1258         // use client label if not explicitly provided
1259         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1260
1261         if (m_accessControl.isSystemService(cred) &&
1262                         ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1263                 return CKM_API_ERROR_INPUT_PARAM;
1264
1265         // check if save is possible
1266         DB::Crypto::Transaction transaction(&handler.database);
1267         int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1268
1269         if (retCode != CKM_API_SUCCESS)
1270                 return retCode;
1271
1272         // extract and encrypt the data
1273         DB::RowVector encryptedRows;
1274         retCode = extractPKCS12Data(handler.crypto, name, ownerLabel, pkcs, keyPolicy,
1275                                                                 certPolicy, encryptedRows);
1276
1277         if (retCode != CKM_API_SUCCESS)
1278                 return retCode;
1279
1280         // save the data
1281         handler.database.saveRows(name, ownerLabel, encryptedRows);
1282         transaction.commit();
1283
1284         return CKM_API_SUCCESS;
1285 }
1286
1287
1288 int CKMLogic::createKeyAESHelper(
1289         const Credentials &cred,
1290         const int size,
1291         const Name &name,
1292         const Label &label,
1293         const PolicySerializable &policy)
1294 {
1295         auto &handler = selectDatabase(cred, label);
1296
1297         // use client label if not explicitly provided
1298         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1299
1300         if (m_accessControl.isSystemService(cred) &&
1301                         ownerLabel.compare(OWNER_ID_SYSTEM) != 0)
1302                 return CKM_API_ERROR_INPUT_PARAM;
1303
1304         // check if save is possible
1305         DB::Crypto::Transaction transaction(&handler.database);
1306         int retCode = checkSaveConditions(cred, handler, name, ownerLabel);
1307
1308         if (retCode != CKM_API_SUCCESS)
1309                 return retCode;
1310
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);
1317
1318         // save the data
1319         DB::Row row(std::move(key), name, ownerLabel,
1320                                 static_cast<int>(policy.extractable));
1321         handler.crypto.encryptRow(row);
1322
1323         handler.database.saveRow(row);
1324
1325         transaction.commit();
1326         return CKM_API_SUCCESS;
1327 }
1328
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)
1338 {
1339         auto &handlerPriv = selectDatabase(cred, labelPrivate);
1340         auto &handlerPub = selectDatabase(cred, labelPublic);
1341
1342         AlgoType keyType = AlgoType::RSA_GEN;
1343
1344         if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
1345                 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");
1346
1347         DataType dt(keyType);
1348
1349         if (!dt.isKey())
1350                 ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");
1351
1352         // use client label if not explicitly provided
1353         const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel :
1354                                                                  labelPrivate;
1355
1356         if (m_accessControl.isSystemService(cred) &&
1357                         ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0)
1358                 return CKM_API_ERROR_INPUT_PARAM;
1359
1360         const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel :
1361                                                                  labelPublic;
1362
1363         if (m_accessControl.isSystemService(cred) &&
1364                         ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0)
1365                 return CKM_API_ERROR_INPUT_PARAM;
1366
1367         bool exportable = policyPrivate.extractable || policyPublic.extractable;
1368         TokenPair keys = m_decider.getStore(dt, exportable).generateAKey(keyGenParams,
1369                                          policyPrivate.password,
1370                                          policyPublic.password);
1371
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);
1376
1377         int retCode;
1378         retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerLabelPrv);
1379
1380         if (CKM_API_SUCCESS != retCode)
1381                 return retCode;
1382
1383         retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerLabelPub);
1384
1385         if (CKM_API_SUCCESS != retCode)
1386                 return retCode;
1387
1388         // save the data
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);
1393
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);
1398
1399         transactionPub.commit();
1400         transactionPriv.commit();
1401         return CKM_API_SUCCESS;
1402 }
1403
1404 RawBuffer CKMLogic::createKeyPair(
1405         const Credentials &cred,
1406         int commandId,
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)
1414 {
1415         int retCode = CKM_API_SUCCESS;
1416
1417         try {
1418                 retCode = createKeyPairHelper(
1419                                           cred,
1420                                           keyGenParams,
1421                                           namePrivate,
1422                                           labelPrivate,
1423                                           namePublic,
1424                                           labelPublic,
1425                                           policyPrivate,
1426                                           policyPublic);
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;
1432         }
1433
1434         return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
1435                                                                         commandId, retCode).Pop();
1436 }
1437
1438 RawBuffer CKMLogic::createKeyAES(
1439         const Credentials &cred,
1440         int commandId,
1441         const int size,
1442         const Name &name,
1443         const Label &label,
1444         const PolicySerializable &policy)
1445 {
1446         int retCode = CKM_API_SUCCESS;
1447
1448         try {
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;
1458         }
1459
1460         return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
1461                                                                         commandId, retCode).Pop();
1462 }
1463
1464 int CKMLogic::readCertificateHelper(
1465         const Credentials &cred,
1466         const LabelNameVector &labelNameVector,
1467         CertificateImplVector &certVector)
1468 {
1469         for (auto &i : labelNameVector) {
1470                 // certificates can't be protected with custom user password
1471                 Crypto::GObjUPtr obj;
1472                 int ec;
1473                 ec = readDataHelper(true,
1474                                                         cred,
1475                                                         DataType::CERTIFICATE,
1476                                                         i.second,
1477                                                         i.first,
1478                                                         Password(),
1479                                                         obj);
1480
1481                 if (ec != CKM_API_SUCCESS)
1482                         return ec;
1483
1484                 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1485
1486                 // try to read chain certificates (if present)
1487                 Crypto::GObjUPtrVector caChainObjs;
1488                 ec = readDataHelper(true,
1489                                                         cred,
1490                                                         DataType::DB_CHAIN_FIRST,
1491                                                         i.second,
1492                                                         i.first,
1493                                                         CKM::Password(),
1494                                                         caChainObjs);
1495
1496                 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1497                         return ec;
1498
1499                 for (auto &caCertObj : caChainObjs)
1500                         certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1501         }
1502
1503         return CKM_API_SUCCESS;
1504 }
1505
1506 int CKMLogic::getCertificateChainHelper(
1507         const CertificateImpl &cert,
1508         const RawBufferVector &untrustedCertificates,
1509         const RawBufferVector &trustedCertificates,
1510         bool useTrustedSystemCertificates,
1511         RawBufferVector &chainRawVector)
1512 {
1513         CertificateImplVector untrustedCertVector;
1514         CertificateImplVector trustedCertVector;
1515         CertificateImplVector chainVector;
1516
1517         if (cert.empty())
1518                 return CKM_API_ERROR_INPUT_PARAM;
1519
1520         for (auto &e : untrustedCertificates) {
1521                 CertificateImpl c(e, DataFormat::FORM_DER);
1522
1523                 if (c.empty())
1524                         return CKM_API_ERROR_INPUT_PARAM;
1525
1526                 untrustedCertVector.push_back(std::move(c));
1527         }
1528
1529         for (auto &e : trustedCertificates) {
1530                 CertificateImpl c(e, DataFormat::FORM_DER);
1531
1532                 if (c.empty())
1533                         return CKM_API_ERROR_INPUT_PARAM;
1534
1535                 trustedCertVector.push_back(std::move(c));
1536         }
1537
1538         CertificateStore store;
1539         int retCode = store.verifyCertificate(cert,
1540                                                                                   untrustedCertVector,
1541                                                                                   trustedCertVector,
1542                                                                                   useTrustedSystemCertificates,
1543                                                                                   m_accessControl.isCCMode(),
1544                                                                                   chainVector);
1545
1546         if (retCode != CKM_API_SUCCESS)
1547                 return retCode;
1548
1549         for (auto &e : chainVector)
1550                 chainRawVector.push_back(e.getDER());
1551
1552         return CKM_API_SUCCESS;
1553 }
1554
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)
1562 {
1563         CertificateImplVector untrustedCertVector;
1564         CertificateImplVector trustedCertVector;
1565         CertificateImplVector chainVector;
1566
1567         if (cert.empty())
1568                 return CKM_API_ERROR_INPUT_PARAM;
1569
1570         int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1571
1572         if (retCode != CKM_API_SUCCESS)
1573                 return retCode;
1574
1575         retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1576
1577         if (retCode != CKM_API_SUCCESS)
1578                 return retCode;
1579
1580         CertificateStore store;
1581         retCode = store.verifyCertificate(cert,
1582                                                                           untrustedCertVector,
1583                                                                           trustedCertVector,
1584                                                                           useTrustedSystemCertificates,
1585                                                                           m_accessControl.isCCMode(),
1586                                                                           chainVector);
1587
1588         if (retCode != CKM_API_SUCCESS)
1589                 return retCode;
1590
1591         for (auto &i : chainVector)
1592                 chainRawVector.push_back(i.getDER());
1593
1594         return CKM_API_SUCCESS;
1595 }
1596
1597 RawBuffer CKMLogic::getCertificateChain(
1598         const Credentials & /*cred*/,
1599         int commandId,
1600         const RawBuffer &certificate,
1601         const RawBufferVector &untrustedCertificates,
1602         const RawBufferVector &trustedCertificates,
1603         bool useTrustedSystemCertificates)
1604 {
1605         CertificateImpl cert(certificate, DataFormat::FORM_DER);
1606         RawBufferVector chainRawVector;
1607         int retCode = CKM_API_ERROR_UNKNOWN;
1608
1609         try {
1610                 retCode = getCertificateChainHelper(cert,
1611                                                                                         untrustedCertificates,
1612                                                                                         trustedCertificates,
1613                                                                                         useTrustedSystemCertificates,
1614                                                                                         chainRawVector);
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;
1620         } catch (...) {
1621                 LogError("Unknown error.");
1622         }
1623
1624         auto response = MessageBuffer::Serialize(static_cast<int>
1625                                         (LogicCommand::GET_CHAIN_CERT),
1626                                         commandId,
1627                                         retCode,
1628                                         chainRawVector);
1629         return response.Pop();
1630 }
1631
1632 RawBuffer CKMLogic::getCertificateChain(
1633         const Credentials &cred,
1634         int commandId,
1635         const RawBuffer &certificate,
1636         const LabelNameVector &untrustedCertificates,
1637         const LabelNameVector &trustedCertificates,
1638         bool useTrustedSystemCertificates)
1639 {
1640         int retCode = CKM_API_ERROR_UNKNOWN;
1641         CertificateImpl cert(certificate, DataFormat::FORM_DER);
1642         RawBufferVector chainRawVector;
1643
1644         try {
1645                 retCode = getCertificateChainHelper(cred,
1646                                                                                         cert,
1647                                                                                         untrustedCertificates,
1648                                                                                         trustedCertificates,
1649                                                                                         useTrustedSystemCertificates,
1650                                                                                         chainRawVector);
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;
1656         } catch (...) {
1657                 LogError("Unknown error.");
1658         }
1659
1660         auto response = MessageBuffer::Serialize(static_cast<int>
1661                                         (LogicCommand::GET_CHAIN_ALIAS),
1662                                         commandId,
1663                                         retCode,
1664                                         chainRawVector);
1665         return response.Pop();
1666 }
1667
1668 RawBuffer CKMLogic::createSignature(
1669         const Credentials &cred,
1670         int commandId,
1671         const Name &privateKeyName,
1672         const Label &ownerLabel,
1673         const Password &password,           // password for private_key
1674         const RawBuffer &message,
1675         const CryptoAlgorithm &cryptoAlg)
1676 {
1677         RawBuffer signature;
1678
1679         int retCode = CKM_API_SUCCESS;
1680
1681         try {
1682                 Crypto::GObjUPtr obj;
1683                 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1684                                                                  ownerLabel, password, obj);
1685
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;
1696         }
1697
1698         auto response = MessageBuffer::Serialize(static_cast<int>
1699                                         (LogicCommand::CREATE_SIGNATURE),
1700                                         commandId,
1701                                         retCode,
1702                                         signature);
1703         return response.Pop();
1704 }
1705
1706 RawBuffer CKMLogic::verifySignature(
1707         const Credentials &cred,
1708         int commandId,
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 &params)
1715 {
1716         int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1717
1718         try {
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);
1725
1726                 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1727                         retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1728                                                                          publicKeyOrCertName, ownerLabel, password, obj);
1729
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;
1737         }
1738
1739         auto response = MessageBuffer::Serialize(static_cast<int>
1740                                         (LogicCommand::VERIFY_SIGNATURE),
1741                                         commandId,
1742                                         retCode);
1743         return response.Pop();
1744 }
1745
1746 int CKMLogic::setPermissionHelper(
1747         const Credentials &cred,                // who's the client
1748         const Name &name,
1749         const Label &label,                     // who's the owner
1750         const Label &accessorLabel,             // who will get the access
1751         const PermissionMask permissionMask)
1752 {
1753         auto &handler = selectDatabase(cred, label);
1754
1755         // we don't know the client
1756         if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel))
1757                 return CKM_API_ERROR_INPUT_PARAM;
1758
1759         // use client label if not explicitly provided
1760         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1761
1762         // verify name and label are correct
1763         if (!isNameValid(name) || !isLabelValid(ownerLabel) ||
1764                         !isLabelValid(accessorLabel))
1765                 return CKM_API_ERROR_INPUT_PARAM;
1766
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;
1770
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;
1775
1776         // can the client modify permissions to owner's row?
1777         int retCode = m_accessControl.canModify(cred, ownerLabel);
1778
1779         if (retCode != CKM_API_SUCCESS)
1780                 return retCode;
1781
1782         DB::Crypto::Transaction transaction(&handler.database);
1783
1784         if (!handler.database.isNameLabelPresent(name, ownerLabel))
1785                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1786
1787         // set permissions to the row owned by ownerLabel for accessorLabel
1788         handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask);
1789         transaction.commit();
1790
1791         return CKM_API_SUCCESS;
1792 }
1793
1794 RawBuffer CKMLogic::setPermission(
1795         const Credentials &cred,
1796         const int command,
1797         const int msgID,
1798         const Name &name,
1799         const Label &label,
1800         const Label &accessorLabel,
1801         const PermissionMask permissionMask)
1802 {
1803         int retCode;
1804
1805         try {
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;
1812         }
1813
1814         return MessageBuffer::Serialize(command, msgID, retCode).Pop();
1815 }
1816
1817 int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel)
1818 {
1819         if (!handle.crypto.haveKey(appLabel)) {
1820                 RawBuffer key;
1821                 auto key_optional = handle.database.getKey(appLabel);
1822
1823                 if (!key_optional) {
1824                         LogError("No key for given label in database");
1825                         return CKM_API_ERROR_DB_ERROR;
1826                 }
1827
1828                 key = *key_optional;
1829                 key = handle.keyProvider.getPureDEK(key);
1830                 handle.crypto.pushKey(appLabel, key);
1831         }
1832
1833         return CKM_API_SUCCESS;
1834 }
1835
1836 } // namespace CKM
1837