Add backend field in policy
[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);
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 = m_decider.getStore(data.type, policy, !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).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         if (policyPrivate.backend != policyPublic.backend)
1352                 ThrowErr(Exc::InputParam, "Error, key pair must be supported with the same backend.");
1353
1354         // use client label if not explicitly provided
1355         const Label &ownerLabelPrv = labelPrivate.empty() ? cred.smackLabel :
1356                                                                  labelPrivate;
1357
1358         if (m_accessControl.isSystemService(cred) &&
1359                         ownerLabelPrv.compare(OWNER_ID_SYSTEM) != 0)
1360                 return CKM_API_ERROR_INPUT_PARAM;
1361
1362         const Label &ownerLabelPub = labelPublic.empty() ? cred.smackLabel :
1363                                                                  labelPublic;
1364
1365         if (m_accessControl.isSystemService(cred) &&
1366                         ownerLabelPub.compare(OWNER_ID_SYSTEM) != 0)
1367                 return CKM_API_ERROR_INPUT_PARAM;
1368
1369         bool exportable = policyPrivate.extractable || policyPublic.extractable;
1370         Policy lessRestricted(Password(), exportable, policyPrivate.backend);
1371
1372         TokenPair keys = m_decider.getStore(dt, lessRestricted).generateAKey(keyGenParams,
1373                                          policyPrivate.password,
1374                                          policyPublic.password);
1375
1376         DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
1377         // in case the same database is used for private and public - the second
1378         // transaction will not be executed
1379         DB::Crypto::Transaction transactionPub(&handlerPub.database);
1380
1381         int retCode;
1382         retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerLabelPrv);
1383
1384         if (CKM_API_SUCCESS != retCode)
1385                 return retCode;
1386
1387         retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerLabelPub);
1388
1389         if (CKM_API_SUCCESS != retCode)
1390                 return retCode;
1391
1392         // save the data
1393         DB::Row rowPrv(std::move(keys.first), namePrivate, ownerLabelPrv,
1394                                    static_cast<int>(policyPrivate.extractable));
1395         handlerPriv.crypto.encryptRow(rowPrv);
1396         handlerPriv.database.saveRow(rowPrv);
1397
1398         DB::Row rowPub(std::move(keys.second), namePublic, ownerLabelPub,
1399                                    static_cast<int>(policyPublic.extractable));
1400         handlerPub.crypto.encryptRow(rowPub);
1401         handlerPub.database.saveRow(rowPub);
1402
1403         transactionPub.commit();
1404         transactionPriv.commit();
1405         return CKM_API_SUCCESS;
1406 }
1407
1408 RawBuffer CKMLogic::createKeyPair(
1409         const Credentials &cred,
1410         int commandId,
1411         const CryptoAlgorithmSerializable &keyGenParams,
1412         const Name &namePrivate,
1413         const Label &labelPrivate,
1414         const Name &namePublic,
1415         const Label &labelPublic,
1416         const PolicySerializable &policyPrivate,
1417         const PolicySerializable &policyPublic)
1418 {
1419         int retCode = CKM_API_SUCCESS;
1420
1421         try {
1422                 retCode = createKeyPairHelper(
1423                                           cred,
1424                                           keyGenParams,
1425                                           namePrivate,
1426                                           labelPrivate,
1427                                           namePublic,
1428                                           labelPublic,
1429                                           policyPrivate,
1430                                           policyPublic);
1431         } catch (const Exc::Exception &e) {
1432                 retCode = e.error();
1433         } catch (const CKM::Exception &e) {
1434                 LogError("CKM::Exception: " << e.GetMessage());
1435                 retCode = CKM_API_ERROR_SERVER_ERROR;
1436         }
1437
1438         return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
1439                                                                         commandId, retCode).Pop();
1440 }
1441
1442 RawBuffer CKMLogic::createKeyAES(
1443         const Credentials &cred,
1444         int commandId,
1445         const int size,
1446         const Name &name,
1447         const Label &label,
1448         const PolicySerializable &policy)
1449 {
1450         int retCode = CKM_API_SUCCESS;
1451
1452         try {
1453                 retCode = createKeyAESHelper(cred, size, name, label, policy);
1454         } catch (const Exc::Exception &e) {
1455                 retCode = e.error();
1456         } catch (std::invalid_argument &e) {
1457                 LogDebug("invalid argument error: " << e.what());
1458                 retCode = CKM_API_ERROR_INPUT_PARAM;
1459         } catch (const CKM::Exception &e) {
1460                 LogError("CKM::Exception: " << e.GetMessage());
1461                 retCode = CKM_API_ERROR_SERVER_ERROR;
1462         }
1463
1464         return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
1465                                                                         commandId, retCode).Pop();
1466 }
1467
1468 int CKMLogic::readCertificateHelper(
1469         const Credentials &cred,
1470         const LabelNameVector &labelNameVector,
1471         CertificateImplVector &certVector)
1472 {
1473         for (auto &i : labelNameVector) {
1474                 // certificates can't be protected with custom user password
1475                 Crypto::GObjUPtr obj;
1476                 int ec;
1477                 ec = readDataHelper(true,
1478                                                         cred,
1479                                                         DataType::CERTIFICATE,
1480                                                         i.second,
1481                                                         i.first,
1482                                                         Password(),
1483                                                         obj);
1484
1485                 if (ec != CKM_API_SUCCESS)
1486                         return ec;
1487
1488                 certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);
1489
1490                 // try to read chain certificates (if present)
1491                 Crypto::GObjUPtrVector caChainObjs;
1492                 ec = readDataHelper(true,
1493                                                         cred,
1494                                                         DataType::DB_CHAIN_FIRST,
1495                                                         i.second,
1496                                                         i.first,
1497                                                         CKM::Password(),
1498                                                         caChainObjs);
1499
1500                 if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1501                         return ec;
1502
1503                 for (auto &caCertObj : caChainObjs)
1504                         certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
1505         }
1506
1507         return CKM_API_SUCCESS;
1508 }
1509
1510 int CKMLogic::getCertificateChainHelper(
1511         const CertificateImpl &cert,
1512         const RawBufferVector &untrustedCertificates,
1513         const RawBufferVector &trustedCertificates,
1514         bool useTrustedSystemCertificates,
1515         RawBufferVector &chainRawVector)
1516 {
1517         CertificateImplVector untrustedCertVector;
1518         CertificateImplVector trustedCertVector;
1519         CertificateImplVector chainVector;
1520
1521         if (cert.empty())
1522                 return CKM_API_ERROR_INPUT_PARAM;
1523
1524         for (auto &e : untrustedCertificates) {
1525                 CertificateImpl c(e, DataFormat::FORM_DER);
1526
1527                 if (c.empty())
1528                         return CKM_API_ERROR_INPUT_PARAM;
1529
1530                 untrustedCertVector.push_back(std::move(c));
1531         }
1532
1533         for (auto &e : trustedCertificates) {
1534                 CertificateImpl c(e, DataFormat::FORM_DER);
1535
1536                 if (c.empty())
1537                         return CKM_API_ERROR_INPUT_PARAM;
1538
1539                 trustedCertVector.push_back(std::move(c));
1540         }
1541
1542         CertificateStore store;
1543         int retCode = store.verifyCertificate(cert,
1544                                                                                   untrustedCertVector,
1545                                                                                   trustedCertVector,
1546                                                                                   useTrustedSystemCertificates,
1547                                                                                   m_accessControl.isCCMode(),
1548                                                                                   chainVector);
1549
1550         if (retCode != CKM_API_SUCCESS)
1551                 return retCode;
1552
1553         for (auto &e : chainVector)
1554                 chainRawVector.push_back(e.getDER());
1555
1556         return CKM_API_SUCCESS;
1557 }
1558
1559 int CKMLogic::getCertificateChainHelper(
1560         const Credentials &cred,
1561         const CertificateImpl &cert,
1562         const LabelNameVector &untrusted,
1563         const LabelNameVector &trusted,
1564         bool useTrustedSystemCertificates,
1565         RawBufferVector &chainRawVector)
1566 {
1567         CertificateImplVector untrustedCertVector;
1568         CertificateImplVector trustedCertVector;
1569         CertificateImplVector chainVector;
1570
1571         if (cert.empty())
1572                 return CKM_API_ERROR_INPUT_PARAM;
1573
1574         int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);
1575
1576         if (retCode != CKM_API_SUCCESS)
1577                 return retCode;
1578
1579         retCode = readCertificateHelper(cred, trusted, trustedCertVector);
1580
1581         if (retCode != CKM_API_SUCCESS)
1582                 return retCode;
1583
1584         CertificateStore store;
1585         retCode = store.verifyCertificate(cert,
1586                                                                           untrustedCertVector,
1587                                                                           trustedCertVector,
1588                                                                           useTrustedSystemCertificates,
1589                                                                           m_accessControl.isCCMode(),
1590                                                                           chainVector);
1591
1592         if (retCode != CKM_API_SUCCESS)
1593                 return retCode;
1594
1595         for (auto &i : chainVector)
1596                 chainRawVector.push_back(i.getDER());
1597
1598         return CKM_API_SUCCESS;
1599 }
1600
1601 RawBuffer CKMLogic::getCertificateChain(
1602         const Credentials & /*cred*/,
1603         int commandId,
1604         const RawBuffer &certificate,
1605         const RawBufferVector &untrustedCertificates,
1606         const RawBufferVector &trustedCertificates,
1607         bool useTrustedSystemCertificates)
1608 {
1609         CertificateImpl cert(certificate, DataFormat::FORM_DER);
1610         RawBufferVector chainRawVector;
1611         int retCode = CKM_API_ERROR_UNKNOWN;
1612
1613         try {
1614                 retCode = getCertificateChainHelper(cert,
1615                                                                                         untrustedCertificates,
1616                                                                                         trustedCertificates,
1617                                                                                         useTrustedSystemCertificates,
1618                                                                                         chainRawVector);
1619         } catch (const Exc::Exception &e) {
1620                 retCode = e.error();
1621         } catch (const std::exception &e) {
1622                 LogError("STD exception " << e.what());
1623                 retCode = CKM_API_ERROR_SERVER_ERROR;
1624         } catch (...) {
1625                 LogError("Unknown error.");
1626         }
1627
1628         auto response = MessageBuffer::Serialize(static_cast<int>
1629                                         (LogicCommand::GET_CHAIN_CERT),
1630                                         commandId,
1631                                         retCode,
1632                                         chainRawVector);
1633         return response.Pop();
1634 }
1635
1636 RawBuffer CKMLogic::getCertificateChain(
1637         const Credentials &cred,
1638         int commandId,
1639         const RawBuffer &certificate,
1640         const LabelNameVector &untrustedCertificates,
1641         const LabelNameVector &trustedCertificates,
1642         bool useTrustedSystemCertificates)
1643 {
1644         int retCode = CKM_API_ERROR_UNKNOWN;
1645         CertificateImpl cert(certificate, DataFormat::FORM_DER);
1646         RawBufferVector chainRawVector;
1647
1648         try {
1649                 retCode = getCertificateChainHelper(cred,
1650                                                                                         cert,
1651                                                                                         untrustedCertificates,
1652                                                                                         trustedCertificates,
1653                                                                                         useTrustedSystemCertificates,
1654                                                                                         chainRawVector);
1655         } catch (const Exc::Exception &e) {
1656                 retCode = e.error();
1657         } catch (const std::exception &e) {
1658                 LogError("STD exception " << e.what());
1659                 retCode = CKM_API_ERROR_SERVER_ERROR;
1660         } catch (...) {
1661                 LogError("Unknown error.");
1662         }
1663
1664         auto response = MessageBuffer::Serialize(static_cast<int>
1665                                         (LogicCommand::GET_CHAIN_ALIAS),
1666                                         commandId,
1667                                         retCode,
1668                                         chainRawVector);
1669         return response.Pop();
1670 }
1671
1672 RawBuffer CKMLogic::createSignature(
1673         const Credentials &cred,
1674         int commandId,
1675         const Name &privateKeyName,
1676         const Label &ownerLabel,
1677         const Password &password,           // password for private_key
1678         const RawBuffer &message,
1679         const CryptoAlgorithm &cryptoAlg)
1680 {
1681         RawBuffer signature;
1682
1683         int retCode = CKM_API_SUCCESS;
1684
1685         try {
1686                 Crypto::GObjUPtr obj;
1687                 retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
1688                                                                  ownerLabel, password, obj);
1689
1690                 if (retCode == CKM_API_SUCCESS)
1691                         signature = obj->sign(cryptoAlg, message);
1692         } catch (const Exc::Exception &e) {
1693                 retCode = e.error();
1694         } catch (const CKM::Exception &e) {
1695                 LogError("Unknown CKM::Exception: " << e.GetMessage());
1696                 retCode = CKM_API_ERROR_SERVER_ERROR;
1697         } catch (const std::exception &e) {
1698                 LogError("STD exception " << e.what());
1699                 retCode = CKM_API_ERROR_SERVER_ERROR;
1700         }
1701
1702         auto response = MessageBuffer::Serialize(static_cast<int>
1703                                         (LogicCommand::CREATE_SIGNATURE),
1704                                         commandId,
1705                                         retCode,
1706                                         signature);
1707         return response.Pop();
1708 }
1709
1710 RawBuffer CKMLogic::verifySignature(
1711         const Credentials &cred,
1712         int commandId,
1713         const Name &publicKeyOrCertName,
1714         const Label &ownerLabel,
1715         const Password &password,           // password for public_key (optional)
1716         const RawBuffer &message,
1717         const RawBuffer &signature,
1718         const CryptoAlgorithm &params)
1719 {
1720         int retCode = CKM_API_ERROR_VERIFICATION_FAILED;
1721
1722         try {
1723                 // try certificate first - looking for a public key.
1724                 // in case of PKCS, pub key from certificate will be found first
1725                 // rather than private key from the same PKCS.
1726                 Crypto::GObjUPtr obj;
1727                 retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
1728                                                                  publicKeyOrCertName, ownerLabel, password, obj);
1729
1730                 if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
1731                         retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
1732                                                                          publicKeyOrCertName, ownerLabel, password, obj);
1733
1734                 if (retCode == CKM_API_SUCCESS)
1735                         retCode = obj->verify(params, message, signature);
1736         } catch (const Exc::Exception &e) {
1737                 retCode = e.error();
1738         } catch (const CKM::Exception &e) {
1739                 LogError("Unknown CKM::Exception: " << e.GetMessage());
1740                 retCode = CKM_API_ERROR_SERVER_ERROR;
1741         }
1742
1743         auto response = MessageBuffer::Serialize(static_cast<int>
1744                                         (LogicCommand::VERIFY_SIGNATURE),
1745                                         commandId,
1746                                         retCode);
1747         return response.Pop();
1748 }
1749
1750 int CKMLogic::setPermissionHelper(
1751         const Credentials &cred,                // who's the client
1752         const Name &name,
1753         const Label &label,                     // who's the owner
1754         const Label &accessorLabel,             // who will get the access
1755         const PermissionMask permissionMask)
1756 {
1757         auto &handler = selectDatabase(cred, label);
1758
1759         // we don't know the client
1760         if (cred.smackLabel.empty() || !isLabelValid(cred.smackLabel))
1761                 return CKM_API_ERROR_INPUT_PARAM;
1762
1763         // use client label if not explicitly provided
1764         const Label &ownerLabel = label.empty() ? cred.smackLabel : label;
1765
1766         // verify name and label are correct
1767         if (!isNameValid(name) || !isLabelValid(ownerLabel) ||
1768                         !isLabelValid(accessorLabel))
1769                 return CKM_API_ERROR_INPUT_PARAM;
1770
1771         // currently we don't support modification of owner's permissions to his own rows
1772         if (ownerLabel == accessorLabel)
1773                 return CKM_API_ERROR_INPUT_PARAM;
1774
1775         // system database does not support write/remove permissions
1776         if ((0 == ownerLabel.compare(OWNER_ID_SYSTEM)) &&
1777                         (permissionMask & Permission::REMOVE))
1778                 return CKM_API_ERROR_INPUT_PARAM;
1779
1780         // can the client modify permissions to owner's row?
1781         int retCode = m_accessControl.canModify(cred, ownerLabel);
1782
1783         if (retCode != CKM_API_SUCCESS)
1784                 return retCode;
1785
1786         DB::Crypto::Transaction transaction(&handler.database);
1787
1788         if (!handler.database.isNameLabelPresent(name, ownerLabel))
1789                 return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
1790
1791         // set permissions to the row owned by ownerLabel for accessorLabel
1792         handler.database.setPermission(name, ownerLabel, accessorLabel, permissionMask);
1793         transaction.commit();
1794
1795         return CKM_API_SUCCESS;
1796 }
1797
1798 RawBuffer CKMLogic::setPermission(
1799         const Credentials &cred,
1800         const int command,
1801         const int msgID,
1802         const Name &name,
1803         const Label &label,
1804         const Label &accessorLabel,
1805         const PermissionMask permissionMask)
1806 {
1807         int retCode;
1808
1809         try {
1810                 retCode = setPermissionHelper(cred, name, label, accessorLabel, permissionMask);
1811         } catch (const Exc::Exception &e) {
1812                 retCode = e.error();
1813         } catch (const CKM::Exception &e) {
1814                 LogError("Error: " << e.GetMessage());
1815                 retCode = CKM_API_ERROR_DB_ERROR;
1816         }
1817
1818         return MessageBuffer::Serialize(command, msgID, retCode).Pop();
1819 }
1820
1821 int CKMLogic::loadAppKey(UserData &handle, const Label &appLabel)
1822 {
1823         if (!handle.crypto.haveKey(appLabel)) {
1824                 RawBuffer key;
1825                 auto key_optional = handle.database.getKey(appLabel);
1826
1827                 if (!key_optional) {
1828                         LogError("No key for given label in database");
1829                         return CKM_API_ERROR_DB_ERROR;
1830                 }
1831
1832                 key = *key_optional;
1833                 key = handle.keyProvider.getPureDEK(key);
1834                 handle.crypto.pushKey(appLabel, key);
1835         }
1836
1837         return CKM_API_SUCCESS;
1838 }
1839
1840 } // namespace CKM
1841