Fix security_manager_14_privacy_manager_fetch_and_update_policy_for_admin
[platform/core/test/security-tests.git] / src / security-manager-tests / security_manager_tests.cpp
1
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <memory.h>
5 #include <unistd.h>
6
7 #include <attr/xattr.h>
8 #include <linux/xattr.h>
9 #include <sys/capability.h>
10 #include <sys/socket.h>
11 #include <sys/types.h>
12 #include <sys/un.h>
13 #include <sys/wait.h>
14 #include <sys/smack.h>
15
16 #include <algorithm>
17 #include <fstream>
18 #include <regex>
19 #include <string>
20 #include <unordered_set>
21
22 #include <ftw.h>
23 #include <grp.h>
24 #include <pwd.h>
25
26 #include <tzplatform_config.h>
27 #include <security-manager.h>
28
29 #include <access_provider.h>
30 #include <dpl/log/log.h>
31 #include <dpl/test/test_runner.h>
32 #include <passwd_access.h>
33 #include <tests_common.h>
34 #include <sm_api.h>
35 #include <sm_db.h>
36 #include <sm_request.h>
37 #include <sm_sharing_request.h>
38 #include <sm_user_request.h>
39 #include <app_install_helper.h>
40 #include <synchronization_pipe.h>
41 #include <temp_test_user.h>
42 #include <uds.h>
43 #include <cynara_test_client.h>
44 #include <cynara_test_admin.h>
45 #include <service_manager.h>
46 #include <cynara_test_admin.h>
47 #include "memory.h"
48
49 using namespace SecurityManagerTest;
50
51 DEFINE_SMARTPTR(cap_free, _cap_struct, CapsSetsUniquePtr);
52 DEFINE_SMARTPTR(tzplatform_context_destroy, tzplatform_context, TzPlatformContextPtr);
53
54 static const privileges_t SM_ALLOWED_PRIVILEGES = {
55     "http://tizen.org/privilege/location",
56     "http://tizen.org/privilege/nfc"
57 };
58
59 static const privileges_t SM_DENIED_PRIVILEGES  = {
60     "http://tizen.org/privilege/bluetooth",
61     "http://tizen.org/privilege/power"
62 };
63
64 static const privileges_t SM_NO_PRIVILEGES  = {
65 };
66
67 static const std::vector<std::string> SM_ALLOWED_GROUPS = {"db_browser", "db_alarm"};
68
69 void changeSecurityContext(const std::string& label, uid_t uid, gid_t gid)
70 {
71     RUNNER_ASSERT_ERRNO_MSG(0 == smack_set_label_for_self(label.c_str()),
72         "Error in smack_set_label_for_self(" << label << ")");
73
74     RUNNER_ASSERT_ERRNO_MSG(0 == setgid(gid), "Error in setgid.");
75     RUNNER_ASSERT_ERRNO_MSG(0 == setuid(uid), "Error in setuid.");
76 }
77
78 std::string genPath(int app_num, const char *postfix) {
79     char buf[16];
80     sprintf(buf, "%02d", app_num);
81     return std::string("/opt/usr/apps/sm_test_") + std::string(buf) + std::string("_pkg_id_full/") + std::string(postfix);
82 }
83 std::string genRWPath(int app_num) {
84     return genPath(app_num, "app_dir");
85 }
86 std::string genROPath(int app_num) {
87     return genPath(app_num, "app_dir_ro");
88 }
89 std::string genPublicROPath(int app_num) {
90     return genPath(app_num, "app_dir_public_ro");
91 }
92 std::string genOwnerRWOthersROPath(int app_num) {
93     return genPath(app_num, "app_dir_rw_others_ro");
94 }
95
96 static const char *const SM_RW_PATH = "/opt/usr/apps/sm_test_02_pkg_id_full/app_dir";
97
98 static const char *const SM_DENIED_PATH = "/opt/usr/apps/non_app_dir";
99 static const char *const SM_TRUSTED_PATH = "/opt/usr/apps/sm_test_02_pkg_id_full/app_dir_trusted";
100
101 static const char *const ANY_USER_REPRESENTATION = "anyuser";/*this may be actually any string*/
102 static const std::string EXEC_FILE("exec");
103 static const std::string NORMAL_FILE("normal");
104 static const std::string LINK_PREFIX("link_to_");
105
106 static const std::string PRIVILEGE_MANAGER_APP = "privilege_manager";
107 static const std::string PRIVILEGE_MANAGER_PKG = "privilege_manager";
108 static const std::string PRIVILEGE_MANAGER_SELF_PRIVILEGE = "http://tizen.org/privilege/notexist";
109 static const std::string PRIVILEGE_MANAGER_ADMIN_PRIVILEGE = "http://tizen.org/privilege/internal/usermanagement";
110
111 static const std::vector<std::string> MANY_APPS = {
112     "security_manager_10_app_1",
113     "security_manager_10_app_2",
114     "security_manager_10_app_3",
115     "security_manager_10_app_4",
116     "security_manager_10_app_5"
117 };
118
119 struct app_attributes {
120     std::string package;
121     std::string Tizen_ver;
122 };
123 static const std::map<std::string, struct app_attributes> MANY_APPS_PKGS = {
124     {"security_manager_10_app_1", {"security_manager_10_pkg_1", "2.1"}},
125     {"security_manager_10_app_2", {"security_manager_10_pkg_2", "3.0"}},
126     {"security_manager_10_app_3", {"security_manager_10_pkg_3", "2.1.1"}},
127     {"security_manager_10_app_4", {"security_manager_10_pkg_4", "3.1"}},
128     {"security_manager_10_app_5", {"security_manager_10_pkg_5", "2.2"}},
129     {PRIVILEGE_MANAGER_APP, {PRIVILEGE_MANAGER_PKG, "3.0"}}
130 };
131
132 static const std::vector<privileges_t> MANY_APPS_PRIVILEGES = {
133     {
134         "http://tizen.org/privilege/internet",
135         "http://tizen.org/privilege/location"
136     },
137     {
138         "http://tizen.org/privilege/telephony",
139         "http://tizen.org/privilege/camera"
140     },
141     {
142         "http://tizen.org/privilege/contact.read",
143         "http://tizen.org/privilege/led",
144         "http://tizen.org/privilege/email"
145     },
146     {
147         "http://tizen.org/privilege/led",
148         "http://tizen.org/privilege/email",
149         "http://tizen.org/privilege/telephony",
150         "http://tizen.org/privilege/camera"
151     },
152     {
153         "http://tizen.org/privilege/internet",
154         "http://tizen.org/privilege/location",
155         "http://tizen.org/privilege/led",
156         "http://tizen.org/privilege/email"
157     }
158 };
159
160 class ScopedProcessLabel {
161 public:
162     ScopedProcessLabel() {
163         smack_new_label_from_self(&label);
164     }
165
166     ~ScopedProcessLabel() {
167         smack_set_label_for_self(label);
168         free(label);
169     }
170
171 private:
172     char *label;
173 };
174
175 static std::string generateAppLabel(const std::string &appId)
176 {
177     return "User::App::" + appId;
178 }
179
180 static std::string generatePkgLabelOwnerRWothersRO(const std::string &pkgId)
181 {
182     return "User::Pkg::" + pkgId + "::SharedRO";
183 }
184
185 static std::string generatePkgLabel(const std::string &pkgId)
186 {
187     return "User::Pkg::" + pkgId;
188 }
189
190 #define FTW_MAX_FDS 16
191
192 static int nftw_remove_labels(const char *fpath, const struct stat* /*sb*/,
193                        int /*typeflag*/, struct FTW* /*ftwbuf*/)
194 {
195     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_ACCESS);
196     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_EXEC);
197     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_TRANSMUTE);
198
199     return 0;
200 }
201
202 static int nftw_set_labels_non_app_dir(const char *fpath, const struct stat* /*sb*/,
203                                 int /*typeflag*/, struct FTW* /*ftwbuf*/)
204 {
205     smack_lsetlabel(fpath, "canary_label", SMACK_LABEL_ACCESS);
206     smack_lsetlabel(fpath, "canary_label", SMACK_LABEL_EXEC);
207     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_TRANSMUTE);
208
209     return 0;
210 }
211
212 static int nftw_check_labels_non_app_dir(const char *fpath, const struct stat* /*sb*/,
213                                   int /*typeflag*/, struct FTW* /*ftwbuf*/)
214 {
215     int result;
216     CStringPtr labelPtr;
217     char* label = nullptr;
218
219     /* ACCESS */
220     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
221     labelPtr.reset(label);
222     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
223     result = strcmp("canary_label", labelPtr.get());
224     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is overwritten");
225
226     /* EXEC */
227     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
228     labelPtr.reset(label);
229     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
230     result = strcmp("canary_label", labelPtr.get());
231     RUNNER_ASSERT_MSG(result == 0, "EXEC label on " << fpath << " is overwritten");
232
233     /* TRANSMUTE */
234     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
235     labelPtr.reset(label);
236     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
237     RUNNER_ASSERT_MSG(labelPtr.get() == nullptr, "TRANSMUTE label on " << fpath << " is set");
238
239     return 0;
240 }
241
242 static int nftw_check_sm_labels_app_dir(const char *fpath, const struct stat *sb,
243                               const char* correctLabel, bool transmute_test, bool exec_test)
244 {
245     int result;
246     CStringPtr labelPtr;
247     char* label = nullptr;
248
249     /* ACCESS */
250     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
251     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
252     labelPtr.reset(label);
253     RUNNER_ASSERT_MSG(label != nullptr, "ACCESS label on " << fpath << " is not set");
254     result = strcmp(correctLabel, label);
255     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is incorrect"
256             " (should be '" << correctLabel << "' and is '" << label << "')");
257
258
259     /* EXEC */
260     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
261     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
262     labelPtr.reset(label);
263
264     if (S_ISREG(sb->st_mode) && (sb->st_mode & S_IXUSR) && exec_test) {
265         RUNNER_ASSERT_MSG(label != nullptr, "EXEC label on " << fpath << " is not set");
266         result = strcmp(correctLabel, label);
267         RUNNER_ASSERT_MSG(result == 0, "Incorrect EXEC label on executable file " << fpath);
268     } else
269         RUNNER_ASSERT_MSG(label == nullptr, "EXEC label on " << fpath << " is set");
270
271
272     /* TRANSMUTE */
273     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
274     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
275     labelPtr.reset(label);
276
277     if (S_ISDIR(sb->st_mode) && transmute_test == true) {
278         RUNNER_ASSERT_MSG(label != nullptr, "TRANSMUTE label on " << fpath << " is not set at all");
279         RUNNER_ASSERT_MSG(strcmp(label,"TRUE") == 0,
280                 "TRANSMUTE label on " << fpath << " is not set properly: '"<<label<<"'");
281     } else {
282         RUNNER_ASSERT_MSG(label == nullptr, "TRANSMUTE label on " << fpath << " is set");
283     }
284
285     return 0;
286 }
287
288 // nftw doesn't allow passing user data to functions. Work around by using global variable
289 static std::string nftw_expected_label;
290 bool nftw_expected_transmute;
291 bool nftw_expected_exec;
292
293 static int nftw_check_sm_labels(const char *fpath, const struct stat *sb,
294                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
295 {
296     return nftw_check_sm_labels_app_dir(fpath, sb,
297         nftw_expected_label.c_str(), nftw_expected_transmute, nftw_expected_exec);
298 }
299
300 static void prepare_app_path(int app_num, bool others_enabled = false)
301 {
302     std::string SM_RW_PATH = genRWPath(app_num);
303     std::string SM_RO_PATH = genROPath(app_num);
304     std::string SM_PUBLIC_RO_PATH = genPublicROPath(app_num);
305     int result;
306
307     result = nftw(SM_RW_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
308     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RW_PATH);
309
310     result = nftw(SM_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
311     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RO_PATH);
312
313     result = nftw(SM_PUBLIC_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
314     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_PUBLIC_RO_PATH);
315
316     if(others_enabled) {
317         std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(app_num);
318         result = nftw(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
319         RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_OWNER_RW_OTHERS_RO_PATH);
320     }
321
322     result = nftw(SM_DENIED_PATH, &nftw_set_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
323     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_DENIED_PATH);
324 }
325
326 static void prepare_app_env(int app_num, bool others_enabled = false)
327 {
328     prepare_app_path(app_num, others_enabled);
329 }
330
331 static void check_app_path_after_install(int app_num, const char *pkgId, bool others_enabled=false)
332 {
333     std::string SM_RW_PATH = genRWPath(app_num);
334     std::string SM_RO_PATH = genROPath(app_num);
335     std::string SM_PUBLIC_RO_PATH = genPublicROPath(app_num);
336     int result;
337
338     nftw_expected_label = generatePkgLabel(pkgId);
339     nftw_expected_transmute = true;
340     nftw_expected_exec = false;
341
342     result = nftw(SM_RW_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
343     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RW_PATH);
344
345     nftw_expected_label = generatePkgLabel(pkgId) + "::RO";
346     nftw_expected_transmute = false;
347     nftw_expected_exec = false;
348
349     result = nftw(SM_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
350     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RO_PATH);
351
352     nftw_expected_label = "User::Home";
353     nftw_expected_transmute = true;
354     nftw_expected_exec = false;
355
356     result = nftw(SM_PUBLIC_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
357     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_PUBLIC_RO_PATH);
358
359     result = nftw(SM_DENIED_PATH, &nftw_check_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
360     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_DENIED_PATH);
361
362     // owner RW, others RO
363     if(others_enabled) {
364         std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(app_num);
365         nftw_expected_label = generatePkgLabelOwnerRWothersRO(pkgId);
366         nftw_expected_transmute = true;
367         nftw_expected_exec = false;
368
369         result = nftw(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
370         RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_OWNER_RW_OTHERS_RO_PATH);
371     }
372 }
373
374
375 static void check_app_permissions(const char *const app_id, const char *const pkg_id, const char *const user,
376                                   const privileges_t &allowed_privs, const privileges_t &denied_privs)
377 {
378     (void) pkg_id;
379     std::string smackLabel = generateAppLabel(app_id);
380
381     CynaraTestClient::Client ctc;
382
383     for (auto &priv : allowed_privs) {
384         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_ALLOWED);
385     }
386
387     for (auto &priv : denied_privs) {
388         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_DENIED);
389     }
390 }
391
392 static void check_app_gids(const char *const app_id, const std::vector<gid_t> &allowed_gids)
393 {
394     int ret;
395     gid_t main_gid = getgid();
396     std::unordered_set<gid_t> reference_gids(allowed_gids.begin(), allowed_gids.end());
397
398     // Reset supplementary groups
399     ret = setgroups(0, NULL);
400     RUNNER_ASSERT_MSG(ret != -1, "Unable to set supplementary groups");
401
402     Api::setProcessGroups(app_id);
403
404     ret = getgroups(0, nullptr);
405     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
406
407     std::vector<gid_t> actual_gids(ret);
408     ret = getgroups(ret, actual_gids.data());
409     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
410
411     for (const auto &gid : actual_gids) {
412         RUNNER_ASSERT_MSG(gid == main_gid || reference_gids.count(gid) > 0,
413             "Application shouldn't get access to group " << gid);
414         reference_gids.erase(gid);
415     }
416
417     RUNNER_ASSERT_MSG(reference_gids.empty(), "Application didn't get access to some groups");
418 }
419
420 static void check_app_after_install(const char *const app_id, const char *const pkg_id,
421                                     const privileges_t &allowed_privs,
422                                     const privileges_t &denied_privs,
423                                     const std::vector<std::string> &allowed_groups)
424 {
425     TestSecurityManagerDatabase dbtest;
426     dbtest.test_db_after__app_install(app_id, pkg_id, allowed_privs);
427     dbtest.check_privileges_removed(app_id, pkg_id, denied_privs);
428
429     /*Privileges should be granted to all users if root installs app*/
430     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, allowed_privs, denied_privs);
431
432     /* Setup mapping of gids to privileges */
433     /* Do this for each privilege for extra check */
434     for (const auto &privilege : allowed_privs) {
435         dbtest.setup_privilege_groups(privilege, allowed_groups);
436     }
437
438     std::vector<gid_t> allowed_gids;
439
440     for (const auto &groupName : allowed_groups) {
441         errno = 0;
442         struct group* grp = getgrnam(groupName.c_str());
443         RUNNER_ASSERT_ERRNO_MSG(grp, "Group: " << groupName << " not found");
444         allowed_gids.push_back(grp->gr_gid);
445     }
446
447     check_app_gids(app_id, allowed_gids);
448 }
449
450 static void check_app_after_install(const char *const app_id, const char *const pkg_id)
451 {
452     TestSecurityManagerDatabase dbtest;
453     dbtest.test_db_after__app_install(app_id, pkg_id);
454 }
455
456 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
457                                       const privileges_t &privileges, const bool is_pkg_removed)
458 {
459     TestSecurityManagerDatabase dbtest;
460     dbtest.test_db_after__app_uninstall(app_id, pkg_id, privileges, is_pkg_removed);
461
462
463     /*Privileges should not be granted anymore to any user*/
464     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, SM_NO_PRIVILEGES, privileges);
465 }
466
467 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
468                                       const bool is_pkg_removed)
469 {
470     TestSecurityManagerDatabase dbtest;
471     dbtest.test_db_after__app_uninstall(app_id, pkg_id, is_pkg_removed);
472 }
473
474 static void install_app(const char *app_id, const char *pkg_id, uid_t uid = 0)
475 {
476     InstallRequest request;
477     request.setAppId(app_id);
478     request.setPkgId(pkg_id);
479     request.setUid(uid);
480     Api::install(request);
481
482     check_app_after_install(app_id, pkg_id);
483 }
484
485 static void uninstall_app(const char *app_id, const char *pkg_id, bool expect_pkg_removed)
486 {
487     InstallRequest request;
488     request.setAppId(app_id);
489
490     Api::uninstall(request);
491
492     check_app_after_uninstall(app_id, pkg_id, expect_pkg_removed);
493 }
494
495 static inline void register_current_process_as_privilege_manager(uid_t uid, bool forAdmin = false)
496 {
497     InstallRequest request;
498     request.setAppId(PRIVILEGE_MANAGER_APP.c_str());
499     request.setPkgId(PRIVILEGE_MANAGER_PKG.c_str());
500     request.setUid(uid);
501     request.addPrivilege(PRIVILEGE_MANAGER_SELF_PRIVILEGE.c_str());
502     if (forAdmin)
503         request.addPrivilege(PRIVILEGE_MANAGER_ADMIN_PRIVILEGE.c_str());
504     Api::install(request);
505     Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
506 };
507
508 static inline struct passwd *getUserStruct(const std::string &userName) {
509     struct passwd *pw = nullptr;
510     errno = 0;
511
512     while(!(pw = getpwnam(userName.c_str()))) {
513         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
514     };
515
516     return pw;
517 };
518
519 static inline struct passwd *getUserStruct(const uid_t uid) {
520     struct passwd *pw = nullptr;
521     errno = 0;
522
523     while(!(pw = getpwuid(uid))) {
524         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
525     };
526
527     return pw;
528 };
529
530 void check_exact_access(const std::string& subject, const std::string& object, const std::string& access)
531 {
532     // check access
533     if (!access.empty()) {
534         int result = smack_have_access(subject.c_str(), object.c_str(), access.c_str());
535         RUNNER_ASSERT_MSG(result >= 0, "smack_have_access failed");
536         RUNNER_ASSERT_MSG(result == 1,
537           "No smack access: " << subject << " " << object << " " << access);
538     }
539     // check excessive access
540     auto foundInAccess = [&access](std::string::value_type c) {
541         return access.find(c) != std::string::npos; };
542
543     std::string negative = "rwxatl";
544     auto end = std::remove_if(negative.begin(), negative.end(), foundInAccess);
545     negative.erase(end, negative.end());
546
547     for(const auto& c : negative) {
548         int result = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
549         RUNNER_ASSERT_MSG(result >= 0, "smack_have_access failed");
550         RUNNER_ASSERT_MSG(result == 0, "Unexpected access for" << 
551             " subject:" << subject <<
552             " object:" << object <<
553             " right:" << std::string(1,c) <<
554             " result:" << result <<
555             " expected:0");
556     }
557 }
558
559 std::string access_opposite(std::string &access) {
560     static const std::map<char, int> access_mapping = {{'r', 0}, {'w', 1}, {'x', 2}, {'a', 3},
561                                                        {'t', 4}, {'l', 5}};
562     //May write implies may lock
563     if (access.find('w') != std::string::npos && access.find('l') == std::string::npos) {
564         access.append("l");
565     }
566     std::string access_opposite = "rwxatl";
567     for (char c : access) {
568         access_opposite[access_mapping.at(c)] = '-';
569     }
570     auto it = std::remove_if(access_opposite.begin(), access_opposite.end(), [](char c) {return c == '-';});
571     access_opposite.erase(it, access_opposite.end());
572     return access_opposite;
573 }
574
575 void check_exact_smack_accesses(const std::string &subject, const std::string &object, const std::string &access) {
576     std::string access_str(access);
577     auto no_access = access_opposite(access_str);
578     for (char c : access_str) {
579         int ret = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
580         RUNNER_ASSERT_MSG(ret >= 0, "smack_have_access failed: <" << subject << ">, <" << object << ">, <" << c << "> errno=" << strerror(errno));
581         RUNNER_ASSERT_MSG(ret == 1, "Access " << c << " from " << subject << " to "
582                           << object << " not given");
583     }
584
585     for (char c : no_access) {
586         int ret = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
587         RUNNER_ASSERT_MSG(ret >= 0, "smack_have_access failed: <" << subject << ">, <" << object << ">, <" << c << "> errno=" << strerror(errno));
588         RUNNER_ASSERT_MSG(ret == 0, "Access " << c << " from " << subject << " to "
589                           << object << " unnecessarily given");
590     }
591 }
592
593
594 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER)
595
596
597 RUNNER_TEST(security_manager_01a_app_double_install_double_uninstall)
598 {
599     const char *const sm_app_id = "sm_test_01a_app_id_double";
600     const char *const sm_pkg_id = "sm_test_01a_pkg_id_double";
601
602     InstallRequest requestInst;
603     requestInst.setAppId(sm_app_id);
604     requestInst.setPkgId(sm_pkg_id);
605
606     Api::install(requestInst);
607     Api::install(requestInst);
608
609     // Check records in the security-manager database
610     check_app_after_install(sm_app_id, sm_pkg_id);
611
612     InstallRequest requestUninst;
613     requestUninst.setAppId(sm_app_id);
614
615     Api::uninstall(requestUninst);
616     Api::uninstall(requestUninst);
617
618     // Check records in the security-manager database
619     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
620 }
621
622
623 RUNNER_TEST(security_manager_01b_app_double_install_wrong_pkg_id)
624 {
625     const char *const sm_app_id = "sm_test_01b_app";
626     const char *const sm_pkg_id = "sm_test_01b_pkg";
627     const char *const sm_pkg_id_wrong = "sm_test_01b_pkg_BAD";
628
629     InstallRequest requestInst;
630     requestInst.setAppId(sm_app_id);
631     requestInst.setPkgId(sm_pkg_id);
632
633     Api::install(requestInst);
634
635     InstallRequest requestInst2;
636     requestInst2.setAppId(sm_app_id);
637     requestInst2.setPkgId(sm_pkg_id_wrong);
638
639     Api::install(requestInst2, SECURITY_MANAGER_ERROR_INPUT_PARAM);
640
641
642     /* Check records in the security-manager database */
643     check_app_after_install(sm_app_id, sm_pkg_id);
644
645     InstallRequest requestUninst;
646     requestUninst.setAppId(sm_app_id);
647
648     Api::uninstall(requestUninst);
649
650
651     /* Check records in the security-manager database */
652     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
653
654 }
655
656 RUNNER_TEST(security_manager_01c_app_uninstall_pkg_id_ignored)
657 {
658     const char * const  sm_app_id = "SM_TEST_01c_APPID";
659     const char * const  sm_pkg_id = "SM_TEST_01c_PKGID";
660     const char * const  sm_pkg_id_wrong = "SM_TEST_01c_PKGID_wrong";
661
662     InstallRequest requestInst;
663     requestInst.setAppId(sm_app_id);
664     requestInst.setPkgId(sm_pkg_id);
665
666     Api::install(requestInst);
667
668     /* Check records in the security-manager database */
669     check_app_after_install(sm_app_id, sm_pkg_id);
670
671     InstallRequest requestUninst;
672     requestUninst.setAppId(sm_app_id);
673     requestUninst.setPkgId(sm_pkg_id_wrong);
674
675     Api::uninstall(requestUninst);
676
677     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
678
679 }
680
681 RUNNER_TEST(security_manager_02_app_install_uninstall_full)
682 {
683     std::string SM_RW_PATH = genRWPath(2);
684     std::string SM_RO_PATH = genROPath(2);
685     std::string SM_PUBLIC_RO_PATH = genPublicROPath(2);
686
687     const char *const sm_app_id = "sm_test_02_app_id_full";
688     const char *const sm_pkg_id = "sm_test_02_pkg_id_full";
689
690     prepare_app_env(2);
691
692     InstallRequest requestInst;
693     requestInst.setAppId(sm_app_id);
694     requestInst.setPkgId(sm_pkg_id);
695     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
696     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
697     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
698     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
699     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
700
701     Api::install(requestInst);
702
703     /* Check records in the security-manager database */
704     check_app_after_install(sm_app_id, sm_pkg_id,
705                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
706
707     /* TODO: add parameters to this function */
708     check_app_path_after_install(2, sm_pkg_id, false);
709
710     InstallRequest requestUninst;
711     requestUninst.setAppId(sm_app_id);
712
713     Api::uninstall(requestUninst);
714
715     /* Check records in the security-manager database,
716      * all previously allowed privileges should be removed */
717     check_app_after_uninstall(sm_app_id, sm_pkg_id,
718                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
719 }
720
721 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
722 {
723     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_smack";
724     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_smack";
725     const char *const socketLabel = "not_expected_label";
726     std::string expected_label = generateAppLabel(app_id);
727     char *label = nullptr;
728     CStringPtr labelPtr;
729     int result;
730
731     uninstall_app(app_id, pkg_id, true);
732     install_app(app_id, pkg_id);
733
734     const auto sockaddr = UDSHelpers::makeAbstractAddress("sm_test_03.socket");
735     int sock = UDSHelpers::createServer(&sockaddr);
736     SockUniquePtr sockPtr(&sock);
737
738     //Set socket label to something different than expecedLabel
739     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPIN, socketLabel);
740     RUNNER_ASSERT_ERRNO_MSG(result == 0,
741         "Can't set socket label. Result: " << result);
742     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPOUT, socketLabel);
743     RUNNER_ASSERT_ERRNO_MSG(result == 0,
744         "Can't set socket label. Result: " << result);
745
746     {
747         ScopedProcessLabel keepLabel;
748         Api::setProcessLabel(app_id);
749
750         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPIN, &label);
751         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
752         labelPtr.reset(label);
753         result = expected_label.compare(label);
754         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
755             expected_label << " Actual: " << label);
756
757         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPOUT, &label);
758         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
759         labelPtr.reset(label);
760         result = expected_label.compare(label);
761         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
762             expected_label << " Actual: " << label);
763
764         result = smack_new_label_from_self(&label);
765         RUNNER_ASSERT_MSG(result >= 0,
766                 " Error getting current process label");
767         RUNNER_ASSERT_MSG(label != nullptr,
768                 " Process label is not set");
769         labelPtr.reset(label);
770
771         result = expected_label.compare(label);
772         RUNNER_ASSERT_MSG(result == 0,
773                 " Process label is incorrect. Expected: \"" << expected_label <<
774                 "\" Actual: \"" << label << "\"");
775     }
776
777     uninstall_app(app_id, pkg_id, true);
778 }
779
780 RUNNER_CHILD_TEST_NOSMACK(security_manager_03_set_label_from_appid_nosmack)
781 {
782     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_nosmack";
783     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_nosmack";
784
785     uninstall_app(app_id, pkg_id, true);
786     install_app(app_id, pkg_id);
787
788     {
789         ScopedProcessLabel keepLabel;
790         Api::setProcessLabel(app_id);
791     }
792
793     uninstall_app(app_id, pkg_id, true);
794 }
795
796 static void prepare_request(InstallRequest &request,
797               const char *const app_id,
798               const char *const pkg_id,
799               app_install_path_type pathType,
800               const char *const path,
801               uid_t uid)
802 {
803     request.setAppId(app_id);
804     request.setPkgId(pkg_id);
805     request.addPath(path, pathType);
806
807     if (uid != 0)
808         request.setUid(uid);
809 }
810
811 static uid_t getGlobalUserId(void)
812 {
813     return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
814 }
815
816 static const std::string appDirPath(const TemporaryTestUser &user,
817         const std::string &appId, const std::string &pkgId)
818 {
819     struct tzplatform_context *tzCtxPtr = nullptr;
820
821     RUNNER_ASSERT(0 == tzplatform_context_create(&tzCtxPtr));
822     TzPlatformContextPtr tzCtxPtrSmart(tzCtxPtr);
823
824     RUNNER_ASSERT_MSG(0 == tzplatform_context_set_user(tzCtxPtr, user.getUid()),
825                       "Unable to set user <" << user.getUserName() << "> for tzplatform context");
826
827     const char *appDir = tzplatform_context_getenv(tzCtxPtr,
828                                 getGlobalUserId() == user.getUid() ? TZ_SYS_RW_APP : TZ_USER_APP);
829     RUNNER_ASSERT_MSG(nullptr != appDir,
830                       "tzplatform_context_getenv failed"
831                           << "for getting sys rw app of user <" << user.getUserName() << ">");
832
833     return std::string(appDir) + "/" + pkgId + "/" + appId;
834 }
835
836 static const std::string nonAppDirPath(const TemporaryTestUser &user)
837 {
838     return TMP_DIR + "/" + user.getUserName();
839 }
840
841 static const std::string uidToStr(const uid_t uid)
842 {
843     return std::to_string(static_cast<unsigned int>(uid));
844 }
845
846 static void install_and_check(const char *const sm_app_id,
847                               const char *const sm_pkg_id,
848                               const TemporaryTestUser& user,
849                               const std::string &appDir,
850                               bool requestUid)
851 {
852     InstallRequest requestPrivate;
853
854     //install app for non-root user
855     //should fail (users may only register folders inside their home)
856     prepare_request(requestPrivate, sm_app_id, sm_pkg_id,
857                     SECURITY_MANAGER_PATH_RW, SM_RW_PATH,
858                     requestUid ? user.getUid() : 0);
859
860     Api::install(requestPrivate, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
861
862     InstallRequest requestPrivateUser;
863
864     //install app for non-root user
865     //should succeed - this time i register folder inside user's home dir
866     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
867                     SECURITY_MANAGER_PATH_RW, appDir.c_str(),
868                     requestUid ? user.getUid() : 0);
869
870     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
871         requestPrivateUser.addPrivilege(privilege.c_str());
872
873     Api::install(requestPrivateUser);
874
875     check_app_permissions(sm_app_id, sm_pkg_id,
876                           uidToStr(user.getUid()).c_str(),
877                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
878 }
879
880 static void createTestDir(const std::string &dir)
881 {
882     mode_t dirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
883     mode_t execFileMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
884     mode_t normalFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
885
886     mktreeSafe(dir, dirMode);
887     creatSafe(dir + "/" + EXEC_FILE, execFileMode);
888     creatSafe(dir + "/" + NORMAL_FILE, normalFileMode);
889     symlinkSafe(dir + "/" + EXEC_FILE, dir + "/" + LINK_PREFIX + EXEC_FILE);
890     symlinkSafe(dir + "/" + NORMAL_FILE, dir + "/" + LINK_PREFIX + NORMAL_FILE);
891 }
892
893 static void createInnerAppDir(const std::string &dir, const std::string &nonAppDir)
894 {
895     createTestDir(dir);
896
897     symlinkSafe(nonAppDir, dir + "/" + LINK_PREFIX + "non_app_dir");
898     symlinkSafe(nonAppDir + "/" + EXEC_FILE,
899                 dir + "/" + LINK_PREFIX + "non_app_" + EXEC_FILE);
900     symlinkSafe(nonAppDir + "/" + NORMAL_FILE,
901                 dir + "/" + LINK_PREFIX + "non_app_" + NORMAL_FILE);
902 }
903
904 static void generateAppDir(const TemporaryTestUser &user,
905        const std::string &appId, const std::string &pkgId)
906 {
907     const std::string dir = appDirPath(user, appId, pkgId);
908     const std::string nonAppDir = nonAppDirPath(user);
909
910     createInnerAppDir(dir, nonAppDir);
911     createInnerAppDir(dir + "/.inner_dir", nonAppDir);
912     createInnerAppDir(dir + "/inner_dir", nonAppDir);
913 }
914
915 static void generateNonAppDir(const TemporaryTestUser &user)
916 {
917     const std::string dir = nonAppDirPath(user);
918
919     createTestDir(dir);
920     createTestDir(dir + "/.inner_dir");
921     createTestDir(dir + "/inner_dir");
922 }
923
924 static void createTestDirs(const TemporaryTestUser &user,
925        const std::string &appId, const std::string &pkgId)
926 {
927     generateAppDir(user, appId, pkgId);
928     generateNonAppDir(user);
929 }
930
931 static void removeTestDirs(const TemporaryTestUser &user,
932        const std::string &appId, const std::string &pkgId)
933 {
934     removeDir(appDirPath(user, appId, pkgId));
935     removeDir(nonAppDirPath(user));
936 }
937
938 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
939 {
940     int result;
941     const char *const sm_app_id = "sm_test_04a_app_id_uid";
942     const char *const sm_pkg_id = "sm_test_04a_pkg_id_uid";
943     const std::string new_user_name = "sm_test_04a_user_name";
944
945     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
946     testUser.create();
947
948     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
949     createTestDirs(testUser, sm_app_id, sm_pkg_id);
950
951     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
952
953     //switch user to non-root
954     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
955     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
956
957     install_and_check(sm_app_id, sm_pkg_id, testUser, userAppDirPath, false);
958
959     //uninstall app as non-root user
960     InstallRequest request;
961     request.setAppId(sm_app_id);
962
963     Api::uninstall(request);
964
965     check_app_permissions(sm_app_id, sm_pkg_id,
966                           uidToStr(testUser.getUid()).c_str(),
967                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
968 }
969
970 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user)
971 {
972     int result;
973     const char *const sm_app_id = "sm_test_04b_app_id_uid";
974     const char *const sm_pkg_id = "sm_test_04b_pkg_id_uid";
975     const std::string new_user_name = "sm_test_04b_user_name";
976
977     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
978     testUser.create();
979
980     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
981     createTestDirs(testUser, sm_app_id, sm_pkg_id);
982
983     install_and_check(sm_app_id, sm_pkg_id, testUser, appDirPath(testUser, sm_app_id, sm_pkg_id), true);
984
985     //switch user to non-root - root may not uninstall apps for specified users
986     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
987     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
988
989     //uninstall app as non-root user
990     InstallRequest request;
991     request.setAppId(sm_app_id);
992
993     Api::uninstall(request);
994
995     check_app_permissions(sm_app_id, sm_pkg_id,
996                           uidToStr(testUser.getUid()).c_str(),
997                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
998 }
999
1000
1001 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
1002 {
1003     int result;
1004     CapsSetsUniquePtr caps, caps_empty(cap_init());
1005
1006     caps.reset(cap_from_text("all=eip"));
1007     RUNNER_ASSERT_MSG(caps, "can't convert capabilities from text");
1008     result = cap_set_proc(caps.get());
1009     RUNNER_ASSERT_MSG(result == 0,
1010         "can't set capabilities. Result: " << result);
1011
1012     Api::dropProcessPrivileges();
1013
1014     caps.reset(cap_get_proc());
1015     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
1016
1017     result = cap_compare(caps.get(), caps_empty.get());
1018     RUNNER_ASSERT_MSG(result == 0,
1019         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
1020 }
1021
1022 RUNNER_CHILD_TEST(security_manager_06_install_app_offline)
1023 {
1024     const char *const app_id = "sm_test_06_app_id_install_app_offline";
1025     const char *const pkg_id = "sm_test_06_pkg_id_install_app_offline";
1026
1027     // Uninstall app on-line, off-line mode doesn't support it
1028     uninstall_app(app_id, pkg_id, true);
1029
1030     ServiceManager("security-manager.service").stopService();
1031
1032     ServiceManager serviceManager("security-manager.socket");
1033     serviceManager.stopService();
1034
1035     install_app(app_id, pkg_id);
1036
1037     serviceManager.startService();
1038
1039     uninstall_app(app_id, pkg_id, true);
1040 }
1041
1042 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
1043 {
1044     const char *const sm_app_id = "sm_test_07_app_id_user";
1045     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
1046     const std::string new_user_name = "sm_test_07_user_name";
1047     std::string uid_string;
1048     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
1049     test_user.create();
1050     test_user.getUidString(uid_string);
1051
1052     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
1053     createTestDirs(test_user, sm_app_id, sm_pkg_id);
1054
1055     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
1056
1057     check_app_after_install(sm_app_id, sm_pkg_id);
1058
1059     test_user.remove();
1060
1061     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1062
1063     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
1064 }
1065
1066 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
1067 {
1068     UserRequest addUserRequest;
1069
1070     const char *const sm_app_id = "sm_test_08_app_id_user";
1071     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
1072     const std::string new_user_name = "sm_test_08_user_name";
1073     std::string uid_string;
1074
1075     // gumd user add
1076     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
1077     test_user.create();
1078     test_user.getUidString(uid_string);
1079
1080     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
1081     createTestDirs(test_user, sm_app_id, sm_pkg_id);
1082
1083     addUserRequest.setUid(test_user.getUid());
1084     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
1085
1086     //sm user add
1087     Api::addUser(addUserRequest);
1088
1089     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
1090
1091     check_app_after_install(sm_app_id, sm_pkg_id);
1092
1093     test_user.remove();
1094
1095     UserRequest deleteUserRequest;
1096     deleteUserRequest.setUid(test_user.getUid());
1097
1098     Api::deleteUser(deleteUserRequest);
1099
1100     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1101
1102     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
1103 }
1104
1105 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
1106 {
1107     const char *const app_id = "security_manager_09_add_user_offline_app";
1108     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
1109     const std::string new_user_name("sm_test_09_user_name");
1110
1111     ServiceManager("security-manager.service").stopService();
1112
1113     ServiceManager serviceManager("security-manager.socket");
1114     serviceManager.stopService();
1115
1116     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, true);
1117     test_user.create();
1118
1119     removeTestDirs(test_user, app_id, pkg_id);
1120     createTestDirs(test_user, app_id, pkg_id);
1121
1122     install_app(app_id, pkg_id, test_user.getUid());
1123
1124     check_app_after_install(app_id, pkg_id);
1125
1126     serviceManager.startService();
1127
1128     test_user.remove();
1129
1130     check_app_after_uninstall(app_id, pkg_id, true);
1131 }
1132
1133 RUNNER_MULTIPROCESS_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
1134 {
1135     //TEST DATA
1136     const std::string username("sm_test_10_user_name");
1137     unsigned int privileges_count = 0;
1138
1139     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1140     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1141
1142     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1143         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1144             MANY_APPS.at(i), std::set<std::string>(
1145                 MANY_APPS_PRIVILEGES.at(i).begin(),
1146                 MANY_APPS_PRIVILEGES.at(i).end())));
1147         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1148     };
1149
1150     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1151         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1152     ++privileges_count;
1153     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1154     //TEST DATA END
1155
1156     SynchronizationPipe pipe;
1157     pid_t pid = fork();
1158
1159     if (pid != 0) { //parent process
1160         pipe.claimParentEp();
1161         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
1162         tmpUser.create();
1163
1164         for(const auto &user : users2AppsMap) {
1165
1166             for(const auto &app : user.second) {
1167                 InstallRequest requestInst;
1168                 requestInst.setAppId(app.first.c_str());
1169                 try {
1170                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1171                 } catch (const std::out_of_range &e) {
1172                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1173                 };
1174                 requestInst.setUid(tmpUser.getUid());
1175
1176                 for (const auto &privilege : app.second) {
1177                     requestInst.addPrivilege(privilege.c_str());
1178                 };
1179
1180                 Api::install(requestInst);
1181             };
1182
1183             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1184         };
1185
1186         //Start child process
1187         pipe.post();
1188         waitPid(pid);
1189
1190         tmpUser.remove();
1191     } else { //child process
1192         pipe.claimChildEp();
1193         pipe.wait();
1194         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
1195
1196         struct passwd *pw = getUserStruct(username);
1197         register_current_process_as_privilege_manager(pw->pw_uid);
1198         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1199         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1200
1201         std::vector<PolicyEntry> policyEntries;
1202         PolicyEntry filter;
1203         Api::getPolicy(filter, policyEntries);
1204
1205         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1206         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1207
1208         for (const auto &policyEntry : policyEntries) {
1209             std::string user = policyEntry.getUser();
1210             std::string app = policyEntry.getAppId();
1211             std::string privilege = policyEntry.getPrivilege();
1212
1213             try {
1214                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1215                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1216                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1217                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1218             } catch (const std::out_of_range &e) {
1219                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1220             } catch (const std::invalid_argument& e) {
1221                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1222             };
1223         };
1224         exit(0);
1225     };
1226 }
1227
1228 RUNNER_MULTIPROCESS_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1229 {
1230     //TEST DATA
1231     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1232     unsigned int privileges_count = 0;
1233
1234     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1235     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1236
1237     for (const auto &username : usernames) {
1238         //Only entries for one of the users will be listed
1239         privileges_count = 0;
1240
1241         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1242             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1243                 MANY_APPS.at(i), std::set<std::string>(
1244                     MANY_APPS_PRIVILEGES.at(i).begin(),
1245                     MANY_APPS_PRIVILEGES.at(i).end())));
1246             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1247         };
1248
1249         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1250     };
1251
1252     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1253         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1254
1255     ++privileges_count;
1256     //TEST DATA END
1257
1258     SynchronizationPipe pipe;
1259     pid_t pid = fork();
1260
1261     if (pid != 0) { //parent process
1262         pipe.claimParentEp();
1263         std::vector<TemporaryTestUser> users = {
1264             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1265             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1266             };
1267
1268         users.at(0).create();
1269         users.at(1).create();
1270
1271         //Install apps for both users
1272         for(const auto &user : users) {
1273             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1274                 InstallRequest requestInst;
1275                 requestInst.setAppId(app.first.c_str());
1276                 try {
1277                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1278                 } catch (const std::out_of_range &e) {
1279                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1280                 };
1281                 requestInst.setUid(user.getUid());
1282
1283                 for (const auto &privilege : app.second) {
1284                     requestInst.addPrivilege(privilege.c_str());
1285                 };
1286
1287                 Api::install(requestInst);
1288             };
1289
1290             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1291         };
1292
1293         //Start child
1294         pipe.post();
1295         waitPid(pid);
1296
1297         for (auto &user : users)
1298             user.remove();
1299
1300     } else { //child process
1301         pipe.claimChildEp();
1302         pipe.wait();
1303
1304         struct passwd *pw = getUserStruct(usernames.at(0));
1305         register_current_process_as_privilege_manager(pw->pw_uid);
1306
1307         //change uid to normal user
1308         errno = 0;
1309         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1310         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1311
1312         std::vector<PolicyEntry> policyEntries;
1313         PolicyEntry filter;
1314
1315         //this call should only return privileges belonging to the current uid
1316         Api::getPolicy(filter, policyEntries);
1317
1318         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1319         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1320
1321         for (const auto &policyEntry : policyEntries) {
1322             std::string user = policyEntry.getUser();
1323             std::string app = policyEntry.getAppId();
1324             std::string privilege = policyEntry.getPrivilege();
1325
1326             try {
1327                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1328                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1329                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1330                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1331             } catch (const std::out_of_range &e) {
1332                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1333             } catch (const std::invalid_argument& e) {
1334                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1335             };
1336         };
1337         exit(0);
1338     };
1339 }
1340
1341 RUNNER_MULTIPROCESS_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1342 {
1343     //TEST DATA
1344     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1345     unsigned int privileges_count = 0;
1346
1347     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1348     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1349
1350     for (const auto &username : usernames) {
1351
1352         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1353             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1354                 MANY_APPS.at(i), std::set<std::string>(
1355                     MANY_APPS_PRIVILEGES.at(i).begin(),
1356                     MANY_APPS_PRIVILEGES.at(i).end())));
1357             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1358         };
1359
1360         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1361     };
1362
1363     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1364         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1365
1366     privileges_count += 2;
1367     //TEST DATA END
1368
1369     SynchronizationPipe pipe;
1370     pid_t pid = fork();
1371
1372     if (pid != 0) { //parent process
1373         pipe.claimParentEp();
1374         std::vector<TemporaryTestUser> users = {
1375             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1376             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1377             };
1378
1379         users.at(0).create();
1380         users.at(1).create();
1381         //Install apps for both users
1382         for(const auto &user : users) {
1383             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1384                 InstallRequest requestInst;
1385                 requestInst.setAppId(app.first.c_str());
1386                 try {
1387                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1388                 } catch (const std::out_of_range &e) {
1389                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1390                 };
1391                 requestInst.setUid(user.getUid());
1392
1393                 for (const auto &privilege : app.second) {
1394                     requestInst.addPrivilege(privilege.c_str());
1395                 };
1396
1397                 Api::install(requestInst);
1398             };
1399
1400             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1401         };
1402
1403         //Start child process
1404         pipe.post();
1405         waitPid(pid);
1406
1407         for (auto &user : users)
1408             user.remove();
1409
1410     } else { //child process
1411         pipe.claimChildEp();
1412         pipe.wait();
1413
1414         struct passwd *pw = getUserStruct(usernames.at(1));
1415         register_current_process_as_privilege_manager(pw->pw_uid, true);
1416
1417         //change uid to normal user
1418         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1419         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1420
1421         std::vector<PolicyEntry> policyEntries;
1422         PolicyEntry filter;
1423         //this call should succeed as the calling user is privileged
1424         Api::getPolicy(filter, policyEntries);
1425
1426         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1427         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1428
1429         for (const auto &policyEntry : policyEntries) {
1430             std::string user = policyEntry.getUser();
1431             std::string app = policyEntry.getAppId();
1432             std::string privilege = policyEntry.getPrivilege();
1433
1434             try {
1435                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1436                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1437                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1438                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1439             } catch (const std::out_of_range &e) {
1440                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1441             } catch (const std::invalid_argument& e) {
1442                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1443             };
1444         };
1445
1446         exit(0);
1447     };
1448 }
1449
1450 RUNNER_MULTIPROCESS_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1451 {
1452     //TEST DATA
1453     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1454
1455     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1456     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1457
1458     for (const auto &username : usernames) {
1459
1460         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1461             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1462                 MANY_APPS.at(i), std::set<std::string>(
1463                     MANY_APPS_PRIVILEGES.at(i).begin(),
1464                     MANY_APPS_PRIVILEGES.at(i).end())));
1465         };
1466
1467         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1468     };
1469
1470     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1471         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1472
1473     //TEST DATA END
1474
1475     pid_t pid[2];
1476     SynchronizationPipe sync[2];
1477     std::vector<PolicyEntry> policyEntries;
1478
1479     pid[0] = fork();
1480
1481     if (pid[0] == 0) { //child #1 process
1482         sync[0].claimChildEp();
1483         sync[0].wait();
1484
1485         struct passwd *pw = getUserStruct(usernames.at(0));
1486         register_current_process_as_privilege_manager(pw->pw_uid);
1487
1488         //change uid to normal user
1489         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1490         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1491
1492         PolicyEntry filter;
1493         PolicyRequest policyRequest;
1494         //this call should succeed as the calling user is privileged
1495         Api::getPolicyForSelf(filter, policyEntries);
1496
1497         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1498
1499         PolicyEntry policyEntry(
1500                 MANY_APPS[0],
1501                 std::to_string(pw->pw_uid),
1502                 "http://tizen.org/privilege/internet"
1503                 );
1504         policyEntry.setLevel("Deny");
1505
1506         policyRequest.addEntry(policyEntry);
1507         policyEntry = PolicyEntry(
1508                 MANY_APPS[1],
1509                 std::to_string(pw->pw_uid),
1510                 "http://tizen.org/privilege/location"
1511                 );
1512         policyEntry.setLevel("Deny");
1513
1514         policyRequest.addEntry(policyEntry);
1515         Api::sendPolicy(policyRequest);
1516         Api::getPolicyForSelf(filter, policyEntries);
1517
1518         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1519         exit(0);
1520     } else { //parent process
1521         sync[0].claimParentEp();
1522         pid[1] = fork();
1523
1524         if (pid[1] == 0) { //child #2 process
1525             sync[1].claimChildEp();
1526             sync[1].wait();
1527             struct passwd *pw_target = getUserStruct(usernames.at(0));
1528             struct passwd *pw = getUserStruct(usernames.at(1));
1529             register_current_process_as_privilege_manager(pw->pw_uid);
1530
1531             //change uid to normal user
1532             int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1533             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1534
1535             PolicyEntry filter = PolicyEntry(
1536                         SECURITY_MANAGER_ANY,
1537                         std::to_string(pw_target->pw_uid),
1538                         SECURITY_MANAGER_ANY
1539                         );
1540
1541             //U2 requests contents of U1 privacy manager - should fail
1542             Api::getPolicyForSelf(filter, policyEntries);
1543             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1544
1545             filter = PolicyEntry(
1546                         SECURITY_MANAGER_ANY,
1547                         SECURITY_MANAGER_ANY,
1548                         SECURITY_MANAGER_ANY
1549                         );
1550
1551             policyEntries.clear();
1552
1553             //U2 requests contents of ADMIN bucket - should fail
1554             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1555             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1556             exit(0);
1557         } else { //parent
1558             sync[1].claimParentEp();
1559             std::vector<TemporaryTestUser> users = {
1560                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1561                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1562                 };
1563
1564             users.at(0).create();
1565             users.at(1).create();
1566
1567             //Install apps for both users
1568             for(const auto &user : users2AppsMap) {
1569
1570                 for(const auto &app : user.second) {
1571                     InstallRequest requestInst;
1572                     requestInst.setAppId(app.first.c_str());
1573                     try {
1574                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1575                     } catch (const std::out_of_range &e) {
1576                         RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1577                     };
1578                     requestInst.setUid(users.at(0).getUid());
1579
1580                     for (const auto &privilege : app.second) {
1581                         requestInst.addPrivilege(privilege.c_str());
1582                     };
1583
1584                     Api::install(requestInst);
1585                 };
1586
1587                 //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1588             };
1589
1590             //Start child #1
1591             sync[0].post();
1592             waitPid(pid[0]);
1593
1594             //Start child #2
1595             sync[1].post();
1596             waitPid(pid[1]);
1597
1598             for (auto &user : users)
1599                 user.remove();
1600         };
1601     };
1602 }
1603
1604 RUNNER_MULTIPROCESS_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1605 {
1606     //TEST DATA
1607     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1608     unsigned int privileges_count = 0;
1609
1610     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1611     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1612
1613     for (const auto &username : usernames) {
1614
1615         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1616             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1617                 MANY_APPS.at(i), std::set<std::string>(
1618                     MANY_APPS_PRIVILEGES.at(i).begin(),
1619                     MANY_APPS_PRIVILEGES.at(i).end())));
1620             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1621         };
1622
1623         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1624     };
1625
1626     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1627         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1628
1629     privileges_count += 2;
1630     //TEST DATA END
1631     SynchronizationPipe pipe;
1632
1633     pid_t pid = fork();
1634     if (pid != 0) {
1635         pipe.claimParentEp();
1636         std::vector<TemporaryTestUser> users = {
1637             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1638             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1639             };
1640
1641         users.at(0).create();
1642         users.at(1).create();
1643
1644         //Install apps for both users
1645         for(const auto &user : users) {
1646
1647             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1648                 InstallRequest requestInst;
1649                 requestInst.setAppId(app.first.c_str());
1650                 try {
1651                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1652                 } catch (const std::out_of_range &e) {
1653                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1654                 };
1655                 requestInst.setUid(user.getUid());
1656
1657                 for (const auto &privilege : app.second) {
1658                     requestInst.addPrivilege(privilege.c_str());
1659                 };
1660
1661                 Api::install(requestInst);
1662             };
1663         };
1664
1665         //Start child process
1666         pipe.post();
1667         waitPid(pid);
1668
1669         //switch back to root
1670         for (auto &user : users)
1671             user.remove();
1672
1673     } else { //child process
1674         pipe.claimChildEp();
1675         pipe.wait();
1676
1677         struct passwd *pw = getUserStruct(usernames.at(1));
1678         register_current_process_as_privilege_manager(pw->pw_uid, true);
1679
1680         //change uid to normal user
1681         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1682         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1683
1684         PolicyRequest *policyRequest = new PolicyRequest();
1685         PolicyEntry filter;
1686         std::vector<PolicyEntry> policyEntries;
1687         //this call should succeed as the calling user is privileged
1688         Api::getPolicyForSelf(filter, policyEntries);
1689
1690         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1691
1692         PolicyEntry policyEntry(
1693                 SECURITY_MANAGER_ANY,
1694                 SECURITY_MANAGER_ANY,
1695                 "http://tizen.org/privilege/internet"
1696                 );
1697         policyEntry.setMaxLevel("Deny");
1698
1699         policyRequest->addEntry(policyEntry);
1700         policyEntry = PolicyEntry(
1701                 SECURITY_MANAGER_ANY,
1702                 SECURITY_MANAGER_ANY,
1703                 "http://tizen.org/privilege/location"
1704                 );
1705         policyEntry.setMaxLevel("Deny");
1706
1707         policyRequest->addEntry(policyEntry);
1708         Api::sendPolicy(*policyRequest);
1709         Api::getPolicyForAdmin(filter, policyEntries);
1710
1711         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1712
1713         delete policyRequest;
1714         policyRequest = new PolicyRequest();
1715         policyEntry = PolicyEntry(
1716                 SECURITY_MANAGER_ANY,
1717                 SECURITY_MANAGER_ANY,
1718                 "http://tizen.org/privilege/internet"
1719                 );
1720         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1721         policyRequest->addEntry(policyEntry);
1722
1723         policyEntry = PolicyEntry(
1724                 SECURITY_MANAGER_ANY,
1725                 SECURITY_MANAGER_ANY,
1726                 "http://tizen.org/privilege/location"
1727                 );
1728         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1729
1730         policyRequest->addEntry(policyEntry);
1731         Api::sendPolicy(*policyRequest);
1732
1733         policyEntries.clear();
1734         Api::getPolicyForAdmin(filter, policyEntries);
1735         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1736
1737         delete policyRequest;
1738
1739         exit(0);
1740     };
1741
1742 }
1743
1744 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1745 {
1746     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
1747     const char *const update_app_id = "security_manager_15_update_app_id";
1748     const char *const update_privilege = "http://tizen.org/privilege/led";
1749     const char *const check_start_bucket = "ADMIN";
1750     const std::string username("sm_test_15_username");
1751     PolicyRequest addPolicyRequest;
1752     CynaraTestAdmin::Admin admin;
1753     ScopedProcessLabel keepLabel;
1754
1755     struct message {
1756         uid_t uid;
1757         gid_t gid;
1758     } msg;
1759
1760     int pipefd[2];
1761     pid_t pid;
1762     int result = 0;
1763
1764     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1765
1766     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1767     user.create();
1768
1769     pid = fork();
1770     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1771     if (pid != 0)//parent process
1772     {
1773         FdUniquePtr pipeptr(pipefd+1);
1774         close(pipefd[0]);
1775
1776         register_current_process_as_privilege_manager(user.getUid(), true);
1777
1778         //send info to child
1779         msg.uid = user.getUid();
1780         msg.gid = user.getGid();
1781
1782         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1783         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1784
1785         waitPid(pid);
1786
1787         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1788                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1789     }
1790     if(pid == 0)
1791     {
1792         FdUniquePtr pipeptr(pipefd);
1793         close(pipefd[1]);
1794
1795         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1796         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1797
1798         //become admin privacy manager manager
1799         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1800         result = drop_root_privileges(msg.uid, msg.gid);
1801         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1802
1803         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1804         entry.setMaxLevel("Allow");
1805
1806         addPolicyRequest.addEntry(entry);
1807         Api::sendPolicy(addPolicyRequest);
1808         exit(0);
1809     }
1810 }
1811
1812 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1813 {
1814     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
1815     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1816     const char *const update_privilege = "http://tizen.org/privilege/led";
1817     const char *const check_start_bucket = "ADMIN";
1818     const std::string username("sm_test_15_username");
1819     PolicyRequest addPolicyRequest;
1820     CynaraTestAdmin::Admin admin;
1821     ScopedProcessLabel keepLabel;
1822
1823     struct message {
1824         uid_t uid;
1825         gid_t gid;
1826     } msg;
1827
1828     int pipefd[2];
1829     pid_t pid;
1830     int result = 0;
1831
1832     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1833
1834     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1835     user.create();
1836
1837     pid = fork();
1838     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1839     if (pid != 0)//parent process
1840     {
1841         FdUniquePtr pipeptr(pipefd+1);
1842         close(pipefd[0]);
1843
1844         register_current_process_as_privilege_manager(user.getUid(), true);
1845
1846         //send info to child
1847         msg.uid = user.getUid();
1848         msg.gid = user.getGid();
1849
1850         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1851         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1852
1853         waitPid(pid);
1854
1855         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_other_app_id).c_str(),
1856                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1857     }
1858     if(pid == 0)
1859     {
1860         FdUniquePtr pipeptr(pipefd);
1861         close(pipefd[1]);
1862
1863         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1864         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1865
1866         //become admin privacy manager manager
1867         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1868         result = drop_root_privileges(msg.uid, msg.gid);
1869         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1870
1871         // use wildcard as appId
1872         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1873         entry.setMaxLevel("Allow");
1874
1875         addPolicyRequest.addEntry(entry);
1876         Api::sendPolicy(addPolicyRequest);
1877         exit(0);
1878     }
1879 }
1880
1881 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1882 {
1883     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
1884     const char *const update_app_id = "security_manager_15_update_app_id";
1885     const char *const update_privilege = "http://tizen.org/privilege/led";
1886     const char *const check_start_bucket = "";
1887     const std::string username("sm_test_15_username");
1888     PolicyRequest addPolicyRequest;
1889     CynaraTestAdmin::Admin admin;
1890     ScopedProcessLabel keepLabel;
1891
1892     struct message {
1893         uid_t uid;
1894         gid_t gid;
1895     } msg;
1896
1897     int pipefd[2];
1898     pid_t pid;
1899     int result = 0;
1900
1901     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1902
1903     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1904     user.create();
1905
1906     pid = fork();
1907     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1908     if (pid != 0)//parent process
1909     {
1910         FdUniquePtr pipeptr(pipefd+1);
1911         close(pipefd[0]);
1912
1913         register_current_process_as_privilege_manager(user.getUid(), false);
1914
1915         //send info to child
1916         msg.uid = user.getUid();
1917         msg.gid = user.getGid();
1918
1919         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1920         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1921
1922         waitPid(pid);
1923
1924         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1925                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1926     }
1927     if(pid == 0)
1928     {
1929         FdUniquePtr pipeptr(pipefd);
1930         close(pipefd[1]);
1931
1932         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1933         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1934
1935         //become admin privacy manager manager
1936         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1937         result = drop_root_privileges(msg.uid, msg.gid);
1938         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1939
1940         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1941         entry.setLevel("Allow");
1942
1943         addPolicyRequest.addEntry(entry);
1944         Api::sendPolicy(addPolicyRequest);
1945         exit(0);
1946     }
1947 }
1948
1949 RUNNER_MULTIPROCESS_TEST(security_manager_16_policy_levels_get)
1950 {
1951     const std::string username("sm_test_16_user_cynara_policy");
1952     CynaraTestAdmin::Admin admin;
1953     int pipefd[2];
1954     pid_t pid;
1955     int result = 0;
1956
1957     struct message {
1958         uid_t uid;
1959         gid_t gid;
1960     } msg;
1961
1962     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1963
1964     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1965     user.create();
1966
1967     pid = fork();
1968     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1969     if (pid != 0)//parent process
1970     {
1971         FdUniquePtr pipeptr(pipefd+1);
1972         close(pipefd[0]);
1973
1974         //send info to child
1975         msg.uid = user.getUid();
1976         msg.gid = user.getGid();
1977
1978         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1979         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1980
1981         waitPid(pid);
1982     }
1983     if(pid == 0)
1984     {
1985         int ret;
1986         char** levels;
1987         std::string allow_policy, deny_policy;
1988         size_t count;
1989         FdUniquePtr pipeptr(pipefd);
1990         close(pipefd[1]);
1991
1992         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1993         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1994
1995         //become admin privacy manager manager
1996         result = drop_root_privileges(msg.uid, msg.gid);
1997         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1998
1999         // without plugins there should only be 2 policies - Allow and Deny
2000         ret = security_manager_policy_levels_get(&levels, &count);
2001
2002         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
2003                 "Invlid return code: " << ret);
2004
2005         RUNNER_ASSERT_MSG(count == 2, "Invalid number of policy levels. Should be 2, instead there is: " << static_cast<int>(count));
2006
2007         deny_policy = std::string(levels[0]);
2008         allow_policy = std::string(levels[count-1]);
2009
2010         // first should always be Deny
2011         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
2012                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
2013
2014         // last should always be Allow
2015         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
2016                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
2017
2018         security_manager_policy_levels_free(levels, count);
2019         exit(0);
2020     }
2021 }
2022
2023 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
2024 {
2025     const char *const update_app_id = "security_manager_17_update_app_id";
2026     const char *const update_privilege = "http://tizen.org/privilege/led";
2027     const char *const check_start_bucket = "";
2028     const std::string username("sm_test_17_username");
2029     PolicyRequest addPolicyRequest;
2030     CynaraTestAdmin::Admin admin;
2031
2032     struct message {
2033         uid_t uid;
2034         gid_t gid;
2035     } msg;
2036
2037     int pipefd[2];
2038     int pipefd2[2];
2039     pid_t pid[2];
2040     int result = 0;
2041     ScopedProcessLabel keepLabel;
2042
2043     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2044     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
2045
2046     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2047     user.create();
2048
2049     pid[0] = fork();
2050     RUNNER_ASSERT_MSG(pid[0] >= 0, "fork failed");
2051     if (pid[0] != 0)//parent process
2052     {
2053         FdUniquePtr pipeptr(pipefd+1);
2054         close(pipefd[0]);
2055
2056         register_current_process_as_privilege_manager(user.getUid(), false);
2057
2058         //send info to child
2059         msg.uid = user.getUid();
2060         msg.gid = user.getGid();
2061
2062         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2063         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2064
2065         waitPid(pid[0]);
2066
2067         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2068                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
2069
2070         pid[1] = fork();
2071         if (pid[1] != 0)//parent process
2072         {
2073             FdUniquePtr pipeptr(pipefd2+1);
2074             close(pipefd2[0]);
2075
2076             //send info to child
2077             msg.uid = user.getUid();
2078             msg.gid = user.getGid();
2079
2080             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
2081             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2082
2083             waitPid(pid[1]);
2084
2085             admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2086                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
2087         }
2088         if(pid[1] == 0)
2089         {
2090             FdUniquePtr pipeptr(pipefd2);
2091             close(pipefd2[1]);
2092
2093             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
2094             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2095
2096             //become admin privacy manager manager
2097             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2098             result = drop_root_privileges(msg.uid, msg.gid);
2099             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2100
2101             // delete this entry
2102             PolicyRequest deletePolicyRequest;
2103             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2104             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
2105
2106             deletePolicyRequest.addEntry(deleteEntry);
2107             Api::sendPolicy(deletePolicyRequest);
2108             exit(0);
2109         }
2110     }
2111     if(pid[0] == 0)
2112     {
2113         FdUniquePtr pipeptr(pipefd);
2114         close(pipefd[1]);
2115
2116         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2117         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2118
2119         //become admin privacy manager manager
2120         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2121         result = drop_root_privileges(msg.uid, msg.gid);
2122         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2123
2124         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2125         entry.setLevel("Allow");
2126
2127         addPolicyRequest.addEntry(entry);
2128         Api::sendPolicy(addPolicyRequest);
2129         exit(0);
2130     }
2131 }
2132
2133 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
2134 {
2135     const std::string username("sm_test_17_user_name");
2136
2137     struct message {
2138         uid_t uid;
2139         gid_t gid;
2140         unsigned int privileges_count;
2141     } msg;
2142
2143     int pipefd[2];
2144     pid_t pid;
2145     int result = 0;
2146     ScopedProcessLabel keepLabel;
2147
2148     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2149
2150     pid = fork();
2151     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2152     if (pid != 0)//parent process
2153     {
2154         FdUniquePtr pipeptr(pipefd+1);
2155         close(pipefd[0]);
2156
2157         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2158         user.create();
2159
2160         unsigned int privileges_count = 0;
2161
2162         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2163             InstallRequest requestInst;
2164             requestInst.setAppId(MANY_APPS[i].c_str());
2165             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).package.c_str());
2166             requestInst.setUid(user.getUid());
2167
2168             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2169                 requestInst.addPrivilege(priv.c_str());
2170             };
2171
2172             Api::install(requestInst);
2173             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2174         };
2175
2176         register_current_process_as_privilege_manager(user.getUid(), false);
2177         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2178         ++privileges_count;
2179
2180         //send info to child
2181         msg.uid = user.getUid();
2182         msg.gid = user.getGid();
2183         msg.privileges_count = privileges_count;
2184
2185         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2186         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2187
2188         waitPid(pid);
2189     }
2190     if(pid == 0)
2191     {
2192         FdUniquePtr pipeptr(pipefd);
2193         close(pipefd[1]);
2194
2195         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2196         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2197
2198         //become admin privacy manager manager
2199         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2200         result = drop_root_privileges(msg.uid, msg.gid);
2201         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2202
2203         // filter by privilege
2204         std::vector<PolicyEntry> policyEntries;
2205         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2206         Api::getPolicy(filter, policyEntries);
2207
2208         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2209         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2210
2211         // filter by other privilege
2212         policyEntries.clear();
2213         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2214         Api::getPolicy(filter2, policyEntries);
2215
2216         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2217         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2218
2219         // filter by appId
2220         policyEntries.clear();
2221         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2222         Api::getPolicy(filter3, policyEntries);
2223
2224         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2225         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2226     }
2227 }
2228
2229 RUNNER_CHILD_TEST(security_manager_18_user_cynara_policy)
2230 {
2231     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2232     const char *const MAIN_BUCKET = "MAIN";
2233     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2234     const char *const ADMIN_BUCKET = "ADMIN";
2235     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2236     const std::string username("sm_test_10_user_cynara_policy");
2237     CynaraTestAdmin::Admin admin;
2238     std::string uid_string;
2239     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2240     user.create();
2241     user.getUidString(uid_string);
2242
2243     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2244     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2245     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2246
2247     user.remove();
2248     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2249
2250     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2251     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2252     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2253     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2254 }
2255
2256 RUNNER_CHILD_TEST(security_manager_19_security_manager_cmd_install)
2257 {
2258     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2259     int ret;
2260     const int SUCCESS = 0;
2261     const int FAILURE = 256;
2262     const std::string app_id = "security_manager_10_app";
2263     const std::string pkg_id = "security_manager_10_pkg";
2264     const std::string username("sm_test_10_user_name");
2265     std::string uid_string;
2266     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2267     user.create();
2268     user.getUidString(uid_string);
2269     const std::string path1 = appDirPath(user, app_id, pkg_id) + "/p1";
2270     const std::string path2 = appDirPath(user, app_id, pkg_id) + "/p2";
2271     const std::string pkgopt = " --pkg=" + pkg_id;
2272     const std::string appopt = " --app=" + app_id;
2273     const std::string uidopt = " --uid=" + uid_string;
2274
2275     mktreeSafe(path1.c_str(), 0);
2276     mktreeSafe(path2.c_str(), 0);
2277
2278     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2279
2280     struct operation {
2281         std::string command;
2282         int expected_result;
2283     };
2284     std::vector<struct operation> operations = {
2285             {"security-manager-cmd", FAILURE},//no option
2286             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2287             {"security-manager-cmd --help", SUCCESS},
2288             {"security-manager-cmd --install", FAILURE},//no params
2289             {"security-manager-cmd -i", FAILURE},//no params
2290             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2291             {installcmd, SUCCESS},
2292             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2293             {installcmd + " --path " + path1 + " rw", SUCCESS},
2294             {installcmd + " --path " + path1, FAILURE},//no path type
2295             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
2296             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
2297             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2298     };
2299
2300     for (auto &op : operations) {
2301         ret = system(op.command.c_str());
2302         RUNNER_ASSERT_MSG(ret == op.expected_result,
2303                 "Unexpected result for command '" << op.command <<"': "
2304                 << ret << " Expected was: "<< op.expected_result);
2305     }
2306 }
2307
2308 RUNNER_CHILD_TEST(security_manager_20_security_manager_cmd_users)
2309 {
2310     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2311     int ret;
2312     const int SUCCESS = 0;
2313     const int FAILURE = 256;
2314     const std::string username("sm_test_11_user_name");
2315     std::string uid_string;
2316     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2317     user.create();
2318     user.getUidString(uid_string);
2319     const std::string uidopt = " --uid=" + uid_string;
2320
2321     struct operation {
2322         std::string command;
2323         int expected_result;
2324     };
2325     std::vector<struct operation> operations = {
2326             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2327             {"security-manager-cmd -m", FAILURE},//no params
2328             {"security-manager-cmd -mr", FAILURE},//no uid
2329             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2330             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2331             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2332             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2333             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2334             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2335             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2336             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2337     };
2338
2339     for (auto &op : operations) {
2340         ret = system(op.command.c_str());
2341         RUNNER_ASSERT_MSG(ret == op.expected_result,
2342                 "Unexpected result for command '" << op.command <<"': "
2343                 << ret << " Expected was: "<< op.expected_result);
2344     }
2345 }
2346
2347 RUNNER_MULTIPROCESS_TEST(security_manager_21_security_manager_admin_deny_user_priv)
2348 {
2349     const int BUFFER_SIZE = 128;
2350     struct message {
2351         uid_t uid;
2352         gid_t gid;
2353         char buf[BUFFER_SIZE];
2354     } msg;
2355
2356     privileges_t admin_required_privs = {
2357             PRIVILEGE_MANAGER_SELF_PRIVILEGE,
2358             PRIVILEGE_MANAGER_ADMIN_PRIVILEGE};
2359     privileges_t manifest_privs = {
2360             "http://tizen.org/privilege/internet",
2361             "http://tizen.org/privilege/camera"};
2362     privileges_t real_privs_allow = {"http://tizen.org/privilege/camera"};
2363     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2364
2365     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2366     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2367     const std::string app_id = "sm_test_13_SOME_APP";
2368     const std::string pkg_id = "sm_test_13_SOME_PKG";
2369
2370     int pipefd[2];
2371     pid_t pid;
2372     int result = 0;
2373
2374     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2375     pid = fork();
2376     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2377     if (pid != 0)//parent process
2378     {
2379         std::string childuidstr;
2380         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, true);
2381         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, true);
2382
2383         InstallRequest request,request2;
2384         FdUniquePtr pipeptr(pipefd+1);
2385         close(pipefd[0]);
2386
2387         admin.create();
2388         child.create();
2389         child.getUidString(childuidstr);
2390
2391         //install privacy manager for admin
2392         request.setAppId(pirivman_id.c_str());
2393         request.setPkgId(pirivman_pkg_id.c_str());
2394         request.setUid(admin.getUid());
2395         for (auto &priv: admin_required_privs)
2396             request.addPrivilege(priv.c_str());
2397         Api::install(request);
2398
2399         //install app for child that has internet privilege
2400         request2.setAppId(app_id.c_str());
2401         request2.setPkgId(pkg_id.c_str());
2402         request2.setUid(child.getUid());
2403         for (auto &priv: manifest_privs)
2404             request2.addPrivilege(priv.c_str());
2405         Api::install(request2);
2406
2407         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2408                               manifest_privs, SM_NO_PRIVILEGES);
2409
2410         //send info to child
2411         msg.uid = admin.getUid();
2412         msg.gid = admin.getGid();
2413         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2414
2415         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2416         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2417
2418         waitPid(pid);
2419
2420         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2421                               real_privs_allow, real_privs_deny);
2422     }
2423     if (pid == 0)//child
2424     {
2425         FdUniquePtr pipeptr(pipefd);
2426         close(pipefd[1]);
2427
2428         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2429         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2430
2431         //become admin privacy manager manager
2432         Api::setProcessLabel(pirivman_id.c_str());
2433         result = drop_root_privileges(msg.uid, msg.gid);
2434         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2435         PolicyRequest addPolicyReq;
2436         //change rights
2437         for (auto &denypriv:real_privs_deny) {
2438             /*this entry will deny some privileges for user whose uid (as c string)
2439               was sent in message's buf field.
2440               That user would be denying internet for child in this case*/
2441             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2442             entry.setMaxLevel("Deny");
2443             addPolicyReq.addEntry(entry);
2444         }
2445         Api::sendPolicy(addPolicyReq);
2446         exit(0);
2447     }
2448 }
2449
2450 namespace {
2451 const int sm_app_shared_test_id = 27;
2452 const char *const sm_app_shared_id = "sm_test_27_app_id_full";
2453 const char *const sm_app_shared_another_in_package_id = "sm_test_27_app_2_id_full";
2454 const char *const sm_pkg_shared_id = "sm_test_27_pkg_id_full";
2455
2456 void test_success_worker(const std::string &appName, int test_num)
2457 {
2458     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2459
2460     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2461
2462     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1,
2463         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName << " failed " << " to " << SM_OWNER_RW_OTHERS_RO_PATH );
2464 }
2465
2466 void test_fail_worker(const std::string &appName, int test_num)
2467 {
2468     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2469
2470     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2471
2472     RUNNER_ASSERT_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) == -1,
2473         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName
2474         << " surprisingly succeeded, while expecting fail");
2475 }
2476 }
2477
2478 RUNNER_TEST(security_manager_27a_API2X_app_install)
2479 {
2480     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2481     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2482     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2483     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2484     prepare_app_env(sm_app_shared_test_id, true);
2485
2486     // install other apps
2487     for(const auto &app : MANY_APPS_PKGS) {
2488         InstallRequest requestInst;
2489         requestInst.setAppId(app.first.c_str());
2490         requestInst.setPkgId(app.second.package.c_str());
2491         requestInst.setAppTizenVersion(app.second.Tizen_ver.c_str());
2492
2493         Api::install(requestInst);
2494     };
2495
2496     // install
2497     {
2498         InstallRequest requestInst;
2499         requestInst.setAppId(sm_app_shared_id);
2500         requestInst.setPkgId(sm_pkg_shared_id);
2501         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2502         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2503         requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2504         requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2505         requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2506         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2507         requestInst.setAppTizenVersion("2.4");
2508         Api::install(requestInst);
2509     }
2510
2511     // another app in package
2512     {
2513         InstallRequest requestInst;
2514         requestInst.setAppId(sm_app_shared_another_in_package_id);
2515         requestInst.setPkgId(sm_pkg_shared_id);
2516         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2517         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2518         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2519         requestInst.setAppTizenVersion("2.4");
2520         Api::install(requestInst);
2521     }
2522
2523     /* Check records in the security-manager database */
2524     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2525                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2526     /* Check records in the security-manager database */
2527     check_app_after_install(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2528                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2529
2530     /* TODO: add parameters to this function */
2531     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2532
2533     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1, "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") failed");
2534 }
2535
2536 RUNNER_CHILD_TEST(security_manager_27b_owner_1_have_access)
2537 {
2538     test_success_worker(sm_app_shared_id, sm_app_shared_test_id);
2539 }
2540
2541 RUNNER_CHILD_TEST(security_manager_27c_owner_2_have_access)
2542 {
2543     test_success_worker(sm_app_shared_another_in_package_id, sm_app_shared_test_id);
2544 }
2545
2546 RUNNER_CHILD_TEST(security_manager_27d_API2X_apps_have_access_app_1)
2547 {
2548     test_success_worker("security_manager_10_app_1", sm_app_shared_test_id);
2549 }
2550
2551 RUNNER_CHILD_TEST(security_manager_27e_API2X_apps_dont_have_access_app_2)
2552 {
2553     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2554 }
2555
2556 RUNNER_CHILD_TEST(security_manager_27f_API2X_apps_have_access_app_3)
2557 {
2558     test_success_worker("security_manager_10_app_3", sm_app_shared_test_id);
2559 }
2560
2561 RUNNER_CHILD_TEST(security_manager_27g_API2X_apps_dont_have_access_app_4)
2562 {
2563     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2564 }
2565
2566 RUNNER_CHILD_TEST(security_manager_27h_API2X_apps_have_access_app_5)
2567 {
2568     test_success_worker("security_manager_10_app_5", sm_app_shared_test_id);
2569 }
2570
2571
2572 RUNNER_TEST(security_manager_27i_API2X_app_uninstall)
2573 {
2574     {
2575         InstallRequest requestUninst;
2576         requestUninst.setAppId(sm_app_shared_id);
2577         Api::uninstall(requestUninst);
2578     }
2579     {
2580         InstallRequest requestUninst;
2581         requestUninst.setAppId(sm_app_shared_another_in_package_id);
2582         Api::uninstall(requestUninst);
2583     }
2584
2585     /* Check records in the security-manager database,
2586      * all previously allowed privileges should be removed */
2587     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2588                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2589     check_app_after_uninstall(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2590                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2591 }
2592
2593 RUNNER_TEST(security_manager_27j_API30_app_install)
2594 {
2595     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2596     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2597     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2598     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2599     prepare_app_env(sm_app_shared_test_id, true);
2600
2601     // install
2602     InstallRequest requestInst;
2603     requestInst.setAppId(sm_app_shared_id);
2604     requestInst.setPkgId(sm_pkg_shared_id);
2605     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2606     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2607     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2608     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2609     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2610     requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2611     requestInst.setAppTizenVersion("3.0");
2612
2613     Api::install(requestInst);
2614
2615     /* Check records in the security-manager database */
2616     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2617                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2618
2619     /* TODO: add parameters to this function */
2620     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2621
2622     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1, "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") failed");
2623 }
2624
2625 RUNNER_CHILD_TEST(security_manager_27k_API30_apps_dont_have_access_app_1)
2626 {
2627     test_fail_worker("security_manager_10_app_1", sm_app_shared_test_id);
2628 }
2629
2630 RUNNER_CHILD_TEST(security_manager_27l_API30_apps_dont_have_access_app_2)
2631 {
2632     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2633 }
2634
2635 RUNNER_CHILD_TEST(security_manager_27m_API30_apps_dont_have_access_app_3)
2636 {
2637     test_fail_worker("security_manager_10_app_3", sm_app_shared_test_id);
2638 }
2639
2640 RUNNER_CHILD_TEST(security_manager_27n_API30_apps_dont_have_access_app_4)
2641 {
2642     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2643 }
2644
2645 RUNNER_CHILD_TEST(security_manager_27o_API30_apps_dont_have_access_app_5)
2646 {
2647     test_fail_worker("security_manager_10_app_5", sm_app_shared_test_id);
2648 }
2649
2650 RUNNER_TEST(security_manager_27p_API30_app_uninstall)
2651 {
2652     InstallRequest requestUninst;
2653     requestUninst.setAppId(sm_app_shared_id);
2654
2655     Api::uninstall(requestUninst);
2656
2657     /* Check records in the security-manager database,
2658      * all previously allowed privileges should be removed */
2659     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2660                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2661
2662     // install other apps
2663     for(const auto &app : MANY_APPS_PKGS) {
2664         InstallRequest requestUninst;
2665         requestUninst.setAppId(app.first);
2666
2667         Api::uninstall(requestUninst);
2668     };
2669 }
2670
2671 namespace {
2672 const char *const owner_access = "rwxat";
2673 const char *const target_path_access = "rxl";
2674 const char *const target_dir_access = "x";
2675 const char *const no_access = "";
2676
2677 void check_system_access(const std::string pathLabel, bool apply = true) {
2678     check_exact_smack_accesses("User", pathLabel, (apply ? owner_access : no_access));
2679     check_exact_smack_accesses("System", pathLabel, (apply ? owner_access : no_access));
2680 }
2681
2682 void check_owner_access(const std::string &ownerLabel, const std::string &pathLabel, bool apply = true) {
2683     check_exact_smack_accesses(ownerLabel, pathLabel, (apply ? owner_access : no_access));
2684 }
2685
2686 void check_target_access(const std::string &ownerPkgLabel, const std::string &targetLabel,
2687         const std::string &pathLabel, bool pathShared = true, bool anyPathShared = true) {
2688     check_exact_smack_accesses(targetLabel, pathLabel, (pathShared ? target_path_access : no_access));
2689     check_exact_smack_accesses(targetLabel, ownerPkgLabel, (anyPathShared ? target_dir_access : no_access));
2690 }
2691
2692 void check_path_label(const std::string &path, const std::string &expectedLabel) {
2693     char *label = nullptr;
2694     int ret = smack_new_label_from_path(path.c_str(), XATTR_NAME_SMACK, 0, &label);
2695     RUNNER_ASSERT_MSG(ret > 0, "smack_new_label_from_path failed for " << path);
2696     SmackLabelPtr realLabel(label);
2697     RUNNER_ASSERT_MSG(realLabel.get() == expectedLabel, "Fetched label from " << path << " different"
2698             " than expected, is : " << realLabel.get() << " should be " << expectedLabel);
2699 }
2700
2701 void createFile(const std::string &filePath)
2702 {
2703     //create temporary file and set label for it
2704     mode_t systemMask;
2705
2706     unlink(filePath.c_str());
2707     //allow to create file with 777 rights
2708     systemMask = umask(0000);
2709     int fd = open(filePath.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
2710     //restore system mask
2711     umask(systemMask);
2712     RUNNER_ASSERT_ERRNO_MSG(fd > -1, "Unable to create file for tests");
2713
2714     //for descriptor protection
2715     FdUniquePtr fd_ptr(&fd);
2716
2717     //change owner and group to user APP
2718     int ret = chown(filePath.c_str(), APP_UID, APP_GID);
2719     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "Unable to change file owner");
2720 }
2721
2722 }
2723
2724 RUNNER_TEST(security_manager_30a_send_incomplete_req1)
2725 {
2726     SharingRequest request;
2727     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2728     request.setOwnerAppId("someOwner");
2729     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2730     request.setTargetAppId("someTarget");
2731     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2732 }
2733
2734 RUNNER_TEST(security_manager_30b_send_incomplete_req2)
2735 {
2736     SharingRequest request;
2737     request.setTargetAppId("someTarget");
2738     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2739     request.setOwnerAppId("someOwner");
2740     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2741 }
2742
2743 RUNNER_TEST(security_manager_30c_send_incomplete_req3)
2744 {
2745     SharingRequest request;
2746     const char *somePaths[] = {"path1", "path2"};
2747     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2748     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2749     request.setOwnerAppId("someOwner");
2750     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2751 }
2752
2753 RUNNER_TEST(security_manager_30d_unknown_owner)
2754 {
2755     // This test depends on order of checks in security-manager service implementation
2756     SharingRequest request;
2757     request.setOwnerAppId("ImPrettySureIDontExist");
2758     request.setTargetAppId("IDontMatter");
2759     const char *somePaths[] = {"path1", "path2"};
2760     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2761     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2762 }
2763
2764 RUNNER_TEST(security_manager_30e_unknown_target)
2765 {
2766     // This test depends on order of checks in security-manager service implementation
2767     AppInstallHelper owner("installedApp");
2768     owner.revokeRules();
2769     owner.createInstallDir();
2770     InstallRequest ownerInst;
2771     ownerInst.setAppId(owner.getAppId());
2772     ownerInst.setPkgId(owner.getPkgId());
2773     Api::install(ownerInst);
2774
2775     SharingRequest request;
2776     request.setOwnerAppId(owner.getAppId());
2777     request.setTargetAppId("NowImPrettySureIDontExist");
2778     const char *somePaths[] = {"path1", "path2"};
2779     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2780     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2781
2782     Api::uninstall(ownerInst);
2783 }
2784
2785 RUNNER_TEST(security_manager_30f_bad_paths)
2786 {
2787     // This test depends on order of checks in security-manager service implementation
2788     AppInstallHelper owner("installedApp");
2789     owner.revokeRules();
2790     owner.createInstallDir();
2791     InstallRequest ownerInst;
2792     ownerInst.setAppId(owner.getAppId());
2793     ownerInst.setPkgId(owner.getPkgId());
2794     Api::install(ownerInst);
2795
2796     AppInstallHelper target("secondInstalledApp");
2797     target.revokeRules();
2798     target.createInstallDir();
2799     InstallRequest targetInst;
2800     targetInst.setAppId(target.getAppId());
2801     targetInst.setPkgId(target.getPkgId());
2802     Api::install(targetInst);
2803
2804     SharingRequest request;
2805     request.setOwnerAppId(owner.getAppId());
2806     request.setTargetAppId(target.getAppId());
2807
2808     const char *somePath = "/tmp/somePath";
2809     createFile(somePath);
2810     const char *somePaths[] = {somePath};
2811     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2812     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_NOT_PATH_OWNER);
2813
2814     Api::uninstall(ownerInst);
2815     Api::uninstall(targetInst);
2816 }
2817
2818 RUNNER_TEST(security_manager_31_simple_share)
2819 {
2820     std::vector<AppInstallHelper> helper {{"app30a"}, {"app30b"}};
2821     auto &owner = helper[0];
2822     auto &target = helper[1];
2823
2824     for (auto &e : helper) {
2825         e.revokeRules();
2826         e.createInstallDir();
2827     }
2828
2829     owner.createPrivateDir();
2830     owner.createSharedFile();
2831
2832     InstallRequest ownerReq;
2833     ownerReq.setAppId(owner.getAppId());
2834     ownerReq.setPkgId(owner.getPkgId());
2835     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
2836     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
2837     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
2838     Api::install(ownerReq);
2839
2840     InstallRequest targetReq;
2841     targetReq.setAppId(target.getAppId());
2842     targetReq.setPkgId(target.getAppId());
2843     Api::install(targetReq);
2844
2845     SharingRequest share1;
2846     std::string sharedPath = owner.getSharedPath();
2847     share1.setOwnerAppId(owner.getAppId());
2848     share1.setTargetAppId(target.getAppId());
2849     const char *path[] = {sharedPath.c_str()};
2850     share1.addPaths(path, 1);
2851     Api::applySharing(share1);
2852
2853     TestSecurityManagerDatabase db;
2854     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
2855     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
2856
2857     check_system_access(pathLabel1);
2858     check_owner_access(owner.generateAppLabel(), pathLabel1);
2859     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
2860     check_path_label(sharedPath, pathLabel1);
2861
2862     Api::dropSharing(share1);
2863     check_system_access(pathLabel1, false);
2864     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
2865     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
2866     check_path_label(sharedPath, owner.generatePkgLabel());
2867
2868     Api::uninstall(ownerReq);
2869     Api::uninstall(targetReq);
2870 }
2871
2872 RUNNER_TEST(security_manager_32_double_share)
2873 {
2874     std::vector<AppInstallHelper> helper {{"app31a"}, {"app31b"}};
2875     auto &owner = helper[0];
2876     auto &target = helper[1];
2877
2878     // cleanup
2879     for (auto &e : helper) {
2880         e.revokeRules();
2881         e.createInstallDir();
2882     }
2883     owner.createPrivateDir();
2884     owner.createSharedFile();
2885
2886     InstallRequest ownerReq;
2887     ownerReq.setAppId(owner.getAppId());
2888     ownerReq.setPkgId(owner.getPkgId());
2889     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
2890
2891     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
2892     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
2893     Api::install(ownerReq);
2894
2895     InstallRequest targetReq;
2896     targetReq.setAppId(target.getAppId());
2897     targetReq.setPkgId(target.getAppId());
2898     Api::install(targetReq);
2899
2900     SharingRequest share1;
2901     std::string sharedPath = owner.getSharedPath(0);
2902     share1.setOwnerAppId(owner.getAppId());
2903     share1.setTargetAppId(target.getAppId());
2904     const char *path[] = {sharedPath.c_str()};
2905     share1.addPaths(path, 1);
2906     Api::applySharing(share1);
2907
2908     TestSecurityManagerDatabase db;
2909     std::string pathLabel = db.get_path_label(sharedPath.c_str());
2910     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
2911
2912     check_system_access(pathLabel);
2913     check_owner_access(owner.generateAppLabel(), pathLabel);
2914     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
2915     check_path_label(sharedPath, pathLabel);
2916
2917     Api::applySharing(share1);
2918     check_system_access(pathLabel);
2919     check_owner_access(owner.generateAppLabel(), pathLabel);
2920     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
2921     check_path_label(sharedPath, pathLabel);
2922
2923     Api::dropSharing(share1);
2924     check_system_access(pathLabel);
2925     check_owner_access(owner.generateAppLabel(), pathLabel);
2926     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
2927     check_path_label(sharedPath, pathLabel);
2928
2929     Api::dropSharing(share1);
2930     check_system_access(pathLabel, false);
2931     check_owner_access(owner.generateAppLabel(), pathLabel, false);
2932     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel, false, false);
2933     check_path_label(sharedPath, owner.generatePkgLabel());
2934
2935     Api::uninstall(ownerReq);
2936     Api::uninstall(targetReq);
2937 }
2938 RUNNER_TEST(security_manager_33_share_two_with_one)
2939 {
2940     std::vector<AppInstallHelper> helper {{"app32a"}, {"app32b"}};
2941     auto &owner = helper[0];
2942     auto &target = helper[1];
2943
2944     // cleanup
2945     for (auto &e : helper) {
2946         e.revokeRules();
2947         e.createInstallDir();
2948     }
2949     owner.createPrivateDir();
2950     owner.createSharedFile(0);
2951     owner.createSharedFile(1);
2952
2953     InstallRequest ownerReq;
2954     ownerReq.setAppId(owner.getAppId());
2955     ownerReq.setPkgId(owner.getPkgId());
2956     ownerReq.addPath(owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW);
2957     ownerReq.addPath(owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW);
2958
2959     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
2960     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
2961     Api::install(ownerReq);
2962
2963     InstallRequest targetReq;
2964     targetReq.setAppId(target.getAppId());
2965     targetReq.setPkgId(target.getAppId());
2966     Api::install(targetReq);
2967
2968     SharingRequest share1, share2;
2969     std::string sharedPath1 = owner.getSharedPath(0);
2970     std::string sharedPath2 = owner.getSharedPath(1);
2971     share1.setOwnerAppId(owner.getAppId());
2972     share2.setOwnerAppId(owner.getAppId());
2973     share1.setTargetAppId(target.getAppId());
2974     share2.setTargetAppId(target.getAppId());
2975     const char *path1[] = {sharedPath1.c_str()};
2976     const char *path2[] = {sharedPath2.c_str()};
2977     share1.addPaths(path1, 1);
2978     share2.addPaths(path2, 1);
2979
2980     Api::applySharing(share1);
2981     TestSecurityManagerDatabase db;
2982     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
2983     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
2984
2985     check_system_access(pathLabel1);
2986     check_owner_access(owner.generateAppLabel(), pathLabel1);
2987     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
2988     check_path_label(sharedPath1, pathLabel1);
2989
2990     Api::applySharing(share2);
2991     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
2992     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
2993     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for private shared paths should be unique!");
2994
2995     check_system_access(pathLabel1);
2996     check_system_access(pathLabel2);
2997     check_owner_access(owner.generateAppLabel(), pathLabel1);
2998     check_owner_access(owner.generateAppLabel(), pathLabel2);
2999     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3000     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3001     check_path_label(sharedPath1, pathLabel1);
3002     check_path_label(sharedPath2, pathLabel2);
3003
3004     Api::dropSharing(share1);
3005     check_system_access(pathLabel1, false);
3006     check_system_access(pathLabel2);
3007     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3008     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false);
3009     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3010     check_path_label(sharedPath1, owner.generatePkgLabel());
3011     check_path_label(sharedPath2, pathLabel2);
3012
3013     Api::dropSharing(share2);
3014     check_system_access(pathLabel1, false);
3015     check_system_access(pathLabel2, false);
3016     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3017     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3018     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3019     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2, false, false);
3020     check_path_label(sharedPath1, owner.generatePkgLabel());
3021     check_path_label(sharedPath2, owner.generatePkgLabel());
3022
3023     Api::uninstall(ownerReq);
3024     Api::uninstall(targetReq);
3025 }
3026
3027 RUNNER_TEST(security_manager_34_share_one_with_two)
3028 {
3029     std::vector<AppInstallHelper> helper {{"app33a"}, {"app33b"}, {"app33c"}};
3030     auto &owner = helper[0];
3031     auto &target1 = helper[1];
3032     auto &target2 = helper[2];
3033
3034     // cleanup
3035     for (auto &e : helper) {
3036         e.revokeRules();
3037         e.createInstallDir();
3038     }
3039     owner.createPrivateDir();
3040     owner.createSharedFile();
3041
3042     InstallRequest ownerReq;
3043     ownerReq.setAppId(owner.getAppId());
3044     ownerReq.setPkgId(owner.getPkgId());
3045     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
3046     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3047     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3048     Api::install(ownerReq);
3049
3050     for (size_t i = 1; i < helper.size(); i++) {
3051         InstallRequest targetReq;
3052         targetReq.setAppId(helper[i].getAppId());
3053         targetReq.setPkgId(helper[i].getAppId());
3054         Api::install(targetReq);
3055     }
3056
3057     SharingRequest share1, share2;
3058     std::string sharedPath = owner.getSharedPath(0).c_str();
3059     share1.setOwnerAppId(owner.getAppId());
3060     share2.setOwnerAppId(owner.getAppId());
3061     share1.setTargetAppId(target1.getAppId());
3062     share2.setTargetAppId(target2.getAppId());
3063
3064     const char *path[] = {sharedPath.c_str()};
3065     share1.addPaths(path, 1);
3066     share2.addPaths(path, 1);
3067
3068     Api::applySharing(share1);
3069     TestSecurityManagerDatabase db;
3070     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3071     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3072
3073     check_system_access(pathLabel);
3074     check_owner_access(owner.generateAppLabel(), pathLabel);
3075     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3076     check_path_label(sharedPath, pathLabel);
3077
3078     Api::applySharing(share2);
3079     check_system_access(pathLabel);
3080     check_owner_access(owner.generateAppLabel(), pathLabel);
3081     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3082     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3083     check_path_label(sharedPath, pathLabel);
3084
3085     Api::dropSharing(share1);
3086     check_system_access(pathLabel);
3087     check_owner_access(owner.generateAppLabel(), pathLabel);
3088     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3089     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3090     check_path_label(sharedPath, pathLabel);
3091
3092     Api::dropSharing(share2);
3093     check_system_access(pathLabel, false);
3094     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3095     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3096     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel, false, false);
3097     check_path_label(sharedPath, owner.generatePkgLabel());
3098
3099     Api::uninstall(ownerReq);
3100     for (size_t i = 1; i < helper.size(); i++) {
3101         InstallRequest targetReq;
3102         targetReq.setAppId(helper[i].getAppId());
3103         targetReq.setPkgId(helper[i].getAppId());
3104         Api::uninstall(targetReq);
3105     }
3106 }
3107
3108 RUNNER_TEST(security_manager_35_share_two_with_two)
3109 {
3110     std::vector<AppInstallHelper> helper {{"app34a"}, {"app34b"}, {"app34c"}};
3111     auto &owner = helper[0];
3112     auto &target1 = helper[1];
3113     auto &target2 = helper[2];
3114
3115     // cleanup
3116     for (auto &e : helper) {
3117         e.revokeRules();
3118         e.createInstallDir();
3119     }
3120     owner.createPrivateDir();
3121     owner.createSharedFile(0);
3122     owner.createSharedFile(1);
3123
3124     InstallRequest ownerReq;
3125     ownerReq.setAppId(owner.getAppId());
3126     ownerReq.setPkgId(owner.getPkgId());
3127     ownerReq.addPath(owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW);
3128     ownerReq.addPath(owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW);
3129
3130     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3131     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3132     Api::install(ownerReq);
3133
3134     for (size_t i = 1; i < helper.size(); i++) {
3135         InstallRequest targetReq;
3136         targetReq.setAppId(helper[i].getAppId());
3137         targetReq.setPkgId(helper[i].getAppId());
3138         Api::install(targetReq);
3139     }
3140
3141     SharingRequest share1, share2;
3142     std::string sharedPath1 = owner.getSharedPath(0).c_str();
3143     std::string sharedPath2 = owner.getSharedPath(1).c_str();
3144     share1.setOwnerAppId(owner.getAppId());
3145     share2.setOwnerAppId(owner.getAppId());
3146     share1.setTargetAppId(target1.getAppId());
3147     share2.setTargetAppId(target2.getAppId());
3148
3149     const char *path1[] = {sharedPath1.c_str()};
3150     const char *path2[] = {sharedPath2.c_str()};
3151     share1.addPaths(path1, 1);
3152     share2.addPaths(path2, 1);
3153
3154     Api::applySharing(share1);
3155     TestSecurityManagerDatabase db;
3156     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3157     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3158
3159     check_system_access(pathLabel1);
3160     check_owner_access(owner.generateAppLabel(), pathLabel1);
3161     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3162     check_path_label(sharedPath1, pathLabel1);
3163
3164     Api::applySharing(share2);
3165     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3166     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3167     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for shared files should be unique!");
3168
3169     check_system_access(pathLabel1);
3170     check_system_access(pathLabel2);
3171     check_owner_access(owner.generateAppLabel(), pathLabel1);
3172     check_owner_access(owner.generateAppLabel(), pathLabel2);
3173     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3174     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2);
3175     check_path_label(sharedPath1, pathLabel1);
3176     check_path_label(sharedPath2, pathLabel2);
3177
3178     Api::dropSharing(share2);
3179     check_system_access(pathLabel1);
3180     check_system_access(pathLabel2, false);
3181     check_owner_access(owner.generateAppLabel(), pathLabel1);
3182     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3183     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3184     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3185     check_path_label(sharedPath1, pathLabel1);
3186     check_path_label(sharedPath2, owner.generatePkgLabel());
3187
3188     Api::dropSharing(share1);
3189     check_system_access(pathLabel1, false);
3190     check_system_access(pathLabel2, false);
3191     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3192     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3193     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1, false, false);
3194     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3195     check_path_label(sharedPath1, owner.generatePkgLabel());
3196     check_path_label(sharedPath2, owner.generatePkgLabel());
3197     Api::uninstall(ownerReq);
3198     for (size_t i = 1; i < helper.size(); i++) {
3199         InstallRequest targetReq;
3200         targetReq.setAppId(helper[i].getAppId());
3201         targetReq.setPkgId(helper[i].getAppId());
3202         Api::uninstall(targetReq);
3203     }
3204 }
3205
3206 RUNNER_TEST(security_manager_40_set_wrong_author_id)
3207 {
3208     InstallRequest requestInst;
3209
3210     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3211         security_manager_app_inst_req_set_author_id(requestInst.get(), NULL));
3212
3213     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3214         security_manager_app_inst_req_set_author_id(requestInst.get(), ""));
3215 }
3216
3217 RUNNER_TEST(security_manager_41_set_author_id_multiple_times)
3218 {
3219     for(unsigned int i=0; i<10; ++i) {
3220         std::string authorId = "some-author-id" + std::to_string(i);
3221
3222         InstallRequest requestInst;
3223         requestInst.setAuthorId(authorId);
3224     }
3225 }
3226
3227 RUNNER_TEST(security_manager_43_app_install_with_trusted_path)
3228 {
3229     std::vector<AppInstallHelper> helper {{"app43a"}, {"app43b"}, {"app43c"}};
3230     auto &provider  = helper[0];
3231     auto &user      = helper[1];
3232     auto &untrusted = helper[2];
3233
3234     TestSecurityManagerDatabase dbtest;
3235     const char *author_id = "custom_author_id_test 41";
3236
3237     const char *const trusted_access = "rwxatl";
3238     const char *const system_access = "rwxatl";
3239
3240     int result;
3241
3242     // cleanup
3243     for (auto &e : helper) {
3244         e.revokeRules();
3245         e.createInstallDir();
3246         e.createTrustedDir();
3247     }
3248
3249     result = nftw(provider.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3250     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_TRUSTED_PATH);
3251
3252     // install app with shared/trusted dir
3253     InstallRequest trustingApp;
3254     trustingApp.setAppId(provider.getAppId());
3255     trustingApp.setPkgId(provider.getPkgId());
3256     trustingApp.setAuthorId("author id to be overwritten");
3257     trustingApp.setAuthorId(author_id);
3258     trustingApp.addPath(provider.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3259     Api::install(trustingApp);
3260
3261     int64_t authorDb = dbtest.get_author_id(author_id);
3262     const std::string trusted_label = std::string("User::Author::") + std::to_string(authorDb);
3263
3264     // check trusted path label
3265     nftw_expected_label = trusted_label;
3266     nftw_expected_transmute = true;
3267     nftw_expected_exec = false;
3268
3269     // check labels
3270     result = nftw(provider.getTrustedDir().c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
3271     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_TRUSTED_PATH);
3272
3273     // check rules
3274     check_exact_access("System", trusted_label, system_access);
3275     check_exact_access("User", trusted_label, system_access);
3276     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, trusted_access);
3277     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3278
3279     // install trusted app
3280     InstallRequest trustedApp;
3281     trustedApp.setAppId(user.getAppId());
3282     trustedApp.setPkgId(user.getPkgId());
3283     trustedApp.setAuthorId(author_id);
3284     Api::install(trustedApp);
3285
3286     // check rules
3287     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3288     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3289
3290     // install untrusted app
3291     InstallRequest untrustedApp;
3292     untrustedApp.setAppId(untrusted.getAppId());
3293     untrustedApp.setPkgId(untrusted.getPkgId());
3294     Api::install(untrustedApp);
3295
3296     // check rules
3297     check_exact_access(generateAppLabel(untrusted.getAppId()), trusted_label, "");
3298     check_exact_access(generatePkgLabel(untrusted.getPkgId()), trusted_label, "");
3299
3300     // uninstall trusting app
3301     Api::uninstall(trustingApp);
3302
3303     // there's still one app with author id, rules should be kept
3304     check_exact_access("System", trusted_label, system_access);
3305     check_exact_access("User", trusted_label, system_access);
3306     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, "");
3307     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3308     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3309     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3310
3311     Api::uninstall(trustedApp);
3312
3313     // no more apps with author id
3314     check_exact_access("System", trusted_label, "");
3315     check_exact_access("User", trusted_label, "");
3316     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, "");
3317     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3318
3319     Api::uninstall(untrustedApp);
3320 }
3321
3322
3323 RUNNER_TEST(security_manager_44_app_install_with_trusted_path_no_author_id)
3324 {
3325     AppInstallHelper help("app44");
3326     help.createInstallDir();
3327     help.createTrustedDir();
3328
3329     // install app with shared/trusted dir but without authors id
3330     InstallRequest app;
3331     app.setAppId(help.getAppId());
3332     app.setPkgId(help.getPkgId());
3333     app.addPath(help.getTrustedDir(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3334     Api::install(app, SECURITY_MANAGER_ERROR_INPUT_PARAM);
3335 }
3336
3337 RUNNER_TEST(security_manager_45_test_authorId_identificator_creation)
3338 {
3339     std::vector<AppInstallHelper> helper {{"a45"}, {"b45"}};
3340     auto &trusted1 = helper[0];
3341     auto &trusted2 = helper[1];
3342
3343     TestSecurityManagerDatabase dbtest;
3344     const char *authorId1 = "custom_author_id_test a45";
3345     const char *authorId2 = "custom_author_id_test b45";
3346
3347     // cleanup
3348     for (auto &e : helper) {
3349         e.revokeRules();
3350         e.createInstallDir();
3351         e.createTrustedDir();
3352     }
3353
3354     // install app with shared/trusted dir
3355     InstallRequest trustingApp;
3356     trustingApp.setAppId(trusted1.getAppId());
3357     trustingApp.setPkgId(trusted1.getPkgId());
3358     trustingApp.setAuthorId(authorId1);
3359     trustingApp.addPath(trusted1.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3360     Api::install(trustingApp);
3361
3362     int64_t authorDb1 = dbtest.get_author_id(authorId1);
3363
3364     // install trusted app
3365     InstallRequest trustedApp;
3366     trustedApp.setAppId(trusted2.getAppId());
3367     trustedApp.setPkgId(trusted2.getPkgId());
3368     trustedApp.setAuthorId(authorId2);
3369     Api::install(trustedApp);
3370
3371     int64_t authorDb2 = dbtest.get_author_id(authorId2);
3372     RUNNER_ASSERT(authorDb1 != authorDb2);
3373 }
3374
3375 RUNNER_TEST(security_manager_46_pkgId_deinstalation_test)
3376 {
3377     /* Description:
3378      * Lets assume that app1 and app2 are part of pkg1.
3379      * Deinstalation of app1 mustnot remove rules:
3380      * System PKG1Label rwxatl
3381      * User PKGLabel rwxatl
3382      */
3383
3384     std::vector<AppInstallHelper> helper {{"a46"}, {"b46"}};
3385     auto &trusted1 = helper[0];
3386     auto &trusted2 = helper[1];
3387
3388     std::string authorId1 = "author46XYZ";
3389
3390     for (auto &e : helper) {
3391         e.revokeRules();
3392         e.createInstallDir();
3393         e.createTrustedDir();
3394     }
3395
3396     InstallRequest trustingApp;
3397     trustingApp.setAppId(trusted1.getAppId());
3398     trustingApp.setPkgId(trusted1.getPkgId());
3399     trustingApp.setAuthorId(authorId1);
3400     trustingApp.addPath(trusted1.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3401     Api::install(trustingApp);
3402
3403     InstallRequest trustingApp2;
3404     trustingApp2.setAppId(trusted2.getAppId());
3405     trustingApp2.setPkgId(trusted1.getPkgId()); // both apps will be part of same pkgId
3406     trustingApp2.setAuthorId(authorId1);
3407     Api::install(trustingApp2);
3408
3409     check_exact_access("System", generateAppLabel(trusted1.getAppId()), "rwxl");
3410     check_exact_access("User", generateAppLabel(trusted1.getAppId()), "rwxl");
3411     check_exact_access("System", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
3412     check_exact_access("User", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
3413     check_exact_access("System", generateAppLabel(trusted2.getAppId()), "rwxl");
3414     check_exact_access("User", generateAppLabel(trusted2.getAppId()), "rwxl");
3415
3416     Api::uninstall(trustingApp2);
3417
3418     check_exact_access("System", generateAppLabel(trusted1.getAppId()), "rwxl");
3419     check_exact_access("User", generateAppLabel(trusted1.getAppId()), "rwxl");
3420     check_exact_access("System", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
3421     check_exact_access("User", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
3422     check_exact_access("System", generateAppLabel(trusted2.getAppId()), "");
3423     check_exact_access("User", generateAppLabel(trusted2.getAppId()), "");
3424
3425     Api::uninstall(trustingApp);
3426
3427     check_exact_access("System", generateAppLabel(trusted1.getAppId()), "");
3428     check_exact_access("User", generateAppLabel(trusted1.getAppId()), "");
3429     check_exact_access("System", generatePkgLabel(trusted1.getPkgId()), "");
3430     check_exact_access("User", generatePkgLabel(trusted1.getPkgId()), "");
3431 }
3432
3433 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CREDENTIAL_API)
3434
3435 class ProcessCredentials {
3436 public:
3437     ProcessCredentials(const std::string &smackLabel) : m_label(smackLabel) {}
3438
3439     const std::string &label(void) const {
3440         return m_label;
3441     }
3442
3443     uid_t uid(void) const {
3444         return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
3445     }
3446
3447     gid_t gid(void) const {
3448         return PasswdAccess::gid("users");
3449     }
3450
3451 private:
3452     std::string m_label;
3453 };
3454
3455 pid_t runInChild(const std::function<void(void)> &process) {
3456     pid_t pid = fork();
3457     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
3458
3459     if (pid == 0) {
3460         process();
3461         exit(EXIT_SUCCESS);
3462     }
3463
3464     return pid;
3465 }
3466
3467 void udsServer(SynchronizationPipe &pipe, const struct sockaddr_un &sockaddr,
3468                const struct ProcessCredentials &peerCredentials) {
3469     SecurityServer::AccessProvider ap(peerCredentials.label());
3470     ap.applyAndSwithToUser(peerCredentials.uid(), peerCredentials.gid());
3471     pipe.claimChildEp();
3472
3473     int sock = UDSHelpers::createServer(&sockaddr);
3474     SockUniquePtr sockPtr(&sock);
3475     pipe.post();
3476     int clientSock = UDSHelpers::acceptClient(sock);
3477
3478     UDSHelpers::waitForDisconnect(clientSock);
3479 }
3480
3481 typedef std::function<void(int sock, pid_t pid)> SocketAssertionFn;
3482
3483 void clientTestTemplate(SocketAssertionFn assertion, const std::string &scope, const std::string &smackLabel) {
3484     const auto sockaddr = UDSHelpers::makeAbstractAddress("test_sm_" + scope + ".socket");
3485     const ProcessCredentials peerCredentials(smackLabel);
3486
3487     SynchronizationPipe pipe;
3488
3489     pid_t pid = runInChild(std::bind(udsServer, std::ref(pipe), std::cref(sockaddr),
3490                            std::cref(peerCredentials)));
3491
3492     pipe.claimParentEp();
3493     pipe.wait();
3494     int sock = UDSHelpers::createClient(&sockaddr);
3495     SockUniquePtr sockPtr(&sock);
3496
3497     assertion(sock, pid);
3498 }
3499
3500 RUNNER_CHILD_TEST(security_manager_51a_get_id_by_socket)
3501 {
3502     const char *const sm_app_id = "sm_test_51a_app";
3503     const char *const sm_pkg_id = "sm_test_51a_pkg";
3504
3505     InstallRequest requestInst;
3506     requestInst.setAppId(sm_app_id);
3507     requestInst.setPkgId(sm_pkg_id);
3508
3509     Api::install(requestInst);
3510
3511     std::string smackLabel = generateAppLabel(sm_app_id);
3512
3513     clientTestTemplate([&] (int sock, pid_t) {
3514         std::string rcvPkgId, rcvAppId;
3515         Api::getPkgIdBySocket(sock, &rcvPkgId, &rcvAppId);
3516         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
3517                           << "; expected = " << sm_pkg_id);
3518         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
3519                           << "; expected = " << sm_app_id);
3520     }, "tcsm27a", smackLabel);
3521
3522     InstallRequest requestUninst;
3523     requestUninst.setAppId(sm_app_id);
3524
3525     Api::uninstall(requestUninst);
3526 }
3527
3528 RUNNER_CHILD_TEST(security_manager_51b_get_id_by_socket)
3529 {
3530     const char *const sm_app_id = "sm_test_51b_app";
3531     const char *const sm_pkg_id = "sm_test_51b_pkg";
3532
3533     InstallRequest requestInst;
3534     requestInst.setAppId(sm_app_id);
3535     requestInst.setPkgId(sm_pkg_id);
3536
3537     Api::install(requestInst);
3538
3539     std::string smackLabel = generateAppLabel(sm_app_id);
3540
3541     clientTestTemplate([&] (int sock, pid_t) {
3542         std::string rcvPkgId, rcvAppId;
3543         Api::getPkgIdBySocket(sock + 1, &rcvPkgId, &rcvAppId, SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT);
3544     }, "tcsm27b", smackLabel);
3545
3546     InstallRequest requestUninst;
3547     requestUninst.setAppId(sm_app_id);
3548
3549     Api::uninstall(requestUninst);
3550 }
3551
3552 RUNNER_CHILD_TEST(security_manager_51c_get_id_by_socket)
3553 {
3554     const char *const sm_app_id = "sm_test_51c_app";
3555     const char *const sm_pkg_id = "sm_test_51c_pkg";
3556
3557     InstallRequest requestInst;
3558     requestInst.setAppId(sm_app_id);
3559     requestInst.setPkgId(sm_pkg_id);
3560
3561     Api::install(requestInst);
3562
3563     std::string smackLabel = generateAppLabel(sm_app_id);
3564
3565     clientTestTemplate([&] (int sock, pid_t) {
3566         std::string rcvPkgId;
3567         Api::getPkgIdBySocket(sock, &rcvPkgId, nullptr);
3568         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
3569                           << "; expected = " << sm_pkg_id);
3570     }, "tcsm27c", smackLabel);
3571
3572     InstallRequest requestUninst;
3573     requestUninst.setAppId(sm_app_id);
3574
3575     Api::uninstall(requestUninst);
3576 }
3577
3578 RUNNER_CHILD_TEST(security_manager_51d_get_id_by_socket)
3579 {
3580     const char *const sm_app_id = "sm_test_51d_app";
3581     const char *const sm_pkg_id = "sm_test_51d_pkg";
3582
3583     InstallRequest requestInst;
3584     requestInst.setAppId(sm_app_id);
3585     requestInst.setPkgId(sm_pkg_id);
3586
3587     Api::install(requestInst);
3588
3589     std::string smackLabel = generateAppLabel(sm_app_id);
3590
3591     clientTestTemplate([&] (int sock, pid_t) {
3592         std::string rcvAppId;
3593         Api::getPkgIdBySocket(sock, nullptr, &rcvAppId);
3594         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
3595                           << "; expected = " << sm_app_id);
3596     }, "tcsm27d", smackLabel);
3597
3598     InstallRequest requestUninst;
3599     requestUninst.setAppId(sm_app_id);
3600
3601     Api::uninstall(requestUninst);
3602 }
3603
3604 RUNNER_CHILD_TEST(security_manager_51e_get_id_by_socket)
3605 {
3606     const char *const sm_app_id = "sm_test_51e_app";
3607     const char *const sm_pkg_id = "sm_test_51e_pkg";
3608
3609     InstallRequest requestInst;
3610     requestInst.setAppId(sm_app_id);
3611     requestInst.setPkgId(sm_pkg_id);
3612
3613     Api::install(requestInst);
3614
3615     std::string smackLabel = generateAppLabel(sm_app_id);
3616
3617     clientTestTemplate([&] (int sock, pid_t) {
3618         Api::getPkgIdBySocket(sock, nullptr, nullptr, SECURITY_MANAGER_ERROR_INPUT_PARAM);
3619     }, "tcsm27e", smackLabel);
3620
3621     InstallRequest requestUninst;
3622     requestUninst.setAppId(sm_app_id);
3623
3624     Api::uninstall(requestUninst);
3625 }
3626
3627 RUNNER_CHILD_TEST(security_manager_52a_get_id_by_pid)
3628 {
3629     const char *const sm_app_id = "sm_test_52a_app";
3630     const char *const sm_pkg_id = "sm_test_52a_pkg";
3631
3632     InstallRequest requestInst;
3633     requestInst.setAppId(sm_app_id);
3634     requestInst.setPkgId(sm_pkg_id);
3635
3636     Api::install(requestInst);
3637
3638     std::string smackLabel = generateAppLabel(sm_app_id);
3639
3640     clientTestTemplate([&] (int, pid_t pid) {
3641         std::string rcvPkgId, rcvAppId;
3642         Api::getPkgIdByPid(pid, &rcvPkgId, &rcvAppId);
3643         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
3644                           << "; expected = " << sm_pkg_id);
3645         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
3646                           << "; expected = " << sm_app_id);
3647     }, "tcsm28a", smackLabel);
3648
3649     InstallRequest requestUninst;
3650     requestUninst.setAppId(sm_app_id);
3651
3652     Api::uninstall(requestUninst);
3653 }
3654
3655 RUNNER_CHILD_TEST(security_manager_52b_get_id_by_pid)
3656 {
3657     const char *const sm_app_id = "sm_test_52b_app";
3658     const char *const sm_pkg_id = "sm_test_52b_pkg";
3659
3660     InstallRequest requestInst;
3661     requestInst.setAppId(sm_app_id);
3662     requestInst.setPkgId(sm_pkg_id);
3663
3664     Api::install(requestInst);
3665
3666     std::string smackLabel = generateAppLabel(sm_app_id);
3667
3668     clientTestTemplate([&] (int, pid_t pid) {
3669         std::string rcvPkgId, rcvAppId;
3670         Api::getPkgIdByPid(pid + 1, &rcvPkgId, &rcvAppId, SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT);
3671     }, "tcsm28b", smackLabel);
3672
3673     InstallRequest requestUninst;
3674     requestUninst.setAppId(sm_app_id);
3675
3676     Api::uninstall(requestUninst);
3677 }
3678
3679 RUNNER_CHILD_TEST(security_manager_52c_get_id_by_pid)
3680 {
3681     const char *const sm_app_id = "sm_test_52c_app";
3682     const char *const sm_pkg_id = "sm_test_52c_pkg";
3683
3684     InstallRequest requestInst;
3685     requestInst.setAppId(sm_app_id);
3686     requestInst.setPkgId(sm_pkg_id);
3687
3688     Api::install(requestInst);
3689
3690     std::string smackLabel = generateAppLabel(sm_app_id);
3691
3692     clientTestTemplate([&] (int, pid_t pid) {
3693         std::string rcvPkgId;
3694         Api::getPkgIdByPid(pid, &rcvPkgId, nullptr);
3695         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
3696                           << "; expected = " << sm_pkg_id);
3697     }, "tcsm28c", smackLabel);
3698
3699     InstallRequest requestUninst;
3700     requestUninst.setAppId(sm_app_id);
3701
3702     Api::uninstall(requestUninst);
3703 }
3704
3705 RUNNER_CHILD_TEST(security_manager_52d_get_id_by_pid)
3706 {
3707     const char *const sm_app_id = "sm_test_52d_app";
3708     const char *const sm_pkg_id = "sm_test_52d_pkg";
3709
3710     InstallRequest requestInst;
3711     requestInst.setAppId(sm_app_id);
3712     requestInst.setPkgId(sm_pkg_id);
3713
3714     Api::install(requestInst);
3715
3716     std::string smackLabel = generateAppLabel(sm_app_id);
3717
3718     clientTestTemplate([&] (int, pid_t pid) {
3719         std::string rcvAppId;
3720         Api::getPkgIdByPid(pid, nullptr, &rcvAppId);
3721         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
3722                           << "; expected = " << sm_app_id);
3723     }, "tcsm28d", smackLabel);
3724
3725     InstallRequest requestUninst;
3726     requestUninst.setAppId(sm_app_id);
3727
3728     Api::uninstall(requestUninst);
3729 }
3730
3731 RUNNER_CHILD_TEST(security_manager_52e_get_id_by_pid)
3732 {
3733     const char *const sm_app_id = "sm_test_52e_app";
3734     const char *const sm_pkg_id = "sm_test_52e_pkg";
3735
3736     InstallRequest requestInst;
3737     requestInst.setAppId(sm_app_id);
3738     requestInst.setPkgId(sm_pkg_id);
3739
3740     Api::install(requestInst);
3741
3742     std::string smackLabel = generateAppLabel(sm_app_id);
3743
3744     clientTestTemplate([&] (int sock, pid_t) {
3745         Api::getPkgIdByPid(sock, nullptr, nullptr, SECURITY_MANAGER_ERROR_INPUT_PARAM);
3746     }, "tcsm28e", smackLabel);
3747
3748     InstallRequest requestUninst;
3749     requestUninst.setAppId(sm_app_id);
3750
3751     Api::uninstall(requestUninst);
3752 }
3753
3754 RUNNER_CHILD_TEST(security_manager_53_app_has_privilege)
3755 {
3756     const char *const sm_app_id = "sm_test_53_app";
3757     const char *const sm_pkg_id = "sm_test_53_pkg";
3758     const std::string new_user_name = "sm_test_47_user_name";
3759
3760     InstallRequest requestInst;
3761     requestInst.setAppId(sm_app_id);
3762     requestInst.setPkgId(sm_pkg_id);
3763     for (auto const &privilege : SM_ALLOWED_PRIVILEGES)
3764         requestInst.addPrivilege(privilege.c_str());
3765     Api::install(requestInst);
3766
3767     for (auto const &privilege : SM_ALLOWED_PRIVILEGES) {
3768         int result;
3769         Api::appHasPrivilege(sm_app_id, privilege.c_str(), getGlobalUserId(), result);
3770         RUNNER_ASSERT_MSG(result == 1, "Application " << sm_app_id <<
3771             " should have access to privilege " << privilege);
3772     }
3773
3774     for (auto const &privilege : SM_DENIED_PRIVILEGES) {
3775         int result;
3776         Api::appHasPrivilege(sm_app_id, privilege.c_str(), getGlobalUserId(), result);
3777         RUNNER_ASSERT_MSG(result == 0, "Application " << sm_app_id <<
3778             " should not have access to privilege " << privilege);
3779     }
3780
3781     InstallRequest requestUninst;
3782     requestUninst.setAppId(sm_app_id);
3783     Api::uninstall(requestUninst);
3784 }
3785
3786 void setupPrivilegeGroups(const privileges_t &privileges, const std::vector<std::string> &groups)
3787 {
3788     TestSecurityManagerDatabase db;
3789     for (const auto &privilege : privileges) {
3790         db.setup_privilege_groups(privilege, groups);
3791     }
3792 }
3793
3794 std::vector<std::string> readPrivilegeGroups()
3795 {
3796     std::vector<std::string> groups;
3797     const static std::string privilegeGroupMappingPath("/usr/share/security-manager/policy/privilege-group.list");
3798     std::ifstream mappingFile(privilegeGroupMappingPath);
3799
3800     RUNNER_ASSERT_MSG(mappingFile.is_open(),
3801         "Unable to read group mapping file " << privilegeGroupMappingPath);
3802
3803     std::string line;
3804     std::regex r("^[^ #]+ +(.*)");
3805     while (std::getline(mappingFile, line)) {
3806         std::smatch m;
3807         if (std::regex_search(line, m, r))
3808             groups.push_back(m[1]);
3809     }
3810
3811     return groups;
3812 }
3813
3814 RUNNER_TEST(security_manager_48_groups_get)
3815 {
3816     setupPrivilegeGroups(SM_ALLOWED_PRIVILEGES, SM_ALLOWED_GROUPS);
3817
3818     std::unordered_set<std::string> groups;
3819     auto tmp = readPrivilegeGroups();
3820     groups.insert(tmp.begin(), tmp.end());
3821     groups.insert(SM_ALLOWED_GROUPS.begin(), SM_ALLOWED_GROUPS.end());
3822
3823     char ** c_groups;
3824     size_t count = 0;
3825
3826     Api::getSecurityManagerGroups(&c_groups, &count);
3827     RUNNER_ASSERT_MSG(count == groups.size(), "security_manager_groups_get should set count to: "
3828                       << groups.size() << " but count is: " << count);
3829
3830     for (const auto &group : groups) {
3831         bool found = false;
3832         for (size_t i = 0; i < count; ++i) {
3833             if (group == c_groups[i]) {
3834                 found = true;
3835                 break;
3836             }
3837         }
3838         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
3839     }
3840     security_manager_groups_free(c_groups, count);
3841 }
3842
3843 int main(int argc, char *argv[])
3844 {
3845     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
3846 }