summaryrefslogtreecommitdiff
path: root/src/common/service_impl.cpp
blob: 5a1da89a282a086b6463f0e7ca5f51bab9896968 (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
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
/*
 * Copyright (c) 2014-2022 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * This file is licensed under the terms of MIT License or the Apache License
 * Version 2.0 of your choice. See the LICENSE.MIT file for MIT license details.
 * See the LICENSE file or the notice below for Apache License Version 2.0
 * details.
 *
 * 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        service_impl.cpp
 * @author      Michal Witanowski <m.witanowski@samsung.com>
 * @author      Jacek Bukarewicz <j.bukarewicz@samsung.com>
 * @author      Rafal Krypa <r.krypa@samsung.com>
 * @author      Krzysztof Sasiak <k.sasiak@samsung.com>
 * @author      Tomasz Swierczek <t.swierczek@samsung.com>
 * @brief       Implementation of the service methods
 */

#include <fcntl.h>
#include <linux/xattr.h>
#include <limits.h>
#include <pwd.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <dirent.h>
#include <cstring>
#include <algorithm>
#include <memory>

#include <dpl/log/log.h>
#include <dpl/errno_string.h>

#include <sys/smack.h>

#include <config.h>
#include "check-proper-drop.h"
#include "protocols.h"
#include "privilege_db.h"
#include "cynara.h"
#include "permissible-set.h"
#include "smack-exceptions.h"
#include "smack-rules.h"
#include "smack-labels.h"
#include "security-manager.h"
#include "tzplatform-config.h"
#include "utils.h"
#include "filesystem.h"
#include "mount-namespace.h"
#include "privilege-info.h"
#include "service_impl_utils.h"

#include "service_impl.h"

namespace SecurityManager {

InstallHelper::InstallHelper() {
    isUserPkgInstalled = false;
    isOldPkgHybrid = false;
}

UninstallHelper::UninstallHelper() {
    isUserPkgInstalled = false;
    isPkgHybrid = false;
    removePkg = false;
    removeAuthor = false;
    authorHash = std::string();
}

namespace {

class ScopedTransaction {
public:
    ScopedTransaction(PrivilegeDb &privilegeDb) : m_isCommited(false), m_privilegeDb(privilegeDb) {
        m_privilegeDb.BeginTransaction();
    }
    ScopedTransaction(const ScopedTransaction &other) = delete;
    ScopedTransaction& operation(const ScopedTransaction &other) = delete;

    void commit() {
        m_privilegeDb.CommitTransaction();
        m_isCommited = true;
    }
    ~ScopedTransaction() {
        if (!m_isCommited) {
            try {
                m_privilegeDb.RollbackTransaction();
            } catch (const SecurityManager::Exception &e) {
                LogError("Transaction rollback failed: " << e.GetMessage());
            } catch(...) {
                LogError("Transaction rollback failed with unknown exception");
            }
        }
    }
private:
    bool m_isCommited;
    PrivilegeDb &m_privilegeDb;
};

bool verifyAppDefinedPrivileges(app_inst_req &req)
{
    std::vector<std::string> licenseVector;

    for (auto &a : req.apps) {
        for (auto &e : a.appDefinedPrivileges) {
            // check if licenses are set for license-privileges
            if ((std::get<1>(e) == SM_APP_DEFINED_PRIVILEGE_TYPE_LICENSED)
                && (std::get<2>(e).empty()))
            {
                LogError("License privilege delivered empty license!");
                return false;
            }

            // check for collision with system privileges
            if (std::get<0>(e).find("http://tizen.org/privilege/") != std::string::npos) {
                LogError("App defined privilege could not contain: 'http://tizen.org/privilege'");
                return false;
            }

            if (std::get<1>(e) == SM_APP_DEFINED_PRIVILEGE_TYPE_LICENSED)
                licenseVector.push_back(std::get<2>(e));
        }

        // get license from 'client' privileges
        for (auto &e : a.privileges) {
            if (!e.second.empty())
                licenseVector.push_back(e.second);
        }
    }

    // We need to verify licenses placement in filesystem
    // Each license must be marked as SECURITY_MANAGER_PATH_RO
    // and the path must be inside application directory.
    // If we put licenses in pkgPaths all of this will be done
    // during paths verification procedure.
    for (auto &e : licenseVector) {
        std::string tmp = realPath(e);
        if (tmp.empty())
            return false;
        req.pkgPaths.emplace_back(std::move(tmp), SECURITY_MANAGER_PATH_RO);
    }

    return true;
}

void labelSharedPaths(const std::string &baseDir, const std::string &pkgName)
{
    const auto sharedPath = baseDir + ".shared/" + pkgName;
    const auto sharedTmpPath = baseDir + ".shared_tmp/" + pkgName;
    if (FS::directoryStatus(sharedPath) > 0 && FS::directoryStatus(sharedTmpPath) > 0) {
        SmackLabels::setupPkgBasePath(sharedPath);
        SmackLabels::setupPkgBasePath(sharedTmpPath);
    }
}

} // end of anonymous namespace

ServiceImpl::ServiceImpl(Offline offline) :
    m_privilegeDb(offline),
    m_NSMountLogic(m_cynara),
    m_offline(offline)
{
    PrivilegeGids::GroupPrivileges group_privileges;
    m_privilegeDb.GetGroupsRelatedPrivileges(group_privileges);
    m_privilegeGids.init(group_privileges);

    if (!underlying(offline)) {
        const auto checkProperDropFlags = CheckProperDrop::computeFlags();
        if (checkProperDropFlags < 0)
            ThrowMsg(FS::Exception::FileError, "Error computing CheckProperDrop flags."
                    " Unable to set up and verify application sandboxes."
                    " Mandatory functionality malfunctioning."
                    " The security-manager service will not run because of this.");
        m_prepareAppFlags = PrepareAppFlags(checkProperDropFlags) << PREPARE_APP_CPD_FLAG_SHIFT;
        static_assert(CheckProperDrop::N_FLAG_BITS + PREPARE_APP_CPD_FLAG_SHIFT <= 8 * sizeof m_prepareAppFlags,
                "CheckProperDrop flags too large for prepareAppFlags");
    }
}

int ServiceImpl::validatePolicy(const Credentials &creds, policy_entry &policyEntry, CynaraAdminPolicy &cyap)
{
    LogDebug("Authenticating and validating policy update request for user with id: " << creds.uid);
    LogDebug("[policy_entry] app: " << policyEntry.appName
            << " user: " << policyEntry.user
            << " privilege: " << policyEntry.privilege
            << " current: " << policyEntry.currentLevel
            << " max: " << policyEntry.maxLevel);

    //automagically fill missing fields:
    if (policyEntry.user.empty())
        policyEntry.user = std::to_string(creds.uid);

    bool forAdmin;
    int level;

    if (policyEntry.currentLevel.empty()) { //for admin
        if (policyEntry.appName.empty()
            || policyEntry.privilege.empty()) {
            LogError("Bad admin update request");
            return SECURITY_MANAGER_ERROR_BAD_REQUEST;
        }

        if (!policyEntry.maxLevel.compare(SECURITY_MANAGER_DELETE)) {
            level = CYNARA_ADMIN_DELETE;
        } else {
            try {
                level = m_cynaraAdmin.convertToPolicyType(policyEntry.maxLevel);
            } catch (const std::out_of_range& e) {
                LogError("policy max level cannot be: " << policyEntry.maxLevel);
                return SECURITY_MANAGER_ERROR_INPUT_PARAM;
            }
        }
        forAdmin = true;

    } else if (policyEntry.maxLevel.empty()) { //for self
        if (!policyEntry.appName.compare(SECURITY_MANAGER_ANY)
            || !policyEntry.privilege.compare(SECURITY_MANAGER_ANY)
            || policyEntry.appName.empty()
            || policyEntry.privilege.empty()) {
            LogError("Bad privacy manager update request");
            return SECURITY_MANAGER_ERROR_BAD_REQUEST;
        }

        if (!policyEntry.currentLevel.compare(SECURITY_MANAGER_DELETE)) {
            level = CYNARA_ADMIN_DELETE;
        } else {
            try {
                level = m_cynaraAdmin.convertToPolicyType(policyEntry.currentLevel);
            } catch (const std::out_of_range& e) {
                LogError("policy current level cannot be: " << policyEntry.currentLevel);
                return SECURITY_MANAGER_ERROR_INPUT_PARAM;
            }
        }
        forAdmin = false;

    } else { //neither => bad request
        return SECURITY_MANAGER_ERROR_BAD_REQUEST;
    }

    if (!policyEntry.user.compare(SECURITY_MANAGER_ANY))
        policyEntry.user = CYNARA_ADMIN_WILDCARD;
    if (!policyEntry.privilege.compare(SECURITY_MANAGER_ANY))
        policyEntry.privilege = CYNARA_ADMIN_WILDCARD;

    const std::string &privilege = (forAdmin || policyEntry.user.compare(std::to_string(creds.uid))) ?
            PRIVILEGE_POLICY_ADMIN : PRIVILEGE_POLICY_USER;
    if (!authenticate(creds, privilege)) {
        LogError("Not enough privilege to enforce user policy");
        return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
    }

    std::string cynaraClient;
    if (policyEntry.appName.compare(SECURITY_MANAGER_ANY)) {
        cynaraClient = getAppProcessLabel(policyEntry.appName);
        if (cynaraClient.empty()) {
            LogWarning("Cannot set policy for unknown application " << policyEntry.appName);
            return SECURITY_MANAGER_ERROR_APP_UNKNOWN;
        }
    } else {
        cynaraClient = CYNARA_ADMIN_WILDCARD;
    }

    cyap = std::move(CynaraAdminPolicy(
        cynaraClient,
        policyEntry.user,
        policyEntry.privilege,
        level,
        (forAdmin)?CynaraAdmin::Buckets.at(Bucket::ADMIN):CynaraAdmin::Buckets.at(Bucket::PRIVACY_MANAGER)));

    LogDebug("Policy update request authenticated and validated successfully");
    return SECURITY_MANAGER_SUCCESS;
}

Smack::Label ServiceImpl::getAppProcessLabel(const std::string &appName, const std::string &pkgName)
{
    bool isPkgHybrid = m_privilegeDb.IsPackageHybrid(pkgName);
    return SmackLabels::generateProcessLabel(appName, pkgName, isPkgHybrid);
}

Smack::Label ServiceImpl::getAppProcessLabel(const std::string &appName)
{
    std::string pkgName;
    m_privilegeDb.GetAppPkgName(appName, pkgName);
    if (pkgName.empty()) {
        LogWarning("Cannot create label for unknown application: " << appName);
        return "";
    }
    return getAppProcessLabel(appName, pkgName);
}

bool ServiceImpl::sharingExists(const std::string &targetAppName, const std::string &path)
{
    int targetPathCount;
    m_privilegeDb.GetTargetPathSharingCount(targetAppName, path, targetPathCount);
    return targetPathCount != 0;
}

bool ServiceImpl::authenticate(const Credentials &creds, const std::string &privilege)
{
    if (creds.authenticated)
        return true;
    return m_cynara.check(creds.label, privilege,
        std::to_string(creds.uid), std::to_string(creds.pid));
}

bool ServiceImpl::authCheck(const Credentials &creds,
                            const uid_t& uid,
                            int installationType)
{
    if (installationType == SM_APP_INSTALL_LOCAL) {
        if (!authenticate(creds, PRIVILEGE_APPINST_USER)) {
            LogError("Caller is not permitted to manage local applications");
            return false;
        }
        if (uid != creds.uid && !authenticate(creds, PRIVILEGE_USER_ADMIN)) {
            LogError("Caller is not permitted to manage applications for other users");
            return false;
        }
        if (uid == getGlobalUserId()) {
            LogError("Request local installation for global uid=" << uid);
            return false;
        }
    } else {
        if (!authenticate(creds, PRIVILEGE_APPINST_ADMIN)) {
            LogError("Caller is not permitted to manage global applications");
            return false;
        }
    }

    return true;
}

int ServiceImpl::labelPaths(const pkg_paths &paths,
                            const std::string &pkgName,
                            app_install_type installationType,
                            const uid_t &uid,
                            bool isSharedRO)
{
    try {
        if (!m_privilegeDb.PkgNameExists(pkgName)) {
            LogError("No such package: " << pkgName);
            return SECURITY_MANAGER_ERROR_INPUT_PARAM;
        }

        std::string authorHash;
        m_privilegeDb.GetPkgAuthorHash(pkgName, authorHash);

        std::string homePath, skelDir;
        std::vector<std::string> pkgLegalBaseDirs;
        int ret = getLegalPkgBaseDirs(uid, pkgName, installationType, homePath,
                                      skelDir, pkgLegalBaseDirs, isSharedRO, m_offline);
        if (ret != SECURITY_MANAGER_SUCCESS) {
            LogError("Failed to generate legal directories for application");
            return ret;
        }

        // check if paths are inside of legal directories
        if (!pathsCheck(paths, pkgLegalBaseDirs))
            return SECURITY_MANAGER_ERROR_NOT_PATH_OWNER;

        if (isSharedRO) {
            // Label shared_ro base paths for bind mounting
            labelSharedPaths(homePath, pkgName);
            // If there are corresponding paths in skel, label them too
            if (!skelDir.empty())
                labelSharedPaths(skelDir, pkgName);
        }
        // register paths
        for (const auto &pkgPath : paths) {
            const std::string &path = pkgPath.first;
            app_install_path_type pathType = static_cast<app_install_path_type>(pkgPath.second);
            SmackLabels::setupPath(pkgName, path, pathType, authorHash);
        }

        for (const auto &basePath : pkgLegalBaseDirs) {
            if (containSubDir(basePath, paths)) {
                SmackLabels::setupPkgBasePath(basePath);
            }
        }

        return SECURITY_MANAGER_SUCCESS;
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Database error: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidParam &e) {
        LogError("Invalid parameter during labeling: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const SmackException::InvalidPathType &e) {
        LogError("Invalid path type: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::Base &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SETTING_FILE_LABEL_FAILED;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }
}

void ServiceImpl::getPkgLabels(const std::string &pkgName, Smack::Labels &pkgsLabels)
{
    bool isPkgHybrid = m_privilegeDb.IsPackageHybrid(pkgName);
    if (isPkgHybrid) {
        std::vector<std::string> apps;
        m_privilegeDb.GetPkgApps(pkgName, apps);
        for (auto &app : apps) {
            auto appLabel = SmackLabels::generateProcessLabel(app, pkgName, isPkgHybrid);
            app = appLabel;
        }
        pkgsLabels = std::move(apps);
    } else {
        pkgsLabels.push_back(SmackLabels::generateProcessLabel("", pkgName, false));
    }
}

void ServiceImpl::updatePermissibleSet(uid_t uid, int type)
{
    std::vector<std::string> userPkgs;
    m_privilegeDb.GetUserPkgs(uid, userPkgs);
    Smack::Labels labelsForUser;
    for (const auto &pkg : userPkgs) {
        Smack::Labels pkgLabels;
        getPkgLabels(pkg, pkgLabels);
        labelsForUser.insert(labelsForUser.end(), pkgLabels.begin(), pkgLabels.end());
    }
    PermissibleSet::updatePermissibleFile(uid, type, labelsForUser);
}

int ServiceImpl::appInstallInitialChecks(const Credentials &creds, app_inst_req &req)
{
    if (!verifyAppDefinedPrivileges(req))
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;

    setRequestDefaultValues(req.uid, req.installationType);

    LogDebug("Install parameters: pkgName: " << req.pkgName
          << ", uid: " << req.uid << ", target Tizen API ver: "
          << (req.tizenVersion.empty() ? "unknown" : req.tizenVersion));

    if (!authCheck(creds, req.uid, req.installationType)) {
        LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label <<
                 " for app installation denied");
        return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
    }

    return SECURITY_MANAGER_SUCCESS;
}

void ServiceImpl::appInstallPrivileges(app_inst_req::app &app, app_inst_req &req,
        InstallHelper &ih)
{
    // Register application in database
    m_privilegeDb.AddApplication(app.appName, req.pkgName, req.uid,
        req.tizenVersion, req.authorName, req.isHybrid);

    // Update policy for app-defined privileges
    m_privilegeDb.GetAppDefinedPrivileges(app.appName, req.uid, ih.oldAppDefinedPrivileges);

    m_privilegeDb.RemoveAppDefinedPrivileges(app.appName, req.uid);
    m_privilegeDb.AddAppDefinedPrivileges(app.appName, req.uid, app.appDefinedPrivileges);

    m_privilegeDb.RemoveClientPrivileges(app.appName, req.uid);
    for (auto &e : app.privileges) {
        if (!e.second.empty())
            m_privilegeDb.AddClientPrivilege(app.appName, req.uid, e.first, e.second);
    }
}

void ServiceImpl::appInstallCynaraPolicies(app_inst_req::app& app, app_inst_req& req,
        InstallHelper &ih)
{
    // Generate and verify Smack labels
    Smack::Label pkgLabel = SmackLabels::generatePathRWLabel(req.pkgName);
    Smack::Label appLabel = SmackLabels::generateProcessLabel(
        app.appName, req.pkgName, req.isHybrid);
    LogDebug("Generated install parameters: app label: " << appLabel <<
             ", pkg label: " << pkgLabel);

    bool global = req.installationType == SM_APP_INSTALL_GLOBAL ||
                  req.installationType == SM_APP_INSTALL_PRELOADED;

    // Set policy in Cynara
    // FIXME: if package is non-hybrid, all apps in the package will have
    // the same Smack label. The following lines will set policy for all
    // apps in the package using only privileges that were requested for
    // the last one, and discarding everything requested for other app_ids.
    // This bug exists in security-manager since version 1.2.1 (Sep 2016).
    std::vector<std::string> privileges;
    privileges.reserve(app.privileges.size());
    for (auto &priv : app.privileges)
        privileges.push_back(priv.first);

    Smack::Label oldAppLabel = SmackLabels::generateProcessLabel(
            app.appName, req.pkgName, ih.isOldPkgHybrid);

    m_cynaraAdmin.updateAppPolicy(oldAppLabel, appLabel, global,
        req.uid, req.pkgType, req.privLevel, privileges);
    m_cynaraAdmin.updateAppDefinedPolicy(global, req.uid,
        ih.oldAppDefinedPrivileges, app.appDefinedPrivileges);
}

int ServiceImpl::appInstallSmackRules(app_inst_req &req, InstallHelper &ih)
{
    std::string authorHash = std::string();
    Smack::Labels pkgLabels;

    try {
        m_privilegeDb.GetPkgAuthorHash(req.pkgName, authorHash);

        // Check if hybridity is changed if the package is installed
        if (ih.isUserPkgInstalled && ih.isOldPkgHybrid != req.isHybrid) {
            for (auto &app : req.apps) {
                Smack::Label oldAppLabel = SmackLabels::generateProcessLabel(
                    app.appName, req.pkgName, ih.isOldPkgHybrid);
                m_smackRules.uninstallApplicationRules(oldAppLabel, req.pkgName, authorHash);
                if (req.isHybrid) // was not hybrid - all labels were the same
                    break;
            }
        }

        getPkgLabels(req.pkgName, pkgLabels);

        for (auto &app : req.apps) {
            LogDebug("Adding Smack rules for new appName: " << app.appName << " with pkgName: "
                    << req.pkgName << ".");
            Smack::Label appLabel = SmackLabels::generateProcessLabel(
                app.appName, req.pkgName, req.isHybrid);

            m_smackRules.installApplicationRules(appLabel, req.pkgName, authorHash, pkgLabels);
            if (!req.isHybrid) // is not hybrid - all labels are the same
                break;
        }
    } catch (const SmackException::InvalidLabel &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidParam &e) {
        LogError("Invalid paramater during labeling: " << e.GetMessage());
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const SmackException::Base &e) {
        LogError("Error while applying Smack policy for application: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SETTING_FILE_LABEL_FAILED;
    } catch (const SecurityManager::Exception &e) {
        LogError("Security Manager exception: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation error: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const PrivilegeDb::Exception &e) {
        throw;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::appInstall(const Credentials &creds, app_inst_req &req)
{
    int ret;

    try {
        // initial checks
        ret = appInstallInitialChecks(creds, req);
        if (ret != SECURITY_MANAGER_SUCCESS)
            return ret;

        InstallHelper ih;
        ih.isUserPkgInstalled = m_privilegeDb.IsUserPkgInstalled(req.pkgName, req.uid);
        ih.isOldPkgHybrid = ih.isUserPkgInstalled ? m_privilegeDb.IsPackageHybrid(req.pkgName) : req.isHybrid;

        if (ih.isUserPkgInstalled && ih.isOldPkgHybrid != req.isHybrid) {
            LogError("Application conflicts with existing one. " <<
                     "Flag isHybrid from the request is different than in the database. " <<
                     "Use security_manager_app_update instead of security_manager_app_install.");
            return SECURITY_MANAGER_ERROR_INPUT_PARAM;
        }

        // [db] begin
        ScopedTransaction trans(m_privilegeDb);

        for (auto &app : req.apps) {
            // [db] add app
            appInstallPrivileges(app, req, ih);
            // [cynara] update app policy
            appInstallCynaraPolicies(app, req, ih);
        }

        // [db] update shared ro
        bool isAppSharedRO = isSharedRO(req.pkgPaths);
        if (isAppSharedRO)
            m_privilegeDb.SetSharedROPackage(req.pkgName);

        // [db] commit
        trans.commit();
        LogDebug("Application installation commited to database");

        // update permissible set
        updatePermissibleSet(req.uid, req.installationType);

        // label paths
        ret = labelPaths(req.pkgPaths,
                         req.pkgName,
                         static_cast<app_install_type>(req.installationType),
                         req.uid,
                         isAppSharedRO);
        if (ret != SECURITY_MANAGER_SUCCESS)
            return ret;

        // apply and merge Smack rules for apps and pkg
        ret = appInstallSmackRules(req, ih);
        return ret;
    } catch (const PrivilegeDb::Exception::IOError &e) {
        LogError("Cannot access application database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeDb::Exception::ConstraintError &e) {
        LogError("Application conflicts with existing one: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const PrivilegeDb::Exception::InternalError &e) {
        LogError("Error while saving application info to database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const CynaraException::Base &e) {
        LogError("Error while setting Cynara rules for application: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PermissibleSet::PermissibleSetException::Base &e) {
        LogError("Error while updating permissible file: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeInfo::Exception::Base &e) {
        LogError("Error while getting privilege information: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation while setting Cynara rules for application: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }

    return SECURITY_MANAGER_ERROR_SERVER_ERROR;
}

int ServiceImpl::appUpdate(const Credentials &creds, app_inst_req &req)
{
    int ret;

    try {
        // initial checks
        ret = appInstallInitialChecks(creds, req);
        if (ret != SECURITY_MANAGER_SUCCESS)
            return ret;

        InstallHelper ih;
        ih.isUserPkgInstalled = m_privilegeDb.IsUserPkgInstalled(req.pkgName, req.uid);
        ih.isOldPkgHybrid = ih.isUserPkgInstalled ? m_privilegeDb.IsPackageHybrid(req.pkgName) : req.isHybrid;

        if (ih.isUserPkgInstalled and ih.isOldPkgHybrid != req.isHybrid) {
            // search for installed apps in the request
            std::vector<std::string> requestedApps;
            for (auto &app : req.apps) {
                requestedApps.push_back(app.appName);
            }
            std::vector<std::string> installedApps;
            m_privilegeDb.GetUserAppsFromPkg(req.uid, req.pkgName, installedApps);

            // search for apps to uninstall (that are not in the request)
            std::vector<std::string> appsToUninstall;
            for (auto &iApp : installedApps) {
                // check if iApp is in the request, if not add it to the appsToUninstall vector
                if (std::find(requestedApps.begin(), requestedApps.end(), iApp) == requestedApps.end()) {
                    appsToUninstall.push_back(iApp);
                }
            }

            // if there are apps to uninstall, create new request and uninstall apps
            if (!appsToUninstall.empty()) {
                app_inst_req reqUninstall = req;
                reqUninstall.apps.clear();
                for (auto &appName : appsToUninstall) {
                    app_inst_req::app tmpApp;
                    tmpApp.appName = appName;
                    reqUninstall.apps.push_back(tmpApp);
                }
                appUninstall(creds, reqUninstall);
            }
        }

        // [db] begin
        ScopedTransaction trans(m_privilegeDb);

        for (auto &app : req.apps) {
            // [db] add app
            appInstallPrivileges(app, req, ih);
            // [cynara] update app policy
            appInstallCynaraPolicies(app, req, ih);
        }

        // [db] update shared ro
        bool isAppSharedRO = isSharedRO(req.pkgPaths);
        m_privilegeDb.SetSharedROPackage(req.pkgName, isAppSharedRO);

        // [db] commit
        trans.commit();
        LogDebug("Application installation commited to database");

        // update permissible set
        updatePermissibleSet(req.uid, req.installationType);

        // label paths
        ret = labelPaths(req.pkgPaths,
                         req.pkgName,
                         static_cast<app_install_type>(req.installationType),
                         req.uid,
                         isAppSharedRO);
        if (ret != SECURITY_MANAGER_SUCCESS)
            return ret;

        // apply and merge Smack rules for apps and pkg
        ret = appInstallSmackRules(req, ih);
        return ret;
    } catch (const PrivilegeDb::Exception::IOError &e) {
        LogError("Cannot access application database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeDb::Exception::ConstraintError &e) {
        LogError("Application conflicts with existing one: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const PrivilegeDb::Exception::InternalError &e) {
        LogError("Error while saving application info to database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const CynaraException::Base &e) {
        LogError("Error while setting Cynara rules for application: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PermissibleSet::PermissibleSetException::Base &e) {
        LogError("Error while updating permissible file: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeInfo::Exception::Base &e) {
        LogError("Error while getting privilege information: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation while setting Cynara rules for application: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }

    return SECURITY_MANAGER_ERROR_SERVER_ERROR;
}

int ServiceImpl::appUninstallInitialChecks(const Credentials &creds, app_inst_req &req, int &toRemove)
{
    setRequestDefaultValues(req.uid, req.installationType);

    LogDebug("Uninstall parameters: pkgName=" << req.pkgName << ", uid=" << req.uid);

    if (!authCheck(creds, req.uid, req.installationType)) {
        LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label <<
                 " for app uninstallation denied");
        return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
    }

    for (auto &app : req.apps) {
        std::string pkgName;
        m_privilegeDb.GetAppPkgName(app.appName, pkgName);

        // Invalid appNames in request will be ignored
        if (pkgName.empty()) {
            LogWarning("Application " << app.appName << " not found in database "
                       "while uninstalling");
            // Mark this appName to be ignored by remaining code
            app.appName.clear();
            continue;
        }

        if (req.pkgName.empty()) {
            req.pkgName = pkgName;
        } else if (req.pkgName != pkgName) {
            LogError("Application " << app.appName << " exists, but wrong package id "
                     << req.pkgName << " is passed, should be: " << pkgName);
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }
        ++toRemove;
    }

    return SECURITY_MANAGER_SUCCESS;
}

void ServiceImpl::appUninstallPrivileges(app_inst_req::app &app, app_inst_req &req,
        UninstallHelper &uh)
{
    std::map<std::string, std::vector<std::string>> asOwnerSharing;
    m_privilegeDb.GetPrivateSharingForOwner(app.appName, asOwnerSharing);

    for (const auto &targetPathsInfo : asOwnerSharing) {
        const auto &targetAppName = targetPathsInfo.first;
        const auto &paths = targetPathsInfo.second;
        // Squash sharing - change counter to 1, so dropPrivatePathSharing will completely clean it
        for (const auto &path : paths) {
            m_privilegeDb.SquashSharing(targetAppName, path);
            auto targetAppLabel = getAppProcessLabel(targetAppName);
            int ret = dropOnePrivateSharing(app.appName, req.pkgName, uh.pkgLabels,
                                            targetAppName, targetAppLabel, path);
            if (ret != SECURITY_MANAGER_SUCCESS) {
                //Ignore error, we want to drop as much as we can
                LogError("Couldn't drop sharing between " << app.appName << " and " << targetAppName);
            }
        }
    }

    std::map<std::string, std::vector<std::string>> asTargetSharing;
    m_privilegeDb.GetPrivateSharingForTarget(app.appName, asTargetSharing);

    Smack::Label processLabel = getAppProcessLabel(app.appName, req.pkgName);
    for (const auto &ownerPathsInfo : asTargetSharing) {
        const auto &ownerAppName = ownerPathsInfo.first;
        const auto &paths = ownerPathsInfo.second;
        // Squash sharing - change counter to 1, so dropPrivatePathSharing will completely clean it
        std::string ownerPkgName;
        Smack::Labels ownerPkgLabels;
        m_privilegeDb.GetAppPkgName(ownerAppName, ownerPkgName);
        getPkgLabels(ownerPkgName, ownerPkgLabels);
        for (const auto &path : paths) {
            m_privilegeDb.SquashSharing(app.appName, path);
            int ret = dropOnePrivateSharing(ownerAppName, ownerPkgName, ownerPkgLabels,
                                            app.appName, processLabel, path);
            if (ret != SECURITY_MANAGER_SUCCESS) {
                //Ignore error, we want to drop as much as we can
                LogError("Couldn't drop sharing between " << app.appName << " and " << ownerAppName);
            }
        }
    }

    m_privilegeDb.GetAppDefinedPrivileges(app.appName, req.uid, uh.oldAppDefinedPrivileges);
}

void ServiceImpl::appUninstallCynaraPolicies(const std::string &processLabel, app_inst_req &req,
        UninstallHelper &ui)
{
    LogDebug("Removing Cynara policy for: pkgName=" << req.pkgName
             << " Smack label=" << processLabel);

    bool global = req.installationType == SM_APP_INSTALL_GLOBAL ||
                  req.installationType == SM_APP_INSTALL_PRELOADED;

    // FIXME: if package is non-hybrid, there may still be some apps left
    // in it after uninstallation. The following code will clear Cynara
    // policy for entire package, as all apps in non-hybrid package have
    // the same Smack label.
    // This bug exists in security-manager since version 1.2.1 (Sep 2016).
    m_cynaraAdmin.updateAppPolicy(processLabel, global,
        req.uid, req.pkgType, req.privLevel, std::vector<std::string>(), true);
    m_cynaraAdmin.updateAppDefinedPolicy(global, req.uid,
        ui.oldAppDefinedPrivileges, AppDefinedPrivilegesVector());
}

int ServiceImpl::appUninstallSmackRules(app_inst_req &req, UninstallHelper &uh)
{
    try {
        LogDebug("Removing Smack rules for pkgName " << req.pkgName);
        m_smackRules.uninstallPackageRules(req.pkgName, uh.pkgLabels);

        for (unsigned appIdx = 0; appIdx < req.apps.size(); ++appIdx) {
            if (uh.removeApps[appIdx]) {
                const std::string &appName = req.apps[appIdx].appName;
                Smack::Label processLabel = SmackLabels::generateProcessLabel(appName, req.pkgName, uh.isPkgHybrid);
                LogDebug("Removing Smack rules for appName " << appName);
                if (uh.removePkg || uh.isPkgHybrid || req.isHybrid) {
                    /*
                     * Nonhybrid apps have the same label, so revoking it is unnecessary
                     * unless whole package is being removed.
                     */
                    m_smackRules.uninstallApplicationRules(processLabel, req.pkgName, uh.authorHash);
                }
                if (!uh.removePkg) {
                    uh.pkgLabels.erase(std::remove(uh.pkgLabels.begin(), uh.pkgLabels.end(), processLabel),
                                    uh.pkgLabels.end());
                }
            }
        }

        if (!uh.removePkg) {
            LogDebug("Recreating Smack rules for pkgName " << req.pkgName);
            m_smackRules.updatePackageRules(req.pkgName, uh.pkgLabels);
        }

        if (!uh.authorHash.empty() && uh.removeAuthor) {
            LogDebug("Removing Smack rules for author " << uh.authorHash);
            m_smackRules.uninstallAuthorRules(uh.authorHash);
        }
    } catch (const SmackException::Base &e) {
        LogError("Error while removing Smack rules for application: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SETTING_FILE_LABEL_FAILED;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation error: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const PrivilegeDb::Exception &e) {
        throw;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::appUninstall(const Credentials &creds, app_inst_req &req)
{
    try {
        // initial checks
        int toRemove = 0;
        int ret = appUninstallInitialChecks(creds, req, toRemove);
        if (ret != SECURITY_MANAGER_SUCCESS) {
            return ret;
        } else {
            // When all app_ids in the request were non-existent, do nothing.
            if (toRemove == 0)
                return SECURITY_MANAGER_SUCCESS;
        }

        // Before we remove the app from the database, let's fetch all apps in the package
        // that this app belongs to, this will allow us to remove all rules within the
        // package that the app appears in
        UninstallHelper uh;
        m_privilegeDb.GetPkgAuthorHash(req.pkgName, uh.authorHash);
        getPkgLabels(req.pkgName, uh.pkgLabels);
        uh.isPkgHybrid = m_privilegeDb.IsPackageHybrid(req.pkgName);

        LogDebug("Uninstalling pkg: " << req.pkgName << " with " << req.apps.size() << " apps");
        for (auto &app: req.apps) {
            LogDebug("-- Removing app: " << app.appName);
        }

        // [db] begin
        ScopedTransaction trans(m_privilegeDb);

        for (auto &app : req.apps) {
            bool removeApp = false;
            if (!app.appName.empty()) {
                // [db] remove app privileges
                appUninstallPrivileges(app, req, uh);

                // [db] remove app
                m_privilegeDb.RemoveApplication(app.appName, req.uid, removeApp, uh.removePkg, uh.removeAuthor);

                // [cynara] update app policy
                appUninstallCynaraPolicies(SmackLabels::generateProcessLabel(app.appName, req.pkgName, uh.isPkgHybrid), req, uh);
            }
            uh.removeApps.push_back(removeApp);
        }

        // [db] commit
        trans.commit();
        LogDebug("Application uninstallation commited to database");

        // update permissible set
        updatePermissibleSet(req.uid, req.installationType);

        // remove and merge Smack rules for apps and pkg
        return appUninstallSmackRules(req, uh);
    } catch (const PrivilegeDb::Exception::IOError &e) {
        LogError("Cannot access application database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while removing application info from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PermissibleSet::PermissibleSetException::Base &e) {
        LogError("Error while updating permissible file: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeInfo::Exception::Base &e) {
        LogError("Error while getting privilege information: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const CynaraException::Base &e) {
        LogError("Error while setting Cynara rules for application: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidLabel &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation while setting Cynara rules for application: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getPkgName(const std::string &appName, std::string &pkgName)
{
    LogDebug("appName: " << appName);

    try {
        m_privilegeDb.GetAppPkgName(appName, pkgName);
        if (pkgName.empty()) {
            LogWarning("Application " << appName << " not found in database");
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        } else {
            LogDebug("pkgName: " << pkgName);
        }
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting pkgName from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::userAdd(const Credentials &creds, uid_t uidAdded, int userType)
{
    if (!authenticate(creds, PRIVILEGE_USER_ADMIN)) {
        LogError("Caller is not permitted to manage users");
        return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
    }
    try {
        m_cynaraAdmin.userInit(uidAdded, static_cast<security_manager_user_type>(userType));
        PermissibleSet::initializeUserPermissibleFile(uidAdded);
    } catch (CynaraException::InvalidParam &e) {
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const PermissibleSet::PermissibleSetException::FileInitError &e) {
        LogError("Error while adding user: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SETTING_FILE_LABEL_FAILED;
    } catch (const SmackException::FileError &e) {
        LogError("Error while adding user: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SETTING_FILE_LABEL_FAILED;
    } catch (const PrivilegeInfo::Exception::Base &e) {
        LogError("Error while getting privilege information: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::exception &e) {
        LogError("Memory allocation error while adding user: " << e.what());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::userDelete(const Credentials &creds, uid_t uidDeleted)
{
    int ret = SECURITY_MANAGER_SUCCESS;

    if (!authenticate(creds, PRIVILEGE_USER_ADMIN)) {
        LogError("Caller is not permitted to manage users");
        return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
    }

    /*Uninstall all user apps*/
    std::vector<std::string> userApps;
    try {
        m_privilegeDb.GetUserApps(uidDeleted, userApps);
        PermissibleSet::removeUserPermissibleFile(uidDeleted);
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting user apps from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PermissibleSet::PermissibleSetException::FileRemoveError &e) {
        LogError("Error while removing user: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_FILE_DELETE_FAILED;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::exception &e) {
        LogError("Memory allocation error while deleting user: " << e.what());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    // Don't check whether the caller may uninstall apps of the removed user
    Credentials credsTmp(creds);
    credsTmp.authenticated = true;
    for (const auto &app : userApps) {
        app_inst_req req;
        req.uid = uidDeleted;
        req.apps[0].appName = app;
        if (appUninstall(credsTmp, req) != SECURITY_MANAGER_SUCCESS) {
        /*if uninstallation of this app fails, just go on trying to uninstall another ones.
        we do not have anything special to do about that matter - user will be deleted anyway.*/
            ret = SECURITY_MANAGER_ERROR_SERVER_ERROR;
        }
    }

    m_cynaraAdmin.userRemove(uidDeleted);

    return ret;
}
typedef std::map<std::string, std::vector<std::string>> AppsAllowedPrivilegesMap;

void ServiceImpl::updateRunningAppSmackPolicy(
    const MountNS::AppContext &appContext,
    const std::map<std::string, std::vector<std::string>> &appsAllowedPrivileges)
{
    LogDebug("Updateing privilege Smack policy for: " << appContext.appProcessLabel);


    auto it = appsAllowedPrivileges.find(appContext.appProcessLabel);
    if (it == appsAllowedPrivileges.end()) {
        LogError("No allowed privileges set for " << appContext.appProcessLabel);
        return;
    }
    auto oldAllowedPrivs = it->second;

    std::vector<std::string> newAllowedPrivs;
    getAppAllowedPrivileges(appContext.appProcessLabel, appContext.uidStr, newAllowedPrivs);

    std::sort(oldAllowedPrivs.begin(), oldAllowedPrivs.end());
    std::sort(newAllowedPrivs.begin(), newAllowedPrivs.end());

    std::vector<std::string> denied, allowed;
    // Deny privileges which were in old allowed privs, but are not in new ones
    std::set_difference(oldAllowedPrivs.begin(), oldAllowedPrivs.end(),
                        newAllowedPrivs.begin(), newAllowedPrivs.end(),
                        std::back_inserter(denied));
    // Allow privileges which are in new allowed privs, but were not in old ones
    std::set_difference(newAllowedPrivs.begin(), newAllowedPrivs.end(),
                        oldAllowedPrivs.begin(), oldAllowedPrivs.end(),
                        std::back_inserter(allowed));

    std::string appName, pkgName;
    SmackLabels::generateAppPkgNameFromLabel(appContext.appProcessLabel, appName, pkgName);

    std::string authorHash;
    m_privilegeDb.GetPkgAuthorHash(pkgName, authorHash);

    m_smackRules.disablePrivilegeRules(appContext.appProcessLabel, pkgName, authorHash, denied);
    m_smackRules.enablePrivilegeRules(appContext.appProcessLabel, pkgName, authorHash, allowed);
}

bool isMultiUser(const MountNS::AppContext &app, const std::vector<MountNS::AppContext> &runningApps)
{
    for (auto &runningApp: runningApps) {
        if (runningApp.appProcessLabel == app.appProcessLabel && runningApp.uidStr != app.uidStr)
            return true;
    }
    return false;
}

int ServiceImpl::policyUpdate(const Credentials &creds, const std::vector<policy_entry> &policyEntries)
{
    try {
        if (policyEntries.size() == 0) {
            LogError("Validation failed: policy update request is empty");
            return SECURITY_MANAGER_ERROR_BAD_REQUEST;
        };

        std::vector<CynaraAdminPolicy> validatedPolicies;

        for (auto &entry : const_cast<std::vector<policy_entry>&>(policyEntries)) {
            CynaraAdminPolicy cyap;
            int ret = validatePolicy(creds, entry, cyap);
            if (ret != SECURITY_MANAGER_SUCCESS)
                return ret;

            validatedPolicies.push_back(std::move(cyap));
        };

        std::map<std::string, std::vector<std::string>> appsAllowedPrivileges;
        std::vector<std::string> allPackages;

        if (m_smackRules.isPrivilegeMappingEnabled()) {
            auto runningApps = MountNS::getMountNSApps();
            for (auto &appContext: runningApps) {
                auto &appProcessLabel = appContext.appProcessLabel;
                auto &uidStr = appContext.uidStr;

                getAppAllowedPrivileges(appProcessLabel, uidStr, appsAllowedPrivileges[appProcessLabel]);
            }
        }
        // Apply updates
        m_cynaraAdmin.setPolicies(validatedPolicies);

        if (m_smackRules.isPrivilegeMappingEnabled()) {
            LogDebug("Updating privilege related Smack rules");
            auto runningApps = MountNS::getMountNSApps();
            for (auto &appContext : runningApps) {
                if (isMultiUser(appContext, runningApps)) {
                    LogError("Detected multiuser launch for " << appContext.appProcessLabel
                             << ", policy won't be updated for its context.");
                } else {
                    try {
                        updateRunningAppSmackPolicy(appContext, appsAllowedPrivileges);
                    } catch (const SmackException::InvalidLabel &e) {
                        LogError("AppContext: " << appContext.appProcessLabel
                                 << " doesn't describe an application");
                    }
                }
            }
        }

        // Update mount namespaces
        // TODO: Don't update all users, apps and privileges, filter by policyEntries
        if (!m_NSMountLogic.check())
            return SECURITY_MANAGER_ERROR_MOUNT_ERROR;
    } catch (const CynaraException::Base &e) {
        LogError("Error while updating Cynara rules: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const FS::Exception::Base &e) {
        LogError("Filesystem error: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation error while updating Cynara rules: " << e.what());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getConfiguredPolicy(const Credentials &creds, bool forAdmin,
    const policy_entry &filter, std::vector<policy_entry> &policyEntries)
{
    try {
        std::string uidStr = std::to_string(creds.uid);
        std::string pidStr = std::to_string(creds.pid);

        LogDebug("Filter is: C: " << filter.appName
                    << ", U: " << filter.user
                    << ", P: " << filter.privilege
                    << ", current: " << filter.currentLevel
                    << ", max: " << filter.maxLevel);

        std::vector<CynaraAdminPolicy> listOfPolicies;

        //convert appName to smack label
        Smack::Label appProcessLabel = filter.appName.compare(SECURITY_MANAGER_ANY) ?
            getAppProcessLabel(filter.appName) : CYNARA_ADMIN_ANY;
        std::string user = filter.user.compare(SECURITY_MANAGER_ANY) ? filter.user : CYNARA_ADMIN_ANY;
        std::string privilege = filter.privilege.compare(SECURITY_MANAGER_ANY) ? filter.privilege : CYNARA_ADMIN_ANY;

        LogDebug("App: " << filter.appName << ", Label: " << appProcessLabel);

        if (forAdmin) {
            if (!authenticate(creds, PRIVILEGE_POLICY_ADMIN)
                && !authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
                LogError("Not enough privilege to access admin enforced policies");
                return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
            }

            //Fetch privileges from ADMIN bucket
            m_cynaraAdmin.listPolicies(
                CynaraAdmin::Buckets.at(Bucket::ADMIN),
                appProcessLabel,
                user,
                privilege,
                listOfPolicies);
            LogDebug("ADMIN - number of policies matched: " << listOfPolicies.size());
        } else {
            if (appProcessLabel != creds.label
                && !authenticate(creds, PRIVILEGE_POLICY_USER)
                && !authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
                LogError("Not enough privilege to access user enforced policies");
                return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
            }

            if (uidStr.compare(user)) {
                if (!authenticate(creds, PRIVILEGE_POLICY_ADMIN)
                    && !authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
                    LogWarning("Not enough privilege to access other user's personal policies");
                    return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
                };
            };
            //Fetch privileges from PRIVACY_MANAGER bucket
            m_cynaraAdmin.listPolicies(
                CynaraAdmin::Buckets.at(Bucket::PRIVACY_MANAGER),
                appProcessLabel,
                user,
                privilege,
                listOfPolicies);
            LogDebug("PRIVACY MANAGER - number of policies matched: " << listOfPolicies.size());
        };

        for (const auto &policy : listOfPolicies) {
            //ignore "jump to bucket" entries
            if (policy.result ==  CYNARA_ADMIN_BUCKET)
                continue;

            policy_entry pe;
            std::vector<std::string> appNames;
            std::string appName, pkgName;

            if (strcmp(policy.client, CYNARA_ADMIN_WILDCARD)) {
                SmackLabels::generateAppPkgNameFromLabel(policy.client, appName, pkgName);
                if (!appName.empty()) {
                    // Hybrid app
                    appNames.push_back(appName);
                } else {
                    if (filter.appName == SECURITY_MANAGER_ANY) {
                        // If user requested policy for all apps, we have to demangle pkgName to
                        // set of appNames in case of non-hybrid apps
                        m_privilegeDb.GetPkgApps(pkgName, appNames);
                    } else {
                        // If user requested policy for specific appName, we have to copy
                        // appName from filter for non-hybrid apps
                        appNames.push_back(filter.appName);
                    }
                }
            } else {
                // Cynara wildcard -> SM any
                appNames.push_back(SECURITY_MANAGER_ANY);
            }

            for (const auto &app : appNames) {
                pe.appName = app;
                pe.user =  strcmp(policy.user, CYNARA_ADMIN_WILDCARD) ? policy.user : SECURITY_MANAGER_ANY;
                pe.privilege = strcmp(policy.privilege, CYNARA_ADMIN_WILDCARD) ? policy.privilege : pe.privilege = SECURITY_MANAGER_ANY;
                pe.currentLevel = m_cynaraAdmin.convertToPolicyDescription(policy.result);

                if (!forAdmin) {
                    // All policy entries in PRIVACY_MANAGER should be fully-qualified
                    pe.maxLevel = m_cynaraAdmin.convertToPolicyDescription(
                        m_cynaraAdmin.getPrivilegeManagerMaxLevel(
                            policy.client, policy.user, policy.privilege));
                } else {
                    // Cannot reliably calculate maxLavel for policies from ADMIN bucket
                    pe.maxLevel = m_cynaraAdmin.convertToPolicyDescription(CYNARA_ADMIN_ALLOW);
                }


                LogDebug(
                    "[policy_entry] app: " << pe.appName
                    << " user: " << pe.user
                    << " privilege: " << pe.privilege
                    << " current: " << pe.currentLevel
                    << " max: " << pe.maxLevel);

                policyEntries.push_back(pe);
            }
        };

    } catch (const CynaraException::Base &e) {
        LogError("Error while listing Cynara rules: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidLabel &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation error while listing Cynara rules: " << e.what());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }


    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getPolicy(const Credentials &creds, const policy_entry &filter,
    std::vector<policy_entry> &policyEntries)
{
    try {
        std::string uidStr = std::to_string(creds.uid);
        std::string pidStr = std::to_string(creds.pid);

        if (!authenticate(creds, PRIVILEGE_POLICY_USER)
            && !authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
            LogWarning("Not enough permission to call: " << __FUNCTION__);
            return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
        };

        LogDebug("Filter is: C: " << filter.appName
                    << ", U: " << filter.user
                    << ", P: " << filter.privilege
                    << ", current: " << filter.currentLevel
                    << ", max: " << filter.maxLevel);

        std::vector<uid_t> listOfUsers;

        if (authenticate(creds, PRIVILEGE_POLICY_ADMIN)
            || authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
            LogDebug("User is privileged");
            if (filter.user.compare(SECURITY_MANAGER_ANY)) {
                LogDebug("Limitting Cynara query to user: " << filter.user);
                try {
                    listOfUsers.push_back(static_cast<uid_t>(std::stoul(filter.user)));
                } catch (std::invalid_argument &e) {
                    LogError("Invalid UID: " << e.what());
                };
            } else {
                m_cynaraAdmin.listUsers(listOfUsers);
            }
        } else {
            LogWarning("Not enough privilege to fetch user policy for all users by user: " << creds.uid);
            LogDebug("Fetching personal policy for user: " << creds.uid);
            listOfUsers.push_back(creds.uid);
        };
        LogDebug("Fetching policy for " << listOfUsers.size() << " users");

        for (const uid_t &user : listOfUsers) {
            LogDebug("User: " << user);
            std::string userStr = std::to_string(user);
            std::vector<std::string> listOfApps;

            if (filter.appName.compare(SECURITY_MANAGER_ANY)) {
                LogDebug("Limitting Cynara query to app: " << filter.appName);
                listOfApps.push_back(filter.appName);
            } else {
                m_privilegeDb.GetUserApps(user, listOfApps);
                LogDebug("Found apps: " << listOfApps.size());
            };

            for (const std::string &appName : listOfApps) {
                LogDebug("App: " << appName);
                std::string appProcessLabel = getAppProcessLabel(appName);
                std::vector<std::string> listOfPrivileges;

                m_cynaraAdmin.getAppPolicy(appProcessLabel, userStr, listOfPrivileges);
                m_cynaraAdmin.getAppPolicy(appProcessLabel, CYNARA_ADMIN_WILDCARD, listOfPrivileges);

                if (filter.privilege.compare(SECURITY_MANAGER_ANY)) {
                    LogDebug("Limitting Cynara query to privilege: " << filter.privilege);
                    // FIXME: this filtering should be already performed by method fetching the privileges
                    if (std::find(listOfPrivileges.begin(), listOfPrivileges.end(),
                        filter.privilege) == listOfPrivileges.end()) {
                        LogDebug("Application " << appName <<
                            " doesn't have the filteres privilege " << filter.privilege);
                        continue;
                    }
                    listOfPrivileges.clear();
                    listOfPrivileges.push_back(filter.privilege);
                }

                LogDebug("Privileges matching filter - " << filter.privilege << ": " << listOfPrivileges.size());

                for (const std::string &privilege : listOfPrivileges) {
                    LogDebug("Privilege: " << privilege);
                    policy_entry pe;

                    pe.appName = appName;
                    pe.user = userStr;
                    pe.privilege = privilege;

                    pe.currentLevel = m_cynaraAdmin.convertToPolicyDescription(
                        m_cynaraAdmin.getPrivilegeManagerCurrLevel(
                            appProcessLabel, userStr, privilege));

                    pe.maxLevel = m_cynaraAdmin.convertToPolicyDescription(
                        m_cynaraAdmin.getPrivilegeManagerMaxLevel(
                            appProcessLabel, userStr, privilege));

                    LogDebug(
                        "[policy_entry] app: " << pe.appName
                        << " user: " << pe.user
                        << " privilege: " << pe.privilege
                        << " current: " << pe.currentLevel
                        << " max: " << pe.maxLevel);

                    policyEntries.push_back(pe);
                };
            };
        };

    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting application privileges from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const CynaraException::Base &e) {
        LogError("Error while listing Cynara rules: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidLabel &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation error while listing Cynara rules: " << e.what());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::policyGetDesc(std::vector<std::string> &levels)
{
    int ret = SECURITY_MANAGER_SUCCESS;

    try {
        m_cynaraAdmin.listPoliciesDescriptions(levels);
    } catch (const CynaraException::OutOfMemory &e) {
        LogError("Error - out of memory while querying Cynara for policy descriptions list: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const CynaraException::InvalidParam &e) {
        LogError("Error - invalid parameter while querying Cynara for policy descriptions list: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_INPUT_PARAM;
    } catch (const CynaraException::ServiceNotAvailable &e) {
        LogError("Error - service not available while querying Cynara for policy descriptions list: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_NO_SUCH_SERVICE;
    } catch (const CynaraException::Base &e) {
        LogError("Error while getting policy descriptions list from Cynara: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return ret;
}
int ServiceImpl::getAppAllowedPrivileges(const Smack::Label &appProcessLabel,
    uid_t uid, std::vector<std::string> &allowedPrivileges)

{
    return getAppAllowedPrivileges(appProcessLabel, std::to_string(uid), allowedPrivileges);
}

int ServiceImpl::getAppAllowedPrivileges(const Smack::Label &appProcessLabel,
    const std::string &uid, std::vector<std::string> &allowedPrivileges)
{
    try {
        LogDebug("Getting allowed privileges for " << appProcessLabel << " and user " << uid);

        std::vector<std::string> privileges;
        m_cynaraAdmin.getAppPolicy(appProcessLabel, uid, privileges);
        m_cynaraAdmin.getAppPolicy(appProcessLabel, CYNARA_ADMIN_WILDCARD, privileges);
        m_cynaraAdmin.getAppPolicy(CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_WILDCARD, privileges);

        vectorRemoveDuplicates(privileges);
        for (auto &privilege : privileges) {
            int result = CYNARA_ADMIN_DENY;
            std::string resultExtra;
            m_cynaraAdmin.check(appProcessLabel, uid, privilege, CynaraAdmin::Buckets[Bucket::PRIVACY_MANAGER], result, resultExtra, true);
            if (result == CYNARA_ADMIN_ALLOW) {
                LogDebug("Application " << appProcessLabel << " has " << privilege << " allowed");
                allowedPrivileges.push_back(privilege);
            }
        }
    } catch (const CynaraException::Base &e) {
        LogError("Error while querying Cynara for permissions: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getForbiddenAndAllowedGroups(
    const Smack::Label &appProcessLabel, const std::vector<std::string> &allowedPrivileges,
    std::vector<gid_t> &forbiddenGroups, std::vector<gid_t> &allowedGroups)
{

    try {
        LogDebug("smack label: " << appProcessLabel);

        for (const auto &privilege : allowedPrivileges) {
            const auto &pgids = m_privilegeGids.getGids(privilege);

            LogDebug("Using privilege " << privilege << " with " <<
                     pgids.size() << " groups assigned");

            if (pgids.empty())
                continue;

            allowedGroups.insert(allowedGroups.end(), pgids.begin(), pgids.end());

        }
        vectorRemoveDuplicates(allowedGroups); // sorted

        auto &gids = m_privilegeGids.getGids(); // sorted
        forbiddenGroups.reserve(gids.size());
        std::set_difference(gids.begin(), gids.end(), allowedGroups.begin(), allowedGroups.end(),
                std::back_inserter(forbiddenGroups)); // sorted
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::policyGroupsForUid(uid_t uid, std::vector<gid_t> &groups)
{
    int ret = SECURITY_MANAGER_SUCCESS;

    try {
        auto userType = m_cynaraAdmin.getUserType(uid);

        if (userType == SM_USER_TYPE_NONE) {
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }

        auto uidStr = std::to_string(uid);
        int result;
        std::string resultExtra;
        std::string bucket;

        switch (userType) {
            case SM_USER_TYPE_NORMAL:
                bucket = CynaraAdmin::Buckets.at(Bucket::USER_TYPE_NORMAL);
                break;
            case SM_USER_TYPE_ADMIN:
                bucket = CynaraAdmin::Buckets.at(Bucket::USER_TYPE_ADMIN);
                break;
            case SM_USER_TYPE_GUEST:
                bucket = CynaraAdmin::Buckets.at(Bucket::USER_TYPE_GUEST);
                break;
            case SM_USER_TYPE_SYSTEM:
                bucket = CynaraAdmin::Buckets.at(Bucket::USER_TYPE_SYSTEM);
                break;
            default:
                // Improperly configured
                return SECURITY_MANAGER_ERROR_UNKNOWN;
        }

        auto &privs = m_privilegeGids.getPrivileges();
        for (auto &p : privs) {
            m_cynaraAdmin.check(CYNARA_ADMIN_ANY, uidStr, p, bucket, result,
                                resultExtra, true);
            if (result == CYNARA_ADMIN_ALLOW) {
                auto &gids = m_privilegeGids.getGids(p);
                groups.insert(groups.end(), gids.begin(), gids.end());
            }
        }
        vectorRemoveDuplicates(groups);
    } catch (const CynaraException::Base &e) {
        LogError("Error while getting user type from Cynara: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting groups from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return ret;
}

int ServiceImpl::appHasPrivilege(
        const Credentials &creds,
        const std::string appName,
        const std::string privilege,
        uid_t uid,
        bool &result)
{
    try {
        Smack::Label appProcessLabel = getAppProcessLabel(appName);
        if ((appProcessLabel != creds.label || creds.uid != uid)
            && !authenticate(creds, PRIVILEGE_POLICY_USER)
            && !authenticate(creds, PRIVILEGE_PERMISSION_CHECK)) {
            LogError("Not enough privilege to access other process policies");
            return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
        }
        std::string uidStr = std::to_string(uid);
        result = m_cynara.check(appProcessLabel, privilege, uidStr, "");
        LogDebug("result = " << result);
    } catch (const CynaraException::Base &e) {
        LogError("Error while querying Cynara for permissions: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidLabel &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    } catch (...) {
        LogError("Unknown exception thrown");
        return SECURITY_MANAGER_ERROR_UNKNOWN;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::dropOnePrivateSharing(
        const std::string &ownerAppName,
        const std::string &ownerPkgName,
        const Smack::Labels &ownerPkgLabels,
        const std::string &targetAppName,
        const Smack::Label &targetAppLabel,
        const std::string &path)
{
    int errorRet;
    try {
        int targetPathCount, pathCount, ownerTargetCount;
        m_privilegeDb.DropPrivateSharing(ownerAppName, targetAppName, path);
        m_privilegeDb.GetTargetPathSharingCount(targetAppName, path, targetPathCount);
        m_privilegeDb.GetPathSharingCount(path, pathCount);
        m_privilegeDb.GetOwnerTargetSharingCount(ownerAppName, targetAppName, ownerTargetCount);
        if (targetPathCount > 0) {
            return SECURITY_MANAGER_SUCCESS;
        }
        //This function can be also called when application is uninstalled, so path won't exist
        if (pathCount < 1 && FS::fileExists(path)) {
            SmackLabels::setupPath(ownerPkgName, path, SECURITY_MANAGER_PATH_RW);
        }
        Smack::Label pathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
        m_smackRules.dropPrivateSharingRules(ownerPkgName, ownerPkgLabels, targetAppLabel,
                                           pathLabel, pathCount < 1, ownerTargetCount < 1);
        return SECURITY_MANAGER_SUCCESS;
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while dropping private sharing in database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::Base &e) {
        LogError("Error performing smack operation: " << e.GetMessage());
        errorRet = SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        errorRet = SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const std::exception &e) {
        LogError("Some exception thrown : " << e.what());
        errorRet = SECURITY_MANAGER_ERROR_UNKNOWN;
    } catch (...) {
        LogError("Unknown exception thrown");
        errorRet = SECURITY_MANAGER_ERROR_UNKNOWN;
    }
    return errorRet;
}

int ServiceImpl::applyPrivatePathSharing(
        const Credentials &creds,
        const std::string &ownerAppName,
        const std::string &targetAppName,
        const std::vector<std::string> &paths)
{
    int errorRet;
    int sharingAdded = 0;
    std::string ownerPkgName;
    std::string targetPkgName;
    Smack::Label targetAppLabel;
    Smack::Labels pkgsLabels;

    try {
        if (!authenticate(creds, PRIVILEGE_APPSHARING_ADMIN)) {
            LogError("Caller is not permitted to manage file sharing");
            return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
        }

        m_privilegeDb.GetAppPkgName(ownerAppName, ownerPkgName);
        if (ownerPkgName.empty()) {
            LogError(ownerAppName << " is not an installed application");
            return SECURITY_MANAGER_ERROR_APP_UNKNOWN;
        }

        m_privilegeDb.GetAppPkgName(targetAppName, targetPkgName);
        if (targetPkgName.empty()) {
            LogError(targetAppName << " is not an installed application");
            return SECURITY_MANAGER_ERROR_APP_UNKNOWN;
        }

        for (const auto &path : paths) {
            std::string pathLabel = SmackLabels::getSmackLabelFromPath(path);
            if (pathLabel != SmackLabels::generatePathRWLabel(ownerPkgName)) {
                Smack::Label generatedPathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
                if (generatedPathLabel != pathLabel) {
                    LogError("Path " << path << " has label " << pathLabel << " and dosen't belong"
                             " to application " << ownerAppName);
                    return SECURITY_MANAGER_ERROR_APP_NOT_PATH_OWNER;
                }
            }
        }
        if (ownerAppName == targetAppName) {
            LogDebug("Owner application is the same as target application");
            return SECURITY_MANAGER_SUCCESS;
        }

        if (ownerPkgName == targetPkgName) {
            LogDebug("Owner and target belong to the same package");
            return SECURITY_MANAGER_SUCCESS;
        }
        targetAppLabel = getAppProcessLabel(targetAppName);
        getPkgLabels(ownerPkgName, pkgsLabels);

        ScopedTransaction trans(m_privilegeDb);
        for (const auto &path : paths) {
            int targetPathCount, pathCount, ownerTargetCount;
            m_privilegeDb.GetTargetPathSharingCount(targetAppName, path, targetPathCount);
            m_privilegeDb.GetPathSharingCount(path, pathCount);
            m_privilegeDb.GetOwnerTargetSharingCount(ownerAppName, targetAppName, ownerTargetCount);
            Smack::Label pathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
            m_privilegeDb.ApplyPrivateSharing(ownerAppName, targetAppName, path, pathLabel);
            sharingAdded++;
            if (targetPathCount > 0) {
                //Nothing to do, only counter needed incrementing
                continue;
            }
            m_smackRules.applyPrivateSharingRules(ownerPkgName, pkgsLabels,
                                                targetAppLabel, pathLabel,
                                                (pathCount > 0),
                                                (ownerTargetCount > 0));
            if (pathCount <= 0) {
                SmackLabels::setupSharedPrivatePath(ownerPkgName, path);
            }
        }
        trans.commit();
        return SECURITY_MANAGER_SUCCESS;
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while applying private sharing in database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::Base &e) {
        LogError("Error performing smack operation: " << e.GetMessage());
        errorRet = SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        errorRet = SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const std::exception &e) {
        LogError("Some exception thrown : " << e.what());
        errorRet = SECURITY_MANAGER_ERROR_UNKNOWN;
    } catch (...) {
        LogError("Unknown exception thrown");
        errorRet = SECURITY_MANAGER_ERROR_UNKNOWN;
    }

    for (int i = 0; i < sharingAdded; i++) {
        const std::string &path = paths[i];
        dropOnePrivateSharing(ownerAppName, ownerPkgName, pkgsLabels,
                              targetAppName, targetAppLabel, path);
    }

    return errorRet;
}

int ServiceImpl::dropPrivatePathSharing(
        const Credentials &creds,
        const std::string &ownerAppName,
        const std::string &targetAppName,
        const std::vector<std::string> &paths)
{
    int errorRet;
    try {
        if (!authenticate(creds, PRIVILEGE_APPSHARING_ADMIN)) {
            LogError("Caller is not permitted to manage file sharing");
            return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
        }

        std::string ownerPkgName;
        m_privilegeDb.GetAppPkgName(ownerAppName, ownerPkgName);
        if (ownerPkgName.empty()) {
            LogError(ownerAppName << " is not an installed application");
            return SECURITY_MANAGER_ERROR_APP_UNKNOWN;
        }

        std::string targetPkgName;
        m_privilegeDb.GetAppPkgName(targetAppName, targetPkgName);
        if (targetPkgName.empty()) {
            LogError(targetAppName << " is not an installed application");
            return SECURITY_MANAGER_ERROR_APP_UNKNOWN;
        }

        for (const auto &path : paths) {
            if (!sharingExists(targetAppName, path)) {
                LogError("Sharing doesn't exist: owner=" << ownerAppName
                         << ", target=" << targetAppName << ", path=" << path);
                return SECURITY_MANAGER_ERROR_INPUT_PARAM;
            }
            Smack::Label pathLabel = SmackLabels::getSmackLabelFromPath(path);
            if (pathLabel != SmackLabels::generatePathRWLabel(ownerPkgName)) {
                Smack::Label generatedPathLabel = SmackLabels::generateSharedPrivateLabel(ownerPkgName, path);
                if (generatedPathLabel != pathLabel) {
                    LogError("Path " << path << " has label " << pathLabel << " and dosen't belong"
                             " to application " << ownerAppName);
                    return SECURITY_MANAGER_ERROR_APP_NOT_PATH_OWNER;
                }
            }
        }

        if (ownerAppName == targetAppName) {
            LogDebug("Owner application is the same as target application");
            return SECURITY_MANAGER_SUCCESS;
        }

        if (ownerPkgName == targetPkgName) {
            LogDebug("Owner and target belong to the same package");
            return SECURITY_MANAGER_SUCCESS;
        }

        Smack::Labels pkgLabels;
        getPkgLabels(ownerPkgName, pkgLabels);
        auto targetAppLabel = getAppProcessLabel(targetAppName, targetPkgName);

        ScopedTransaction trans(m_privilegeDb);
        for (const auto &path : paths) {
            int ret = dropOnePrivateSharing(ownerAppName, ownerPkgName, pkgLabels,
                                            targetAppName, targetAppLabel, path);
            if (ret != SECURITY_MANAGER_SUCCESS) {
                return ret;
            }
        }
        trans.commit();
        return SECURITY_MANAGER_SUCCESS;
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while dropping private sharing in database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::Base &e) {
        LogError("Error performing smack operation: " << e.GetMessage());
        errorRet = SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        errorRet = SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const std::exception &e) {
        LogError("Some exception thrown : " << e.what());
        errorRet = SECURITY_MANAGER_ERROR_UNKNOWN;
    } catch (...) {
        LogError("Unknown exception thrown");
        errorRet = SECURITY_MANAGER_ERROR_UNKNOWN;
    }

    return errorRet;
}

int ServiceImpl::pathsRegister(const Credentials &creds, path_req req)
{
    LogDebug("Paths registration parameters: pkgName: " << req.pkgName <<
             ", uid: " << req.uid);

    if (req.pkgPaths.empty())
        return SECURITY_MANAGER_SUCCESS;

    try {
        setRequestDefaultValues(req.uid, req.installationType);

        if (!authCheck(creds, req.uid, req.installationType)) {
            LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label <<
                " for path registration denied");
            return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
        }
    } catch (const CynaraException::Base &e) {
        LogError("Error while querying Cynara for permissions: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }

    bool isRequestSharedRO = isSharedRO(req.pkgPaths);
    try {
        if (isRequestSharedRO) {
            ScopedTransaction trans(m_privilegeDb);

            m_privilegeDb.SetSharedROPackage(req.pkgName);

            trans.commit();
        }
    } catch (const PrivilegeDb::Exception::IOError &e) {
        LogError("Cannot access application database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const PrivilegeDb::Exception::InternalError &e) {
        LogError("Error while saving application info to database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return labelPaths(req.pkgPaths,
                      req.pkgName,
                      static_cast<app_install_type>(req.installationType),
                      req.uid,
                      isRequestSharedRO);
}

int ServiceImpl::shmAppName(const Credentials &creds, const std::string &shmName, const std::string &appName)
{
    try {
        if (shmName.empty() || appName.empty())
            return SECURITY_MANAGER_ERROR_INPUT_PARAM;

        if (!m_privilegeDb.AppNameExists(appName)) {
            LogError("Unknown application id: " << appName);
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }

        if (!authenticate(creds, PRIVILEGE_SHM)) {
            LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label << " for shm denied");
            return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
        }

        Smack::Label label = getAppProcessLabel(appName);

        int fd = shm_open(shmName.c_str(), O_RDWR, 0);
        if (fd < 0) {
            LogError("Error in shm_open");
            return SECURITY_MANAGER_ERROR_INPUT_PARAM;
        }

        auto scopeClose = makeUnique(&fd, [](int *ptr) -> void { if (*ptr >= 0) close(*ptr);});

        Credentials fdCreds = Credentials::getCredentialsFromFd(fd);

        if (fdCreds.label == label) {
            // Nothing to do. The file already has proper label.
            // Client called this function twice?
            LogDebug("Noting to do. File have already label: " << label << " The client probably called this api twice.");
            return SECURITY_MANAGER_SUCCESS;
        }

        if ((creds.label != fdCreds.label) || (creds.uid != fdCreds.uid)) {
            LogDebug("Client (smack: " << creds.label <<", pid: " << creds.pid
                << ") does not have permission to access shared memory file (segment name: "
                << shmName << ").");
            return SECURITY_MANAGER_ERROR_ACCESS_DENIED;
        }

        SmackLabels::setSmackLabelForFd(fd, label);
    } catch (const CynaraException::Base &e) {
        LogError("Error while querying Cynara for permissions: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::Base &e) {
        LogError("Error while set/get smack label in /dev/shm: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const TizenPlatformConfig::Exception::Base &e) {
        LogError("Error while reading configuration: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getAppDefinedPrivilegeDescription(
        uid_t uid,
        const std::string &privilege,
        std::string &appName,
        std::string &pkgName,
        std::string &license)
{
    try {
        // Local provider have priority. Search for local provider.
        if (m_privilegeDb.GetAppPkgLicenseForAppDefinedPrivilege(uid, privilege, appName, pkgName, license))
        {
            // We found local provider. We may return it.
            return SECURITY_MANAGER_SUCCESS;
        }

        // Local provider not found. Search for global provider.
        std::string localAppName, localPkgName, localLicense;
        if (!m_privilegeDb.GetAppPkgLicenseForAppDefinedPrivilege(getGlobalUserId(), privilege, localAppName, localPkgName, localLicense))
        {
            LogDebug("Privilege " << privilege << " not found in database");
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }

        // Global provider found. Check if it's not hidden by local installation of application with same pkgName.
        if (m_privilegeDb.IsUserPkgInstalled(localPkgName, uid))
        {
            // Ups. There is local installation of application with the same pkgId (it does not provide privilege).
            // Global provider could not be used!
            LogDebug("Local installation hiddes global one. Local installation of pkg: " << localPkgName << " does not support: " << privilege);
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }

        // Return result
        appName = std::move(localAppName);
        pkgName = std::move(localPkgName);
        license = std::move(localLicense);
    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting appName or pkgName from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getAppDefinedPrivilegeProvider(
        uid_t uid,
        const std::string &privilege,
        std::string &appName,
        std::string &pkgName)
{
    std::string localLicense;
    return getAppDefinedPrivilegeDescription(uid, privilege, appName, pkgName, localLicense);
}

int ServiceImpl::getAppDefinedPrivilegeLicense(
        uid_t uid,
        const std::string &privilege,
        std::string &license)
{
    std::string localAppName, localPkgName, localLicense;
    int ret = getAppDefinedPrivilegeDescription(uid, privilege, localAppName, localPkgName, localLicense);

    if (ret != SECURITY_MANAGER_SUCCESS) {
        return ret;
    }

    if (localLicense.empty()) {
        return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
    }

    license = std::move(localLicense);
    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getClientPrivilegeLicense(
        const std::string &appName,
        const std::string &pkgName,
        uid_t uid,
        const std::string &privilege,
        std::string &license)
{
    try {
        std::string licenseString;
        uid_t requestUid = m_privilegeDb.IsUserPkgInstalled(pkgName, uid) ? uid : getGlobalUserId();

        if (m_privilegeDb.IsPackageHybrid(pkgName)) {
            if (appName.empty()) {
                LogDebug("appName could not be empty if you ask about hybrid application");
                return SECURITY_MANAGER_ERROR_INPUT_PARAM;
            }

            if (!m_privilegeDb.GetLicenseForClientPrivilegeAndApp(appName, requestUid, privilege, licenseString)) {
                LogDebug("License was not found for privilege: " << privilege << " appId: " << appName << " and uid: " << requestUid);
                return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
            }
        } else if (!m_privilegeDb.GetLicenseForClientPrivilegeAndPkg(pkgName, requestUid, privilege, licenseString)) {
            LogDebug("License was not found for privilege: " << privilege << " pkgId: " << pkgName << " and uid: " << requestUid);
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }

        license = std::move(licenseString);

    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting license for app: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::appSetupNamespace(const Credentials &creds, const std::string &appProcessLabel,
        const std::vector<std::string> &privPathsVector, std::vector<bool> &privPathsStatusVector)
{
    int ret;
    if (!authenticate(creds, PRIVILEGE_APP_NAMESPACE)) {
        LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label << " for setup app namespace denied");
        return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
    }

    try {
        const std::string uidStr = std::to_string(creds.uid);
        const std::string appsDir = MountNS::getUserAppsMountPointsPath(creds.uid);
        const std::string appDir =  MountNS::getUserAppMountPointPath(creds.uid, appProcessLabel);
        const std::string appFile = MountNS::getUserAppServiceMountPointPath(creds.uid, appProcessLabel, creds.pid);
        const std::string procFile = "/proc/" + std::to_string(creds.pid) + "/ns/mnt";

        if (FS::directoryStatus(appsDir) == 0) { // directory does not exist
            ret = FS::createDirectory(appsDir);
            if (ret != SECURITY_MANAGER_SUCCESS)
                return ret;
        }

        if (FS::directoryStatus(appDir) == 0) { // directory does not exist
            ret = FS::createDirectory(appDir);
            if (ret != SECURITY_MANAGER_SUCCESS)
                return ret;
        }

        if (FS::fileStatus(appFile) != 0) { // file exists
            ret = FS::removeFile(appFile);
            if (ret != SECURITY_MANAGER_SUCCESS)
                return ret;
        }

        ret = FS::symLink(procFile, appFile);
        if (ret != SECURITY_MANAGER_SUCCESS) {
            FS::removeFile(appFile);
            return ret;
        }

        privPathsStatusVector.reserve(privPathsVector.size());
        for (auto &privilege : privPathsVector)
            privPathsStatusVector.push_back(m_cynara.check(appProcessLabel, privilege, uidStr, {}));

    } catch (const PrivilegeDb::Exception::Base &e) {
        LogError("Error while getting shared_ro flag from database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const CynaraException::Base &e) {
        LogError("Error while querying Cynara for permissions: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const SmackException::InvalidLabel &e) {
        LogError("Error while generating Smack labels: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    } catch (...) {
        LogError("Unknown exception thrown");
        return SECURITY_MANAGER_ERROR_UNKNOWN;
    }
    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::getAppManifestPolicy(const Credentials &creds, const std::string &appName,
                                      uid_t uid, std::vector<std::string> &privileges)
{
    try {
        std::string pkgName;
        m_privilegeDb.GetAppPkgName(appName, pkgName);

        if (pkgName.empty()) {
            LogError("Checking manifest policy for unknown application: " << appName);
            return SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT;
        }

        std::string cynaraClient = getAppProcessLabel(appName);
        std::string uidStr = m_privilegeDb.IsUserPkgInstalled(pkgName, uid) ? std::to_string(uid) : CYNARA_ADMIN_WILDCARD;

        // Allow application to check the manifest
        if (((creds.label != cynaraClient)
             || (uidStr != CYNARA_ADMIN_WILDCARD && uidStr != std::to_string(creds.uid)))
            && !(authenticate(creds, PRIVILEGE_USER_ADMIN) || authenticate(creds, PRIVILEGE_PERMISSION_CHECK)))
        {
            LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label << " for checking app manifest policy denied");
            return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
        }

        m_cynaraAdmin.getAppPolicy(cynaraClient, uidStr, privileges);
    } catch (const CynaraException::Base &e) {
        LogError("Error while querying Cynara: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (const std::bad_alloc &e) {
        LogError("Memory allocation failed: " << e.what());
        return SECURITY_MANAGER_ERROR_MEMORY;
    } catch (const PrivilegeDb::Exception::IOError &e) {
        LogError("Cannot access application database: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    } catch (...) {
        LogError("Unknown exception thrown");
        return SECURITY_MANAGER_ERROR_UNKNOWN;
    }

    return SECURITY_MANAGER_SUCCESS;
}

int ServiceImpl::appCleanNamespace(const Credentials &creds, const std::string &appName, uid_t uid, pid_t pid)
{
    if (!authenticate(creds, PRIVILEGE_APP_NAMESPACE)) {
        LogError("Request from uid=" << creds.uid << ", Smack=" << creds.label <<
                 " for cleanup app namespace denied");
        return SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED;
    }

    const std::string appProcessLabel = getAppProcessLabel(appName);
    const std::string appDir =  MountNS::getUserAppMountPointPath(uid, appProcessLabel);
    const std::string appFile = MountNS::getUserAppServiceMountPointPath(uid, appProcessLabel, pid);

    int ret = FS::removeFile(appFile);

    auto pids = FS::getLinksFromDirectory(appDir);
    if (pids.empty())
        ret = FS::removeDirectory(appDir);

    return ret;
}

Smack::Label ServiceImpl::getProcessLabel(const std::string &appName)
{
    LogDebug("Requested fetching label of process for application " << appName);
    return getAppProcessLabel(appName);
}

int ServiceImpl::prepareApp(const Credentials &creds, const std::string &appName, const std::vector<std::string> &privPathsVector,
        Smack::Label &label, std::string &pkgName, PrepareAppFlags &prepareAppFlags,
        std::vector<gid_t> &forbiddenGroups, std::vector<gid_t> &allowedGroups, std::vector<bool> &privPathsStatusVector)
{
    try {
        LogDebug("Requested prepareApp for application " << appName);

        bool isHybrid, enabledSharedRO;
        if (!m_privilegeDb.GetAppPkgInfo(appName, pkgName, isHybrid, enabledSharedRO))
            return SECURITY_MANAGER_ERROR_UNKNOWN;
        prepareAppFlags = m_prepareAppFlags | (enabledSharedRO ? PREPARE_APP_SHARED_RO_FLAG : 0);
        label = SmackLabels::generateProcessLabel(appName, pkgName, isHybrid);

        std::vector<std::string> allowedPrivileges;
        int ret = getAppAllowedPrivileges(label, creds.uid, allowedPrivileges);
        if (ret != SECURITY_MANAGER_SUCCESS) {
            LogError("Failed to fetch allowed privileges for " << label);
            return ret;
        }

        std::string authorHash;
        m_privilegeDb.GetPkgAuthorHash(pkgName, authorHash);

        std::vector<std::string> pkgLabels;
        getPkgLabels(pkgName, pkgLabels);

        if (m_smackRules.isPrivilegeMappingEnabled()) {
            // We have to remove all possible privilege related Smack rules, because application
            // policy might have changed from last prepareApp
            // (e.g. application new version was installed)
            m_smackRules.disableAllPrivilegeRules(label, pkgName, authorHash);

            // TODO: Optimization is welcomed here
            auto runningApps = MountNS::getMountNSApps();
            if (isMultiUser({label, std::to_string(creds.uid)}, runningApps)) {
                LogWarning("Detected multiuser instance of " << appName
                        << ". Privilege related Smack rules are cleared and won't be reapplied.");
            } else {
                m_smackRules.enablePrivilegeRules(label, pkgName, authorHash, allowedPrivileges);
            }
        }

        ret = getForbiddenAndAllowedGroups(label, allowedPrivileges, forbiddenGroups,
                                        allowedGroups);
        return ret != SECURITY_MANAGER_SUCCESS ? ret
            : appSetupNamespace(creds, label, privPathsVector, privPathsStatusVector);
    } catch (const FS::Exception::Base &e) {
        LogError("Filesystem error: " << e.DumpToString());
        return SECURITY_MANAGER_ERROR_SERVER_ERROR;
    }
}

} /* namespace SecurityManager */