summaryrefslogtreecommitdiff
path: root/src/manager/service/ckm-logic.cpp
blob: c54b9a4f3c76e16e346f8508a8995bbacc61dd20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
/*
 *  Copyright (c) 2014 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 *
 * @file        ckm-logic.cpp
 * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
 * @version     1.0
 * @brief       Sample service implementation.
 */
#include <dpl/serialization.h>
#include <dpl/log/log.h>
#include <ckm/ckm-error.h>
#include <ckm/ckm-type.h>
#include <key-provider.h>
#include <file-system.h>
#include <ckm-logic.h>
#include <key-impl.h>
#include <key-aes-impl.h>
#include <certificate-config.h>
#include <certificate-store.h>
#include <algorithm>
#include <sw-backend/store.h>
#include <generic-backend/exception.h>
#include <ss-migrate.h>

namespace {
const char *const CERT_SYSTEM_DIR          = CA_CERTS_DIR;
const char *const SYSTEM_DB_PASSWD         = "cAtRugU7";

bool isClientValid(const CKM::ClientId &client)
{
	if (client.find(CKM::ALIAS_SEPARATOR) != CKM::ClientId::npos)
		return false;

	return true;
}

bool isNameValid(const CKM::Name &name)
{
	if (name.find(CKM::ALIAS_SEPARATOR) != CKM::Name::npos)
		return false;

	return true;
}

} // anonymous namespace

namespace CKM {

const uid_t CKMLogic::SYSTEM_DB_UID = 0;
const uid_t CKMLogic::ADMIN_USER_DB_UID = 5001;

CKMLogic::CKMLogic()
{
	CertificateConfig::addSystemCertificateDir(CERT_SYSTEM_DIR);

	m_accessControl.updateCCMode();
}

CKMLogic::~CKMLogic() {}

void CKMLogic::loadDKEKFile(uid_t user, const Password &password)
{
	auto &handle = m_userDataMap[user];

	FileSystem fs(user);

	auto wrappedDKEK = fs.getDKEK();

	if (wrappedDKEK.empty()) {
		wrappedDKEK = KeyProvider::generateDomainKEK(std::to_string(user), password);
		fs.saveDKEK(wrappedDKEK);
	}

	handle.keyProvider = KeyProvider(wrappedDKEK, password);
}

void CKMLogic::saveDKEKFile(uid_t user, const Password &password)
{
	auto &handle = m_userDataMap[user];

	FileSystem fs(user);
	fs.saveDKEK(handle.keyProvider.getWrappedDomainKEK(password));
}

void CKMLogic::migrateSecureStorageData(bool isAdminUser)
{
	SsMigration::migrate(isAdminUser, [this](const std::string &name,
											 const Crypto::Data &data,
											 bool adminUserFlag) {
		LogInfo("Migrate data called with  name: " << name);
		auto ownerId = adminUserFlag ? CLIENT_ID_ADMIN_USER : CLIENT_ID_SYSTEM;
		auto uid = adminUserFlag ? ADMIN_USER_DB_UID : SYSTEM_DB_UID;

		int ret = verifyAndSaveDataHelper(Credentials(uid, ownerId), name, ownerId, data,
										  PolicySerializable());

		if (ret == CKM_API_ERROR_DB_ALIAS_EXISTS)
			LogWarning("Alias already exist for migrated name: " << name);
		else if (ret != CKM_API_SUCCESS)
			LogError("Failed to migrate secure-storage data. name: " << name <<
					 " ret: " << ret);
	});
}

int CKMLogic::unlockDatabase(uid_t user, const Password &password)
{
	if (0 < m_userDataMap.count(user) &&
			m_userDataMap[user].keyProvider.isInitialized())
		return CKM_API_SUCCESS;

	int retCode = CKM_API_SUCCESS;

	try {
		auto &handle = m_userDataMap[user];

		FileSystem fs(user);
		loadDKEKFile(user, password);

		auto wrappedDatabaseDEK = fs.getDBDEK();

		if (wrappedDatabaseDEK.empty()) {
			wrappedDatabaseDEK = handle.keyProvider.generateDEK(std::to_string(user));
			fs.saveDBDEK(wrappedDatabaseDEK);
		}

		RawBuffer key = handle.keyProvider.getPureDEK(wrappedDatabaseDEK);

		handle.database = DB::Crypto(fs.getDBPath(), key);
		handle.crypto = CryptoLogic();

		if (!m_accessControl.isSystemService(user)) {
			// remove data of removed apps during locked state
			ClientIdVector removedApps = fs.clearRemovedsApps();

			for (auto &app : removedApps) {
				handle.crypto.removeKey(app);
				handle.database.deleteKey(app);
			}
		}

		if (user == SYSTEM_DB_UID && SsMigration::hasData())
			migrateSecureStorageData(false);
		else if (user == ADMIN_USER_DB_UID && SsMigration::hasData())
			migrateSecureStorageData(true);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	if (CKM_API_SUCCESS != retCode)
		m_userDataMap.erase(user);

	return retCode;
}

int CKMLogic::unlockSystemDB()
{
	return unlockDatabase(SYSTEM_DB_UID, SYSTEM_DB_PASSWD);
}

UserData &CKMLogic::selectDatabase(const Credentials &cred,
								   const ClientId &explicitOwner)
{
	// if user trying to access system service - check:
	//    * if user database is unlocked [mandatory]
	//    * if not - proceed with regular user database
	//    * if explicit system database owner given -> switch to system DB
	if (!m_accessControl.isSystemService(cred)) {
		if (0 == m_userDataMap.count(cred.clientUid))
			ThrowErr(Exc::DatabaseLocked, "database with UID: ", cred.clientUid, " locked");

		if (0 != explicitOwner.compare(CLIENT_ID_SYSTEM))
			return m_userDataMap[cred.clientUid];
	}

	// system database selected, modify the owner id
	if (CKM_API_SUCCESS != unlockSystemDB())
		ThrowErr(Exc::DatabaseLocked, "can not unlock system database");

	return m_userDataMap[SYSTEM_DB_UID];
}

RawBuffer CKMLogic::unlockUserKey(uid_t user, const Password &password)
{
	int retCode = CKM_API_SUCCESS;

	if (!m_accessControl.isSystemService(user))
		retCode = unlockDatabase(user, password);
	else // do not allow lock/unlock operations for system users
		retCode = CKM_API_ERROR_INPUT_PARAM;

	return MessageBuffer::Serialize(retCode).Pop();
}

RawBuffer CKMLogic::updateCCMode()
{
	m_accessControl.updateCCMode();
	return MessageBuffer::Serialize(CKM_API_SUCCESS).Pop();
}

RawBuffer CKMLogic::lockUserKey(uid_t user)
{
	int retCode = CKM_API_SUCCESS;

	if (!m_accessControl.isSystemService(user))
		m_userDataMap.erase(user);
	else // do not allow lock/unlock operations for system users
		retCode = CKM_API_ERROR_INPUT_PARAM;

	return MessageBuffer::Serialize(retCode).Pop();
}

RawBuffer CKMLogic::removeUserData(uid_t user)
{
	int retCode = CKM_API_SUCCESS;

	if (m_accessControl.isSystemService(user))
		user = SYSTEM_DB_UID;

	m_userDataMap.erase(user);

	FileSystem fs(user);
	fs.removeUserData();

	return MessageBuffer::Serialize(retCode).Pop();
}

int CKMLogic::changeUserPasswordHelper(uid_t user,
									   const Password &oldPassword,
									   const Password &newPassword)
{
	// do not allow to change system database password
	if (m_accessControl.isSystemService(user))
		return CKM_API_ERROR_INPUT_PARAM;

	loadDKEKFile(user, oldPassword);
	saveDKEKFile(user, newPassword);

	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::changeUserPassword(
	uid_t user,
	const Password &oldPassword,
	const Password &newPassword)
{
	int retCode = CKM_API_SUCCESS;

	try {
		retCode = changeUserPasswordHelper(user, oldPassword, newPassword);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	return MessageBuffer::Serialize(retCode).Pop();
}

int CKMLogic::resetUserPasswordHelper(
	uid_t user,
	const Password &newPassword)
{
	// do not allow to reset system database password
	if (m_accessControl.isSystemService(user))
		return CKM_API_ERROR_INPUT_PARAM;

	int retCode = CKM_API_SUCCESS;

	if (0 == m_userDataMap.count(user)) {
		// Check if key exists. If exists we must return error
		FileSystem fs(user);
		auto wrappedDKEKMain = fs.getDKEK();

		if (!wrappedDKEKMain.empty())
			retCode = CKM_API_ERROR_BAD_REQUEST;
	} else {
		saveDKEKFile(user, newPassword);
	}

	return retCode;
}

RawBuffer CKMLogic::resetUserPassword(
	uid_t user,
	const Password &newPassword)
{
	int retCode = CKM_API_SUCCESS;

	try {
		retCode = resetUserPasswordHelper(user, newPassword);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	return MessageBuffer::Serialize(retCode).Pop();
}

RawBuffer CKMLogic::removeApplicationData(const ClientId &owner)
{
	int retCode = CKM_API_SUCCESS;

	try {
		if (owner.empty()) {
			retCode = CKM_API_ERROR_INPUT_PARAM;
		} else {
			UidVector uids = FileSystem::getUIDsFromDBFile();

			for (auto userId : uids) {
				if (0 == m_userDataMap.count(userId)) {
					FileSystem fs(userId);
					fs.addRemovedApp(owner);
				} else {
					auto &handle = m_userDataMap[userId];
					handle.crypto.removeKey(owner);
					handle.database.deleteKey(owner);
				}
			}
		}
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	return MessageBuffer::Serialize(retCode).Pop();
}

int CKMLogic::checkSaveConditions(
	const Credentials &accessorCred,
	UserData &handler,
	const Name &name,
	const ClientId &owner)
{
	// verify name and client are correct
	if (!isNameValid(name) || !isClientValid(owner)) {
		LogDebug("Invalid parameter passed to key-manager");
		return CKM_API_ERROR_INPUT_PARAM;
	}

	// check if accessor is allowed to save owner's items
	int access_ec = m_accessControl.canSave(accessorCred, owner);

	if (access_ec != CKM_API_SUCCESS) {
		LogDebug("accessor " << accessorCred.client << " can not save rows owned by " <<
				 owner);
		return access_ec;
	}

	// check if not a duplicate
	if (handler.database.isNameOwnerPresent(name, owner))
		return CKM_API_ERROR_DB_ALIAS_EXISTS;

	// encryption section
	if (!handler.crypto.haveKey(owner)) {
		RawBuffer got_key;
		auto key_optional = handler.database.getKey(owner);

		if (!key_optional) {
			LogDebug("No Key in database found. Generating new one for client: " <<
					 owner);
			got_key = handler.keyProvider.generateDEK(owner);
			handler.database.saveKey(owner, got_key);
		} else {
			LogDebug("Key from DB");
			got_key = *key_optional;
		}

		got_key = handler.keyProvider.getPureDEK(got_key);
		handler.crypto.pushKey(owner, got_key);
	}

	return CKM_API_SUCCESS;
}

DB::Row CKMLogic::createEncryptedRow(
	CryptoLogic &crypto,
	const Name &name,
	const ClientId &owner,
	const Crypto::Data &data,
	const Policy &policy) const
{
	Crypto::GStore &store = m_decider.getStore(data.type, policy);

	// do not encrypt data with password during cc_mode on
	Token token = store.import(data,
							   m_accessControl.isCCMode() ? "" : policy.password,
							   Crypto::EncryptionParams());
	DB::Row row(std::move(token), name, owner,
				static_cast<int>(policy.extractable));
	crypto.encryptRow(row);
	return row;
}

int CKMLogic::verifyBinaryData(Crypto::Data &input) const
{
	Crypto::Data dummy;
	return toBinaryData(input, dummy);
}

int CKMLogic::toBinaryData(const Crypto::Data &input,
						   Crypto::Data &output) const
{
	// verify the data integrity
	if (input.type.isKey()) {
		KeyShPtr output_key;

		if (input.type.isSKey())
			output_key = CKM::Key::createAES(input.data);
		else
			output_key = CKM::Key::create(input.data);

		if (output_key.get() == NULL) {
			LogDebug("provided binary data is not valid key data");
			return CKM_API_ERROR_INPUT_PARAM;
		}

		output = std::move(Crypto::Data(input.type, output_key->getDER()));
	} else if (input.type.isCertificate() || input.type.isChainCert()) {
		CertificateShPtr cert = CKM::Certificate::create(input.data,
								DataFormat::FORM_DER);

		if (cert.get() == NULL) {
			LogDebug("provided binary data is not valid certificate data");
			return CKM_API_ERROR_INPUT_PARAM;
		}

		output = std::move(Crypto::Data(input.type, cert->getDER()));
	} else {
		output = input;
	}

	// TODO: add here BINARY_DATA verification, i.e: max size etc.
	return CKM_API_SUCCESS;
}

int CKMLogic::verifyAndSaveDataHelper(
	const Credentials &cred,
	const Name &name,
	const ClientId &explicitOwner,
	const Crypto::Data &data,
	const PolicySerializable &policy)
{
	int retCode = CKM_API_ERROR_UNKNOWN;

	try {
		// check if data is correct
		Crypto::Data binaryData;
		retCode = toBinaryData(data, binaryData);

		if (retCode != CKM_API_SUCCESS)
			return retCode;
		else
			return saveDataHelper(cred, name, explicitOwner, binaryData, policy);
	} catch (const Exc::Exception &e) {
		return e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		return CKM_API_ERROR_SERVER_ERROR;
	}
}

int CKMLogic::getKeyForService(
	const Credentials &cred,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &pass,
	Crypto::GObjShPtr &key)
{
	try {
		// Key is for internal service use. It won't be exported to the client
		Crypto::GObjUPtr obj;
		int retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, name, explicitOwner,
									 pass, obj);

		if (retCode == CKM_API_SUCCESS)
			key = std::move(obj);

		return retCode;
	} catch (const Exc::Exception &e) {
		return e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		return CKM_API_ERROR_SERVER_ERROR;
	}
}

RawBuffer CKMLogic::saveData(
	const Credentials &cred,
	int commandId,
	const Name &name,
	const ClientId &explicitOwner,
	const Crypto::Data &data,
	const PolicySerializable &policy)
{
	int retCode = verifyAndSaveDataHelper(cred, name, explicitOwner, data, policy);
	auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::SAVE),
					commandId,
					retCode,
					static_cast<int>(data.type));
	return response.Pop();
}

int CKMLogic::extractPKCS12Data(
	CryptoLogic &crypto,
	const Name &name,
	const ClientId &owner,
	const PKCS12Serializable &pkcs,
	const PolicySerializable &keyPolicy,
	const PolicySerializable &certPolicy,
	DB::RowVector &output) const
{
	// private key is mandatory
	auto key = pkcs.getKey();

	if (!key) {
		LogError("Failed to get private key from pkcs");
		return CKM_API_ERROR_INVALID_FORMAT;
	}

	Crypto::Data keyData(DataType(key->getType()), key->getDER());
	int retCode = verifyBinaryData(keyData);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	output.push_back(createEncryptedRow(crypto, name, owner, keyData,
										keyPolicy));

	// certificate is mandatory
	auto cert = pkcs.getCertificate();

	if (!cert) {
		LogError("Failed to get certificate from pkcs");
		return CKM_API_ERROR_INVALID_FORMAT;
	}

	Crypto::Data certData(DataType::CERTIFICATE, cert->getDER());
	retCode = verifyBinaryData(certData);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	output.push_back(createEncryptedRow(crypto, name, owner, certData,
										certPolicy));

	// CA cert chain
	unsigned int cert_index = 0;

	for (const auto &ca : pkcs.getCaCertificateShPtrVector()) {
		Crypto::Data caCertData(DataType::getChainDatatype(cert_index ++),
								ca->getDER());
		int retCode = verifyBinaryData(caCertData);

		if (retCode != CKM_API_SUCCESS)
			return retCode;

		output.push_back(createEncryptedRow(crypto, name, owner, caCertData,
											certPolicy));
	}

	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::savePKCS12(
	const Credentials &cred,
	int commandId,
	const Name &name,
	const ClientId &explicitOwner,
	const PKCS12Serializable &pkcs,
	const PolicySerializable &keyPolicy,
	const PolicySerializable &certPolicy)
{
	int retCode = CKM_API_ERROR_UNKNOWN;

	try {
		retCode = saveDataHelper(cred, name, explicitOwner, pkcs, keyPolicy, certPolicy);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::SAVE_PKCS12),
					commandId,
					retCode);
	return response.Pop();
}


int CKMLogic::removeDataHelper(
	const Credentials &cred,
	const Name &name,
	const ClientId &explicitOwner)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	if (!isNameValid(name) || !isClientValid(owner)) {
		LogDebug("Invalid owner or name format");
		return CKM_API_ERROR_INPUT_PARAM;
	}

	DB::Crypto::Transaction transaction(&handler.database);

	// read and check permissions
	PermissionMaskOptional permissionRowOpt =
		handler.database.getPermissionRow(name, owner, cred.client);
	int retCode = m_accessControl.canDelete(cred,
											toPermissionMask(permissionRowOpt));

	if (retCode != CKM_API_SUCCESS) {
		LogWarning("access control check result: " << retCode);
		return retCode;
	}

	// get all matching rows
	DB::RowVector rows;
	handler.database.getRows(name, owner, DataType::DB_FIRST,
							 DataType::DB_LAST, rows);

	if (rows.empty()) {
		LogDebug("No row for given name and owner");
		return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
	}

	// load app key if needed
	retCode = loadAppKey(handler, rows.front().owner);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	// destroy it in store
	for (auto &r : rows) {
		try {
			handler.crypto.decryptRow(Password(), r);
			m_decider.getStore(r).destroy(r);
		} catch (const Exc::AuthenticationFailed &) {
			LogDebug("Authentication failed when removing data. Ignored.");
		}
	}

	// delete row in db
	handler.database.deleteRow(name, owner);
	transaction.commit();

	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::removeData(
	const Credentials &cred,
	int commandId,
	const Name &name,
	const ClientId &explicitOwner)
{
	int retCode = CKM_API_ERROR_UNKNOWN;

	try {
		retCode = removeDataHelper(cred, name, explicitOwner);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("Error: " << e.GetMessage());
		retCode = CKM_API_ERROR_DB_ERROR;
	}

	auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::REMOVE),
					commandId,
					retCode);
	return response.Pop();
}

int CKMLogic::readSingleRow(const Name &name,
							const ClientId &owner,
							DataType dataType,
							DB::Crypto &database,
							DB::Row &row)
{
	DB::Crypto::RowOptional row_optional;

	if (dataType.isKey()) {
		// read all key types
		row_optional = database.getRow(name,
									   owner,
									   DataType::DB_KEY_FIRST,
									   DataType::DB_KEY_LAST);
	} else {
		// read anything else
		row_optional = database.getRow(name,
									   owner,
									   dataType);
	}

	if (!row_optional) {
		LogDebug("No row for given name, owner and type");
		return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
	} else {
		row = *row_optional;
	}

	return CKM_API_SUCCESS;
}


int CKMLogic::readMultiRow(const Name &name,
						   const ClientId &owner,
						   DataType dataType,
						   DB::Crypto &database,
						   DB::RowVector &output)
{
	if (dataType.isKey())
		// read all key types
		database.getRows(name,
						 owner,
						 DataType::DB_KEY_FIRST,
						 DataType::DB_KEY_LAST,
						 output);
	else if (dataType.isChainCert())
		// read all key types
		database.getRows(name,
						 owner,
						 DataType::DB_CHAIN_FIRST,
						 DataType::DB_CHAIN_LAST,
						 output);
	else
		// read anything else
		database.getRows(name,
						 owner,
						 dataType,
						 output);

	if (!output.size()) {
		LogDebug("No row for given name, owner and type");
		return CKM_API_ERROR_DB_ALIAS_UNKNOWN;
	}

	return CKM_API_SUCCESS;
}

int CKMLogic::checkDataPermissionsHelper(const Credentials &accessorCred,
		const Name &name,
		const ClientId &owner,
		const DB::Row &row,
		bool exportFlag,
		DB::Crypto &database)
{
	PermissionMaskOptional permissionRowOpt =
		database.getPermissionRow(name, owner, accessorCred.client);

	if (exportFlag)
		return m_accessControl.canExport(accessorCred,
										 row,
										 toPermissionMask(permissionRowOpt));

	return m_accessControl.canRead(accessorCred,
								   toPermissionMask(permissionRowOpt));
}

Crypto::GObjUPtr CKMLogic::rowToObject(
	UserData &handler,
	DB::Row row,
	const Password &password)
{
	Crypto::GStore &store = m_decider.getStore(row);

	Password pass = m_accessControl.isCCMode() ? "" : password;

	// decrypt row
	Crypto::GObjUPtr obj;

	if (CryptoLogic::getSchemeVersion(row.encryptionScheme) ==
			CryptoLogic::ENCRYPTION_V2) {
		handler.crypto.decryptRow(Password(), row);

		obj = store.getObject(row, pass);
	} else {
		// decrypt entirely with old scheme: b64(pass(appkey(data))) -> data
		handler.crypto.decryptRow(pass, row);
		// destroy it in store
		store.destroy(row);

		// import it to store with new scheme: data -> pass(data)
		Token token = store.import(Crypto::Data(row.dataType, row.data), pass, Crypto::EncryptionParams());

		// get it from the store (it can be different than the data we imported into store)
		obj = store.getObject(token, pass);

		// update row with new token
		*static_cast<Token *>(&row) = std::move(token);

		// encrypt it with app key: pass(data) -> b64(appkey(pass(data))
		handler.crypto.encryptRow(row);

		// update it in db
		handler.database.updateRow(row);
	}

	return obj;
}

int CKMLogic::readDataHelper(
	bool exportFlag,
	const Credentials &cred,
	DataType dataType,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &password,
	Crypto::GObjUPtrVector &objs)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	if (!isNameValid(name) || !isClientValid(owner))
		return CKM_API_ERROR_INPUT_PARAM;

	// read rows
	DB::Crypto::Transaction transaction(&handler.database);
	DB::RowVector rows;
	int retCode = readMultiRow(name, owner, dataType, handler.database, rows);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	// all read rows belong to the same owner
	DB::Row &firstRow = rows.at(0);

	// check access rights
	retCode = checkDataPermissionsHelper(cred, name, owner, firstRow,
										 exportFlag, handler.database);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	// load app key if needed
	retCode = loadAppKey(handler, firstRow.owner);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	// decrypt row
	for (auto &row : rows)
		objs.push_back(rowToObject(handler, std::move(row), password));

	// rowToObject may modify db
	transaction.commit();

	return CKM_API_SUCCESS;
}

int CKMLogic::readDataHelper(
	bool exportFlag,
	const Credentials &cred,
	DataType dataType,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &password,
	Crypto::GObjUPtr &obj)
{
	DataType objDataType;
	return readDataHelper(exportFlag, cred, dataType, name, explicitOwner,
						  password, obj, objDataType);
}

int CKMLogic::readDataHelper(
	bool exportFlag,
	const Credentials &cred,
	DataType dataType,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &password,
	Crypto::GObjUPtr &obj,
	DataType &objDataType)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	if (!isNameValid(name) || !isClientValid(owner))
		return CKM_API_ERROR_INPUT_PARAM;

	// read row
	DB::Crypto::Transaction transaction(&handler.database);
	DB::Row row;
	int retCode = readSingleRow(name, owner, dataType, handler.database, row);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	objDataType = row.dataType;

	// check access rights
	retCode = checkDataPermissionsHelper(cred, name, owner, row, exportFlag,
									 	 handler.database);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	// load app key if needed
	retCode = loadAppKey(handler, row.owner);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	obj = rowToObject(handler, std::move(row), password);
	// rowToObject may modify db
	transaction.commit();

	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::getData(
	const Credentials &cred,
	int commandId,
	DataType dataType,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &password)
{
	int retCode = CKM_API_SUCCESS;
	RawBuffer rowData;
	DataType objDataType;

	try {
		Crypto::GObjUPtr obj;
		retCode = readDataHelper(true, cred, dataType, name, explicitOwner,
								 password, obj, objDataType);

		if (retCode == CKM_API_SUCCESS)
			rowData = obj->getBinary();
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	if (CKM_API_SUCCESS != retCode)
		rowData.clear();

	auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET),
					commandId,
					retCode,
					static_cast<int>(objDataType),
					rowData);
	return response.Pop();
}

RawBuffer CKMLogic::getDataProtectionStatus(
		const Credentials &cred,
		int commandId,
		DataType dataType,
		const Name &name,
		const ClientId &explicitOwner)
{
	int retCode = CKM_API_SUCCESS;
	bool status = false;
	DataType objDataType;
	Password password;

	try {
		Crypto::GObjUPtr obj;
		retCode = readDataHelper(false, cred, dataType, name, explicitOwner,
								 password, obj, objDataType);

	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	if (retCode == CKM_API_ERROR_AUTHENTICATION_FAILED) {
		status = true;
		retCode = CKM_API_SUCCESS;
	}

	auto response = MessageBuffer::Serialize(static_cast<int>(LogicCommand::GET_PROTECTION_STATUS),
					commandId,
					retCode,
					static_cast<int>(objDataType),
					status);
	return response.Pop();
}

int CKMLogic::getPKCS12Helper(
	const Credentials &cred,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &keyPassword,
	const Password &certPassword,
	KeyShPtr &privKey,
	CertificateShPtr &cert,
	CertificateShPtrVector &caChain)
{
	int retCode;

	// read private key (mandatory)
	Crypto::GObjUPtr keyObj;
	retCode = readDataHelper(true, cred, DataType::DB_KEY_FIRST, name, explicitOwner,
							 keyPassword, keyObj);

	if (retCode != CKM_API_SUCCESS) {
		if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
			return retCode;
	} else {
		privKey = CKM::Key::create(keyObj->getBinary());
	}

	// read certificate (mandatory)
	Crypto::GObjUPtr certObj;
	retCode = readDataHelper(true, cred, DataType::CERTIFICATE, name, explicitOwner,
							 certPassword, certObj);

	if (retCode != CKM_API_SUCCESS) {
		if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
			return retCode;
	} else {
		cert = CKM::Certificate::create(certObj->getBinary(), DataFormat::FORM_DER);
	}

	// read CA cert chain (optional)
	Crypto::GObjUPtrVector caChainObjs;
	retCode = readDataHelper(true, cred, DataType::DB_CHAIN_FIRST, name, explicitOwner,
							 certPassword, caChainObjs);

	if (retCode != CKM_API_SUCCESS && retCode != CKM_API_ERROR_DB_ALIAS_UNKNOWN) {
		if (retCode != CKM_API_ERROR_NOT_EXPORTABLE)
			return retCode;
	} else {
		for (auto &caCertObj : caChainObjs)
			caChain.push_back(CKM::Certificate::create(caCertObj->getBinary(),
													   DataFormat::FORM_DER));
	}

	// if anything found, return it
	if (privKey || cert || caChain.size() > 0)
		retCode = CKM_API_SUCCESS;

	return retCode;
}

RawBuffer CKMLogic::getPKCS12(
	const Credentials &cred,
	int commandId,
	const Name &name,
	const ClientId &explicitOwner,
	const Password &keyPassword,
	const Password &certPassword)
{
	int retCode = CKM_API_ERROR_UNKNOWN;

	PKCS12Serializable output;

	try {
		KeyShPtr privKey;
		CertificateShPtr cert;
		CertificateShPtrVector caChain;
		retCode = getPKCS12Helper(cred, name, explicitOwner, keyPassword,
								  certPassword, privKey, cert, caChain);

		// prepare response
		if (retCode == CKM_API_SUCCESS)
			output = PKCS12Serializable(std::move(privKey), std::move(cert),
										std::move(caChain));
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::GET_PKCS12),
					commandId,
					retCode,
					output);
	return response.Pop();
}

int CKMLogic::getDataListHelper(const Credentials &cred,
								const DataType dataType,
								OwnerNameVector &ownerNameVector)
{
	int retCode = CKM_API_ERROR_DB_LOCKED;

	if (0 < m_userDataMap.count(cred.clientUid)) {
		auto &database = m_userDataMap[cred.clientUid].database;

		try {
			OwnerNameVector tmpVector;

			if (dataType.isKey()) {
				// list all key types
				database.listNames(cred.client,
								   tmpVector,
								   DataType::DB_KEY_FIRST,
								   DataType::DB_KEY_LAST);
			} else {
				// list anything else
				database.listNames(cred.client,
								   tmpVector,
								   dataType);
			}

			ownerNameVector.insert(ownerNameVector.end(), tmpVector.begin(),
								   tmpVector.end());
			retCode = CKM_API_SUCCESS;
		} catch (const CKM::Exception &e) {
			LogError("Error: " << e.GetMessage());
			retCode = CKM_API_ERROR_DB_ERROR;
		} catch (const Exc::Exception &e) {
			retCode = e.error();
		}
	}

	return retCode;
}

RawBuffer CKMLogic::getDataList(
	const Credentials &cred,
	int commandId,
	DataType dataType)
{
	OwnerNameVector systemVector;
	OwnerNameVector userVector;
	OwnerNameVector ownerNameVector;

	int retCode = unlockSystemDB();

	if (CKM_API_SUCCESS == retCode) {
		// system database
		if (m_accessControl.isSystemService(cred)) {
			// lookup system DB
			retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
													CLIENT_ID_SYSTEM),
										dataType,
										systemVector);
		} else {
			// user - lookup system, then client DB
			retCode = getDataListHelper(Credentials(SYSTEM_DB_UID,
													cred.client),
										dataType,
										systemVector);

			// private database
			if (retCode == CKM_API_SUCCESS) {
				retCode = getDataListHelper(cred,
											dataType,
											userVector);
			}
		}
	}

	if (retCode == CKM_API_SUCCESS) {
		ownerNameVector.insert(ownerNameVector.end(), systemVector.begin(),
							   systemVector.end());
		ownerNameVector.insert(ownerNameVector.end(), userVector.begin(),
							   userVector.end());
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::GET_LIST),
					commandId,
					retCode,
					static_cast<int>(dataType),
					ownerNameVector);
	return response.Pop();
}

int CKMLogic::importInitialData(
	const Name &name,
	const Crypto::Data &data,
	const Crypto::EncryptionParams &encParams,
	const Policy &policy)
{
	try {
		if (encParams.iv.empty() != encParams.tag.empty()) {
			LogError("Both iv and tag must be empty or set");
			return CKM_API_ERROR_INPUT_PARAM;
		}

		// Inital values are always imported with root credentials. Client id is not important.
		Credentials rootCred(0, "");

		auto &handler = selectDatabase(rootCred, CLIENT_ID_SYSTEM);

		// check if save is possible
		DB::Crypto::Transaction transaction(&handler.database);
		int retCode = checkSaveConditions(rootCred, handler, name, CLIENT_ID_SYSTEM);

		if (retCode != CKM_API_SUCCESS)
			return retCode;

		Crypto::GStore &store =
				m_decider.getStore(data.type, policy, !encParams.iv.empty());

		Token token;

		if (encParams.iv.empty()) {
            // Data are not encrypted, let's try to verify them
			Crypto::Data binaryData;

			if (CKM_API_SUCCESS != (retCode = toBinaryData(data, binaryData)))
				return retCode;

			token = store.import(binaryData,
								 m_accessControl.isCCMode() ? "" : policy.password,
								 encParams);
		} else {
			token = store.import(data,
								 m_accessControl.isCCMode() ? "" : policy.password,
								 encParams);
		}

		DB::Row row(std::move(token), name, CLIENT_ID_SYSTEM,
					static_cast<int>(policy.extractable));
		handler.crypto.encryptRow(row);

		handler.database.saveRow(row);
		transaction.commit();
	} catch (const Exc::Exception &e) {
		return e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		return CKM_API_ERROR_SERVER_ERROR;
	} catch (const std::exception &e) {
		LogError("Std::exception: " << e.what());
		return CKM_API_ERROR_SERVER_ERROR;
	}

	return CKM_API_SUCCESS;
}

int CKMLogic::saveDataHelper(
	const Credentials &cred,
	const Name &name,
	const ClientId &explicitOwner,
	const Crypto::Data &data,
	const PolicySerializable &policy)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	if (m_accessControl.isSystemService(cred) &&
			owner.compare(CLIENT_ID_SYSTEM) != 0) {
		LogError("System services can only use " << CLIENT_ID_SYSTEM << " as owner id") ;
		return CKM_API_ERROR_INPUT_PARAM;
	}

	// check if save is possible
	DB::Crypto::Transaction transaction(&handler.database);
	int retCode = checkSaveConditions(cred, handler, name, owner);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	// save the data
	DB::Row encryptedRow = createEncryptedRow(handler.crypto, name, owner,
						   data, policy);
	handler.database.saveRow(encryptedRow);

	transaction.commit();
	return CKM_API_SUCCESS;
}

int CKMLogic::saveDataHelper(
	const Credentials &cred,
	const Name &name,
	const ClientId &explicitOwner,
	const PKCS12Serializable &pkcs,
	const PolicySerializable &keyPolicy,
	const PolicySerializable &certPolicy)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	if (m_accessControl.isSystemService(cred) &&
			owner.compare(CLIENT_ID_SYSTEM) != 0)
		return CKM_API_ERROR_INPUT_PARAM;

	// check if save is possible
	DB::Crypto::Transaction transaction(&handler.database);
	int retCode = checkSaveConditions(cred, handler, name, owner);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	// extract and encrypt the data
	DB::RowVector encryptedRows;
	retCode = extractPKCS12Data(handler.crypto, name, owner, pkcs, keyPolicy,
								certPolicy, encryptedRows);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	// save the data
	handler.database.saveRows(name, owner, encryptedRows);
	transaction.commit();

	return CKM_API_SUCCESS;
}


int CKMLogic::createKeyAESHelper(
	const Credentials &cred,
	const int size,
	const Name &name,
	const ClientId &explicitOwner,
	const PolicySerializable &policy)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	if (m_accessControl.isSystemService(cred) &&
			owner.compare(CLIENT_ID_SYSTEM) != 0)
		return CKM_API_ERROR_INPUT_PARAM;

	// check if save is possible
	DB::Crypto::Transaction transaction(&handler.database);
	int retCode = checkSaveConditions(cred, handler, name, owner);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	// create key in store
	CryptoAlgorithm keyGenAlgorithm;
	keyGenAlgorithm.setParam(ParamName::ALGO_TYPE, AlgoType::AES_GEN);
	keyGenAlgorithm.setParam(ParamName::GEN_KEY_LEN, size);
	Token key = m_decider.getStore(DataType::KEY_AES,
	                               policy).generateSKey(keyGenAlgorithm, policy.password);

	// save the data
	DB::Row row(std::move(key), name, owner,
				static_cast<int>(policy.extractable));
	handler.crypto.encryptRow(row);

	handler.database.saveRow(row);

	transaction.commit();
	return CKM_API_SUCCESS;
}

int CKMLogic::createKeyPairHelper(
	const Credentials &cred,
	const CryptoAlgorithmSerializable &keyGenParams,
	const Name &namePrivate,
	const ClientId &explicitOwnerPrivate,
	const Name &namePublic,
	const ClientId &explicitOwnerPublic,
	const PolicySerializable &policyPrivate,
	const PolicySerializable &policyPublic)
{
	auto &handlerPriv = selectDatabase(cred, explicitOwnerPrivate);
	auto &handlerPub = selectDatabase(cred, explicitOwnerPublic);

	AlgoType keyType = AlgoType::RSA_GEN;

	if (!keyGenParams.getParam(ParamName::ALGO_TYPE, keyType))
		ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE not found.");

	DataType dt(keyType);

	if (!dt.isKey())
		ThrowErr(Exc::InputParam, "Error, parameter ALGO_TYPE with wrong value.");

	if (policyPrivate.backend != policyPublic.backend)
		ThrowErr(Exc::InputParam, "Error, key pair must be supported with the same backend.");

	// use client id if not explicitly provided
	const ClientId &ownerPrv = explicitOwnerPrivate.empty() ? cred.client :
							   explicitOwnerPrivate;

	if (m_accessControl.isSystemService(cred) &&
			ownerPrv.compare(CLIENT_ID_SYSTEM) != 0)
		return CKM_API_ERROR_INPUT_PARAM;

	const ClientId &ownerPub = explicitOwnerPublic.empty() ? cred.client :
							   explicitOwnerPublic;

	if (m_accessControl.isSystemService(cred) &&
			ownerPub.compare(CLIENT_ID_SYSTEM) != 0)
		return CKM_API_ERROR_INPUT_PARAM;

	bool exportable = policyPrivate.extractable || policyPublic.extractable;
	Policy lessRestricted(Password(), exportable, policyPrivate.backend);

	TokenPair keys = m_decider.getStore(dt, lessRestricted).generateAKey(keyGenParams,
					 policyPrivate.password,
					 policyPublic.password);

	DB::Crypto::Transaction transactionPriv(&handlerPriv.database);
	// in case the same database is used for private and public - the second
	// transaction will not be executed
	DB::Crypto::Transaction transactionPub(&handlerPub.database);

	int retCode;
	retCode = checkSaveConditions(cred, handlerPriv, namePrivate, ownerPrv);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	retCode = checkSaveConditions(cred, handlerPub, namePublic, ownerPub);

	if (CKM_API_SUCCESS != retCode)
		return retCode;

	// save the data
	DB::Row rowPrv(std::move(keys.first), namePrivate, ownerPrv,
				   static_cast<int>(policyPrivate.extractable));
	handlerPriv.crypto.encryptRow(rowPrv);
	handlerPriv.database.saveRow(rowPrv);

	DB::Row rowPub(std::move(keys.second), namePublic, ownerPub,
				   static_cast<int>(policyPublic.extractable));
	handlerPub.crypto.encryptRow(rowPub);
	handlerPub.database.saveRow(rowPub);

	transactionPub.commit();
	transactionPriv.commit();
	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::createKeyPair(
	const Credentials &cred,
	int commandId,
	const CryptoAlgorithmSerializable &keyGenParams,
	const Name &namePrivate,
	const ClientId &explicitOwnerPrivate,
	const Name &namePublic,
	const ClientId &explicitOwnerPublic,
	const PolicySerializable &policyPrivate,
	const PolicySerializable &policyPublic)
{
	int retCode = CKM_API_SUCCESS;

	try {
		retCode = createKeyPairHelper(
					  cred,
					  keyGenParams,
					  namePrivate,
					  explicitOwnerPrivate,
					  namePublic,
					  explicitOwnerPublic,
					  policyPrivate,
					  policyPublic);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_PAIR),
									commandId, retCode).Pop();
}

RawBuffer CKMLogic::createKeyAES(
	const Credentials &cred,
	int commandId,
	const int size,
	const Name &name,
	const ClientId &explicitOwner,
	const PolicySerializable &policy)
{
	int retCode = CKM_API_SUCCESS;

	try {
		retCode = createKeyAESHelper(cred, size, name, explicitOwner, policy);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (std::invalid_argument &e) {
		LogDebug("invalid argument error: " << e.what());
		retCode = CKM_API_ERROR_INPUT_PARAM;
	} catch (const CKM::Exception &e) {
		LogError("CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	return MessageBuffer::Serialize(static_cast<int>(LogicCommand::CREATE_KEY_AES),
									commandId, retCode).Pop();
}

int CKMLogic::readCertificateHelper(
	const Credentials &cred,
	const OwnerNameVector &ownerNameVector,
	CertificateImplVector &certVector)
{
	for (auto &i : ownerNameVector) {
		// certificates can't be protected with custom user password
		Crypto::GObjUPtr obj;
		int ec;
		ec = readDataHelper(true,
							cred,
							DataType::CERTIFICATE,
							i.second,
							i.first,
							Password(),
							obj);

		if (ec != CKM_API_SUCCESS)
			return ec;

		certVector.emplace_back(obj->getBinary(), DataFormat::FORM_DER);

		// try to read chain certificates (if present)
		Crypto::GObjUPtrVector caChainObjs;
		ec = readDataHelper(true,
							cred,
							DataType::DB_CHAIN_FIRST,
							i.second,
							i.first,
							CKM::Password(),
							caChainObjs);

		if (ec != CKM_API_SUCCESS && ec != CKM_API_ERROR_DB_ALIAS_UNKNOWN)
			return ec;

		for (auto &caCertObj : caChainObjs)
			certVector.emplace_back(caCertObj->getBinary(), DataFormat::FORM_DER);
	}

	return CKM_API_SUCCESS;
}

int CKMLogic::getCertificateChainHelper(
	const CertificateImpl &cert,
	const RawBufferVector &untrustedCertificates,
	const RawBufferVector &trustedCertificates,
	bool useTrustedSystemCertificates,
	RawBufferVector &chainRawVector)
{
	CertificateImplVector untrustedCertVector;
	CertificateImplVector trustedCertVector;
	CertificateImplVector chainVector;

	if (cert.empty())
		return CKM_API_ERROR_INPUT_PARAM;

	for (auto &e : untrustedCertificates) {
		CertificateImpl c(e, DataFormat::FORM_DER);

		if (c.empty())
			return CKM_API_ERROR_INPUT_PARAM;

		untrustedCertVector.push_back(std::move(c));
	}

	for (auto &e : trustedCertificates) {
		CertificateImpl c(e, DataFormat::FORM_DER);

		if (c.empty())
			return CKM_API_ERROR_INPUT_PARAM;

		trustedCertVector.push_back(std::move(c));
	}

	CertificateStore store;
	int retCode = store.verifyCertificate(cert,
										  untrustedCertVector,
										  trustedCertVector,
										  useTrustedSystemCertificates,
										  m_accessControl.isCCMode(),
										  chainVector);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	for (auto &e : chainVector)
		chainRawVector.push_back(e.getDER());

	return CKM_API_SUCCESS;
}

int CKMLogic::getCertificateChainHelper(
	const Credentials &cred,
	const CertificateImpl &cert,
	const OwnerNameVector &untrusted,
	const OwnerNameVector &trusted,
	bool useTrustedSystemCertificates,
	RawBufferVector &chainRawVector)
{
	CertificateImplVector untrustedCertVector;
	CertificateImplVector trustedCertVector;
	CertificateImplVector chainVector;

	if (cert.empty())
		return CKM_API_ERROR_INPUT_PARAM;

	int retCode = readCertificateHelper(cred, untrusted, untrustedCertVector);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	retCode = readCertificateHelper(cred, trusted, trustedCertVector);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	CertificateStore store;
	retCode = store.verifyCertificate(cert,
									  untrustedCertVector,
									  trustedCertVector,
									  useTrustedSystemCertificates,
									  m_accessControl.isCCMode(),
									  chainVector);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	for (auto &i : chainVector)
		chainRawVector.push_back(i.getDER());

	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::getCertificateChain(
	const Credentials & /*cred*/,
	int commandId,
	const RawBuffer &certificate,
	const RawBufferVector &untrustedCertificates,
	const RawBufferVector &trustedCertificates,
	bool useTrustedSystemCertificates)
{
	CertificateImpl cert(certificate, DataFormat::FORM_DER);
	RawBufferVector chainRawVector;
	int retCode = CKM_API_ERROR_UNKNOWN;

	try {
		retCode = getCertificateChainHelper(cert,
											untrustedCertificates,
											trustedCertificates,
											useTrustedSystemCertificates,
											chainRawVector);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const std::exception &e) {
		LogError("STD exception " << e.what());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	} catch (...) {
		LogError("Unknown error.");
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::GET_CHAIN_CERT),
					commandId,
					retCode,
					chainRawVector);
	return response.Pop();
}

RawBuffer CKMLogic::getCertificateChain(
	const Credentials &cred,
	int commandId,
	const RawBuffer &certificate,
	const OwnerNameVector &untrustedCertificates,
	const OwnerNameVector &trustedCertificates,
	bool useTrustedSystemCertificates)
{
	int retCode = CKM_API_ERROR_UNKNOWN;
	CertificateImpl cert(certificate, DataFormat::FORM_DER);
	RawBufferVector chainRawVector;

	try {
		retCode = getCertificateChainHelper(cred,
											cert,
											untrustedCertificates,
											trustedCertificates,
											useTrustedSystemCertificates,
											chainRawVector);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const std::exception &e) {
		LogError("STD exception " << e.what());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	} catch (...) {
		LogError("Unknown error.");
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::GET_CHAIN_ALIAS),
					commandId,
					retCode,
					chainRawVector);
	return response.Pop();
}

RawBuffer CKMLogic::createSignature(
	const Credentials &cred,
	int commandId,
	const Name &privateKeyName,
	const ClientId &explicitOwner,
	const Password &password,           // password for private_key
	const RawBuffer &message,
	const CryptoAlgorithm &cryptoAlg)
{
	RawBuffer signature;

	int retCode = CKM_API_SUCCESS;

	try {
		Crypto::GObjUPtr obj;
		retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST, privateKeyName,
								 explicitOwner, password, obj);

		if (retCode == CKM_API_SUCCESS)
			signature = obj->sign(cryptoAlg, message);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("Unknown CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	} catch (const std::exception &e) {
		LogError("STD exception " << e.what());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::CREATE_SIGNATURE),
					commandId,
					retCode,
					signature);
	return response.Pop();
}

RawBuffer CKMLogic::verifySignature(
	const Credentials &cred,
	int commandId,
	const Name &publicKeyOrCertName,
	const ClientId &explicitOwner,
	const Password &password,           // password for public_key (optional)
	const RawBuffer &message,
	const RawBuffer &signature,
	const CryptoAlgorithm &params)
{
	int retCode = CKM_API_ERROR_VERIFICATION_FAILED;

	try {
		// try certificate first - looking for a public key.
		// in case of PKCS, pub key from certificate will be found first
		// rather than private key from the same PKCS.
		Crypto::GObjUPtr obj;
		retCode = readDataHelper(false, cred, DataType::CERTIFICATE,
								 publicKeyOrCertName, explicitOwner, password, obj);

		if (retCode == CKM_API_ERROR_DB_ALIAS_UNKNOWN)
			retCode = readDataHelper(false, cred, DataType::DB_KEY_FIRST,
									 publicKeyOrCertName, explicitOwner, password, obj);

		if (retCode == CKM_API_SUCCESS)
			retCode = obj->verify(params, message, signature);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("Unknown CKM::Exception: " << e.GetMessage());
		retCode = CKM_API_ERROR_SERVER_ERROR;
	}

	auto response = MessageBuffer::Serialize(static_cast<int>
					(LogicCommand::VERIFY_SIGNATURE),
					commandId,
					retCode);
	return response.Pop();
}

int CKMLogic::setPermissionHelper(
	const Credentials &cred,                // who's the client
	const Name &name,
	const ClientId &explicitOwner,                     // who's the owner
	const ClientId &accessor,             // who will get the access
	const PermissionMask permissionMask)
{
	auto &handler = selectDatabase(cred, explicitOwner);

	// we don't know the client
	if (cred.client.empty() || !isClientValid(cred.client))
		return CKM_API_ERROR_INPUT_PARAM;

	// use client id if not explicitly provided
	const ClientId &owner = explicitOwner.empty() ? cred.client : explicitOwner;

	// verify name and owner are correct
	if (!isNameValid(name) || !isClientValid(owner) ||
			!isClientValid(accessor))
		return CKM_API_ERROR_INPUT_PARAM;

	// currently we don't support modification of owner's permissions to his own rows
	if (owner == accessor)
		return CKM_API_ERROR_INPUT_PARAM;

	// system database does not support write/remove permissions
	if ((0 == owner.compare(CLIENT_ID_SYSTEM)) &&
			(permissionMask & Permission::REMOVE))
		return CKM_API_ERROR_INPUT_PARAM;

	// can the client modify permissions to owner's row?
	int retCode = m_accessControl.canModify(cred, owner);

	if (retCode != CKM_API_SUCCESS)
		return retCode;

	DB::Crypto::Transaction transaction(&handler.database);

	if (!handler.database.isNameOwnerPresent(name, owner))
		return CKM_API_ERROR_DB_ALIAS_UNKNOWN;

	// set permissions to the row owned by owner for accessor
	handler.database.setPermission(name, owner, accessor, permissionMask);
	transaction.commit();

	return CKM_API_SUCCESS;
}

RawBuffer CKMLogic::setPermission(
	const Credentials &cred,
	const int command,
	const int msgID,
	const Name &name,
	const ClientId &explicitOwner,
	const ClientId &accessor,
	const PermissionMask permissionMask)
{
	int retCode;

	try {
		retCode = setPermissionHelper(cred, name, explicitOwner, accessor, permissionMask);
	} catch (const Exc::Exception &e) {
		retCode = e.error();
	} catch (const CKM::Exception &e) {
		LogError("Error: " << e.GetMessage());
		retCode = CKM_API_ERROR_DB_ERROR;
	}

	return MessageBuffer::Serialize(command, msgID, retCode).Pop();
}

int CKMLogic::loadAppKey(UserData &handle, const ClientId &owner)
{
	if (!handle.crypto.haveKey(owner)) {
		RawBuffer key;
		auto key_optional = handle.database.getKey(owner);

		if (!key_optional) {
			LogError("No key for given owner in database");
			return CKM_API_ERROR_DB_ERROR;
		}

		key = *key_optional;
		key = handle.keyProvider.getPureDEK(key);
		handle.crypto.pushKey(owner, key);
	}

	return CKM_API_SUCCESS;
}

} // namespace CKM