Tests for new structure of application file paths
[platform/core/test/security-tests.git] / tests / security-manager-tests / security_manager_tests.cpp
1 #include <dpl/log/log.h>
2 #include <dpl/test/test_runner.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <memory.h>
6 #include <string>
7 #include <unordered_set>
8 #include <sys/capability.h>
9 #include <semaphore.h>
10
11 #include <unistd.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 #include <attr/xattr.h>
17 #include <linux/xattr.h>
18
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22
23 #include <grp.h>
24 #include <pwd.h>
25
26 #include <libprivilege-control_test_common.h>
27 #include <tests_common.h>
28
29 #include <tzplatform_config.h>
30 #include <security-manager.h>
31 #include <sm_api.h>
32 #include <sm_db.h>
33 #include <sm_request.h>
34 #include <sm_user_request.h>
35 #include <temp_test_user.h>
36 #include <cynara_test_client.h>
37 #include <cynara_test_admin.h>
38 #include <service_manager.h>
39 #include <cynara_test_admin.h>
40
41 using namespace SecurityManagerTest;
42
43 DEFINE_SMARTPTR(cap_free, _cap_struct, CapsSetsUniquePtr);
44 DEFINE_SMARTPTR(tzplatform_context_destroy, tzplatform_context, TzPlatformContextPtr);
45
46 static const privileges_t SM_ALLOWED_PRIVILEGES = {
47     "http://tizen.org/privilege/location",
48     "http://tizen.org/privilege/camera"
49 };
50
51 static const privileges_t SM_DENIED_PRIVILEGES  = {
52     "http://tizen.org/privilege/bluetooth",
53     "http://tizen.org/privilege/power"
54 };
55
56 static const privileges_t SM_NO_PRIVILEGES  = {
57 };
58
59 static const std::vector<std::string> SM_ALLOWED_GROUPS = {"db_browser", "db_alarm"};
60
61 static const char *const SM_RW_PATH = "/usr/apps/app_dir";
62 static const char *const SM_RO_PATH = "/usr/apps/app_dir_public_ro";
63 static const char *const SM_DENIED_PATH = "/usr/apps/non_app_dir";
64
65 static const char *const ANY_USER_REPRESENTATION = "anyuser";/*this may be actually any string*/
66 static const std::string EXEC_FILE("exec");
67 static const std::string NORMAL_FILE("normal");
68 static const std::string LINK_PREFIX("link_to_");
69
70 static const std::string PRIVILEGE_MANAGER_APP = "privilege_manager";
71 static const std::string PRIVILEGE_MANAGER_PKG = "privilege_manager";
72 static const std::string PRIVILEGE_MANAGER_SELF_PRIVILEGE = "http://tizen.org/privilege/systemsettings";
73 static const std::string PRIVILEGE_MANAGER_ADMIN_PRIVILEGE = "http://tizen.org/privilege/systemsettings.admin";
74
75 static const std::vector<std::string> MANY_APPS = {
76     "security_manager_10_app_1",
77     "security_manager_10_app_2",
78     "security_manager_10_app_3",
79     "security_manager_10_app_4",
80     "security_manager_10_app_5"
81 };
82
83 static const std::map<std::string, std::string> MANY_APPS_PKGS = {
84     {"security_manager_10_app_1", "security_manager_10_pkg_1"},
85     {"security_manager_10_app_2", "security_manager_10_pkg_2"},
86     {"security_manager_10_app_3", "security_manager_10_pkg_3"},
87     {"security_manager_10_app_4", "security_manager_10_pkg_4"},
88     {"security_manager_10_app_5", "security_manager_10_pkg_5"},
89     {PRIVILEGE_MANAGER_APP, PRIVILEGE_MANAGER_PKG}
90 };
91
92 static const std::vector<privileges_t> MANY_APPS_PRIVILEGES = {
93     {
94         "http://tizen.org/privilege/internet",
95         "http://tizen.org/privilege/location"
96     },
97     {
98         "http://tizen.org/privilege/telephony",
99         "http://tizen.org/privilege/camera"
100     },
101     {
102         "http://tizen.org/privilege/contact.read",
103         "http://tizen.org/privilege/led",
104         "http://tizen.org/privilege/email"
105     },
106     {
107         "http://tizen.org/privilege/led",
108         "http://tizen.org/privilege/email",
109         "http://tizen.org/privilege/telephony",
110         "http://tizen.org/privilege/camera"
111     },
112     {
113         "http://tizen.org/privilege/internet",
114         "http://tizen.org/privilege/location",
115         "http://tizen.org/privilege/led",
116         "http://tizen.org/privilege/email"
117     }
118 };
119
120 static void generateAppLabel(const std::string &appId, std::string &label)
121 {
122     (void) appId;
123     label = "User";
124 }
125
126 static int nftw_check_sm_labels_app_dir(const char *fpath, const struct stat *sb,
127                               const char* correctLabel, bool transmute_test, bool exec_test)
128 {
129     int result;
130     CStringPtr labelPtr;
131     char* label = nullptr;
132
133     /* ACCESS */
134     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
135     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
136     labelPtr.reset(label);
137     RUNNER_ASSERT_MSG(label != nullptr, "ACCESS label on " << fpath << " is not set");
138     result = strcmp(correctLabel, label);
139     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is incorrect"
140             " (should be '" << correctLabel << "' and is '" << label << "')");
141
142
143     /* EXEC */
144     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
145     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
146     labelPtr.reset(label);
147
148     if (S_ISREG(sb->st_mode) && (sb->st_mode & S_IXUSR) && exec_test) {
149         RUNNER_ASSERT_MSG(label != nullptr, "EXEC label on " << fpath << " is not set");
150         result = strcmp(correctLabel, label);
151         RUNNER_ASSERT_MSG(result == 0, "Incorrect EXEC label on executable file " << fpath);
152     } else
153         RUNNER_ASSERT_MSG(label == nullptr, "EXEC label on " << fpath << " is set");
154
155
156     /* TRANSMUTE */
157     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
158     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
159     labelPtr.reset(label);
160
161     if (S_ISDIR(sb->st_mode) && transmute_test == true) {
162         RUNNER_ASSERT_MSG(label != nullptr, "TRANSMUTE label on " << fpath << " is not set at all");
163         RUNNER_ASSERT_MSG(strcmp(label,"TRUE") == 0,
164                 "TRANSMUTE label on " << fpath << " is not set properly: '"<<label<<"'");
165     } else {
166         RUNNER_ASSERT_MSG(label == nullptr, "TRANSMUTE label on " << fpath << " is set");
167     }
168
169     return 0;
170 }
171
172
173 static int nftw_check_sm_labels_app_rw_dir(const char *fpath, const struct stat *sb,
174                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
175 {
176     return nftw_check_sm_labels_app_dir(fpath, sb, USER_APP_ID, false, true);
177 }
178
179 static int nftw_check_sm_labels_app_ro_dir(const char *fpath, const struct stat *sb,
180                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
181 {
182
183     return nftw_check_sm_labels_app_dir(fpath, sb, "User::Home", true, false);
184 }
185
186 static void prepare_app_path()
187 {
188     int result;
189
190     result = nftw(SM_RW_PATH, &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
191     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RW_PATH);
192
193     result = nftw(SM_RO_PATH, &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
194     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RO_PATH);
195
196     result = nftw(SM_DENIED_PATH, &nftw_set_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
197     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_DENIED_PATH);
198 }
199
200 static void prepare_app_env()
201 {
202     prepare_app_path();
203 }
204
205 /* TODO: add parameters to this function */
206 static void check_app_path_after_install()
207 {
208     int result;
209
210     result = nftw(SM_RW_PATH, &nftw_check_sm_labels_app_rw_dir, FTW_MAX_FDS, FTW_PHYS);
211     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RW_PATH);
212
213     result = nftw(SM_RO_PATH, &nftw_check_sm_labels_app_ro_dir, FTW_MAX_FDS, FTW_PHYS);
214     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RO_PATH);
215
216     result = nftw(SM_DENIED_PATH, &nftw_check_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
217     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_DENIED_PATH);
218 }
219
220
221 static void check_app_permissions(const char *const app_id, const char *const pkg_id, const char *const user,
222                                   const privileges_t &allowed_privs, const privileges_t &denied_privs)
223 {
224     (void) pkg_id;
225     std::string smackLabel;
226     generateAppLabel(app_id, smackLabel);
227
228     CynaraTestClient::Client ctc;
229
230     for (auto &priv : allowed_privs) {
231         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_ALLOWED);
232     }
233
234     for (auto &priv : denied_privs) {
235         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_DENIED);
236     }
237 }
238
239 static void check_app_gids(const char *const app_id, const std::vector<gid_t> &allowed_gids)
240 {
241     int ret;
242     gid_t main_gid = getgid();
243     std::unordered_set<gid_t> reference_gids(allowed_gids.begin(), allowed_gids.end());
244
245     // Reset supplementary groups
246     ret = setgroups(0, NULL);
247     RUNNER_ASSERT_MSG(ret != -1, "Unable to set supplementary groups");
248
249     Api::setProcessGroups(app_id);
250
251     ret = getgroups(0, nullptr);
252     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
253
254     std::vector<gid_t> actual_gids(ret);
255     ret = getgroups(ret, actual_gids.data());
256     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
257
258     for (const auto &gid : actual_gids) {
259         RUNNER_ASSERT_MSG(gid == main_gid || reference_gids.count(gid) > 0,
260             "Application shouldn't get access to group " << gid);
261         reference_gids.erase(gid);
262     }
263
264     RUNNER_ASSERT_MSG(reference_gids.empty(), "Application didn't get access to some groups");
265 }
266
267 static void check_app_after_install(const char *const app_id, const char *const pkg_id,
268                                     const privileges_t &allowed_privs,
269                                     const privileges_t &denied_privs,
270                                     const std::vector<std::string> &allowed_groups)
271 {
272     TestSecurityManagerDatabase dbtest;
273     dbtest.test_db_after__app_install(app_id, pkg_id, allowed_privs);
274     dbtest.check_privileges_removed(app_id, pkg_id, denied_privs);
275
276     /*Privileges should be granted to all users if root installs app*/
277     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, allowed_privs, denied_privs);
278
279     /* Setup mapping of gids to privileges */
280     /* Do this for each privilege for extra check */
281     for (const auto &privilege : allowed_privs) {
282         dbtest.setup_privilege_groups(privilege, allowed_groups);
283     }
284
285     std::vector<gid_t> allowed_gids;
286
287     for (const auto &groupName : allowed_groups) {
288         errno = 0;
289         struct group* grp = getgrnam(groupName.c_str());
290         RUNNER_ASSERT_ERRNO_MSG(grp, "Group: " << groupName << " not found");
291         allowed_gids.push_back(grp->gr_gid);
292     }
293
294     check_app_gids(app_id, allowed_gids);
295 }
296
297 static void check_app_after_install(const char *const app_id, const char *const pkg_id)
298 {
299     TestSecurityManagerDatabase dbtest;
300     dbtest.test_db_after__app_install(app_id, pkg_id);
301 }
302
303 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
304                                       const privileges_t &privileges, const bool is_pkg_removed)
305 {
306     TestSecurityManagerDatabase dbtest;
307     dbtest.test_db_after__app_uninstall(app_id, pkg_id, privileges, is_pkg_removed);
308
309
310     /*Privileges should not be granted anymore to any user*/
311     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, SM_NO_PRIVILEGES, privileges);
312 }
313
314 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
315                                       const bool is_pkg_removed)
316 {
317     TestSecurityManagerDatabase dbtest;
318     dbtest.test_db_after__app_uninstall(app_id, pkg_id, is_pkg_removed);
319 }
320
321 static void install_app(const char *app_id, const char *pkg_id, uid_t uid = 0)
322 {
323     InstallRequest request;
324     request.setAppId(app_id);
325     request.setPkgId(pkg_id);
326     request.setUid(uid);
327     Api::install(request);
328
329     check_app_after_install(app_id, pkg_id);
330
331 }
332
333 static void uninstall_app(const char *app_id, const char *pkg_id, bool expect_pkg_removed)
334 {
335     InstallRequest request;
336     request.setAppId(app_id);
337
338     Api::uninstall(request);
339
340     check_app_after_uninstall(app_id, pkg_id, expect_pkg_removed);
341 }
342
343 static inline void register_current_process_as_privilege_manager(uid_t uid, bool forAdmin = false)
344 {
345     InstallRequest request;
346     request.setAppId(PRIVILEGE_MANAGER_APP.c_str());
347     request.setPkgId(PRIVILEGE_MANAGER_PKG.c_str());
348     request.setUid(uid);
349     request.addPrivilege(PRIVILEGE_MANAGER_SELF_PRIVILEGE.c_str());
350     if (forAdmin)
351         request.addPrivilege(PRIVILEGE_MANAGER_ADMIN_PRIVILEGE.c_str());
352     Api::install(request);
353     Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
354 };
355
356 static inline struct passwd *getUserStruct(const std::string &userName) {
357     struct passwd *pw = nullptr;
358     errno = 0;
359
360     while(!(pw = getpwnam(userName.c_str()))) {
361         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
362     };
363
364     return pw;
365 };
366
367 static inline struct passwd *getUserStruct(const uid_t uid) {
368     struct passwd *pw = nullptr;
369     errno = 0;
370
371     while(!(pw = getpwuid(uid))) {
372         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
373     };
374
375     return pw;
376 };
377
378 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER)
379
380
381 RUNNER_TEST(security_manager_01a_app_double_install_double_uninstall)
382 {
383     const char *const sm_app_id = "sm_test_01a_app_id_double";
384     const char *const sm_pkg_id = "sm_test_01a_pkg_id_double";
385
386     InstallRequest requestInst;
387     requestInst.setAppId(sm_app_id);
388     requestInst.setPkgId(sm_pkg_id);
389
390     Api::install(requestInst);
391     Api::install(requestInst);
392
393     /* Check records in the security-manager database */
394     check_app_after_install(sm_app_id, sm_pkg_id);
395
396     InstallRequest requestUninst;
397     requestUninst.setAppId(sm_app_id);
398
399     Api::uninstall(requestUninst);
400     Api::uninstall(requestUninst);
401
402     /* Check records in the security-manager database */
403     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
404 }
405
406
407 RUNNER_TEST(security_manager_01b_app_double_install_wrong_pkg_id)
408 {
409     const char *const sm_app_id = "sm_test_01b_app";
410     const char *const sm_pkg_id = "sm_test_01b_pkg";
411     const char *const sm_pkg_id_wrong = "sm_test_01b_pkg_BAD";
412
413     InstallRequest requestInst;
414     requestInst.setAppId(sm_app_id);
415     requestInst.setPkgId(sm_pkg_id);
416
417     Api::install(requestInst);
418
419     InstallRequest requestInst2;
420     requestInst2.setAppId(sm_app_id);
421     requestInst2.setPkgId(sm_pkg_id_wrong);
422
423     Api::install(requestInst2, SECURITY_MANAGER_ERROR_INPUT_PARAM);
424
425
426     /* Check records in the security-manager database */
427     check_app_after_install(sm_app_id, sm_pkg_id);
428
429     InstallRequest requestUninst;
430     requestUninst.setAppId(sm_app_id);
431
432     Api::uninstall(requestUninst);
433
434
435     /* Check records in the security-manager database */
436     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
437
438 }
439
440 RUNNER_TEST(security_manager_01c_app_uninstall_pkg_id_ignored)
441 {
442     const char * const  sm_app_id = "SM_TEST_01c_APPID";
443     const char * const  sm_pkg_id = "SM_TEST_01c_PKGID";
444     const char * const  sm_pkg_id_wrong = "SM_TEST_01c_PKGID_wrong";
445
446     InstallRequest requestInst;
447     requestInst.setAppId(sm_app_id);
448     requestInst.setPkgId(sm_pkg_id);
449
450     Api::install(requestInst);
451
452     /* Check records in the security-manager database */
453     check_app_after_install(sm_app_id, sm_pkg_id);
454
455     InstallRequest requestUninst;
456     requestUninst.setAppId(sm_app_id);
457     requestUninst.setPkgId(sm_pkg_id_wrong);
458
459     Api::uninstall(requestUninst);
460
461     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
462
463 }
464
465 RUNNER_TEST(security_manager_02_app_install_uninstall_full)
466 {
467     const char *const sm_app_id = "sm_test_02_app_id_full";
468     const char *const sm_pkg_id = "sm_test_02_pkg_id_full";
469
470     prepare_app_env();
471
472     InstallRequest requestInst;
473     requestInst.setAppId(sm_app_id);
474     requestInst.setPkgId(sm_pkg_id);
475     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
476     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
477     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
478     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
479
480     Api::install(requestInst);
481
482     /* Check records in the security-manager database */
483     check_app_after_install(sm_app_id, sm_pkg_id,
484                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
485
486     /* TODO: add parameters to this function */
487     check_app_path_after_install();
488
489     InstallRequest requestUninst;
490     requestUninst.setAppId(sm_app_id);
491
492     Api::uninstall(requestUninst);
493
494     /* Check records in the security-manager database,
495      * all previously allowed privileges should be removed */
496     check_app_after_uninstall(sm_app_id, sm_pkg_id,
497                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
498 }
499
500 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
501 {
502     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_smack";
503     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_smack";
504     const char *const expected_label = USER_APP_ID;
505     const char *const socketLabel = "not_expected_label";
506     char *label = nullptr;
507     CStringPtr labelPtr;
508     int result;
509
510     uninstall_app(app_id, pkg_id, true);
511     install_app(app_id, pkg_id);
512
513     struct sockaddr_un sockaddr = {AF_UNIX, SOCK_PATH};
514     //Clean up before creating socket
515     unlink(SOCK_PATH);
516     int sock = socket(AF_UNIX, SOCK_STREAM, 0);
517     RUNNER_ASSERT_ERRNO_MSG(sock >= 0, "socket failed");
518     SockUniquePtr sockPtr(&sock);
519     //Bind socket to address
520     result = bind(sock, (struct sockaddr*) &sockaddr, sizeof(struct sockaddr_un));
521     RUNNER_ASSERT_ERRNO_MSG(result == 0, "bind failed");
522     //Set socket label to something different than expecedLabel
523     result = fsetxattr(sock, XATTR_NAME_SMACKIPIN, socketLabel,
524         strlen(socketLabel), 0);
525     RUNNER_ASSERT_ERRNO_MSG(result == 0,
526         "Can't set socket label. Result: " << result);
527     result = fsetxattr(sock, XATTR_NAME_SMACKIPOUT, socketLabel,
528         strlen(socketLabel), 0);
529     RUNNER_ASSERT_ERRNO_MSG(result == 0,
530         "Can't set socket label. Result: " << result);
531
532     Api::setProcessLabel(app_id);
533
534     char value[SMACK_LABEL_LEN + 1];
535     ssize_t size;
536     size = fgetxattr(sock, XATTR_NAME_SMACKIPIN, value, sizeof(value));
537     RUNNER_ASSERT_ERRNO_MSG(size != -1, "fgetxattr failed: " << value);
538     result = strcmp(expected_label, value);
539     RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
540         expected_label << " Actual: " << value);
541
542     size = fgetxattr(sock, XATTR_NAME_SMACKIPOUT, value, sizeof(value));
543     RUNNER_ASSERT_ERRNO_MSG(size != -1, "fgetxattr failed: " << value);
544     result = strcmp(expected_label, value);
545     RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
546         expected_label << " Actual: " << value);
547
548     result = smack_new_label_from_self(&label);
549     RUNNER_ASSERT_MSG(result >= 0,
550             " Error getting current process label");
551     RUNNER_ASSERT_MSG(label != nullptr,
552             " Process label is not set");
553     labelPtr.reset(label);
554
555     result = strcmp(expected_label, label);
556     RUNNER_ASSERT_MSG(result == 0,
557             " Process label is incorrect. Expected: \"" << expected_label <<
558             "\" Actual: \"" << label << "\"");
559
560     uninstall_app(app_id, pkg_id, true);
561 }
562
563 RUNNER_CHILD_TEST_NOSMACK(security_manager_03_set_label_from_appid_nosmack)
564 {
565     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_nosmack";
566     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_nosmack";
567
568     uninstall_app(app_id, pkg_id, true);
569     install_app(app_id, pkg_id);
570
571     Api::setProcessLabel(app_id);
572
573     uninstall_app(app_id, pkg_id, true);
574 }
575
576 static void prepare_request(InstallRequest &request,
577               const char *const app_id,
578               const char *const pkg_id,
579               app_install_path_type pathType,
580               const char *const path,
581               uid_t uid)
582 {
583     request.setAppId(app_id);
584     request.setPkgId(pkg_id);
585     request.addPath(path, pathType);
586
587     if (uid != 0)
588         request.setUid(uid);
589 }
590
591 static uid_t getGlobalUserId(void)
592 {
593     return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
594 }
595
596 static const std::string appDirPath(const TemporaryTestUser &user)
597 {
598     struct tzplatform_context *tzCtxPtr = nullptr;
599
600     RUNNER_ASSERT(0 == tzplatform_context_create(&tzCtxPtr));
601     TzPlatformContextPtr tzCtxPtrSmart(tzCtxPtr);
602
603     RUNNER_ASSERT_MSG(0 == tzplatform_context_set_user(tzCtxPtr, user.getUid()),
604                       "Unable to set user <" << user.getUserName() << "> for tzplatform context");
605
606     const char *appDir = tzplatform_context_getenv(tzCtxPtr,
607                                 getGlobalUserId() == user.getUid() ? TZ_SYS_RW_APP : TZ_USER_APP);
608     RUNNER_ASSERT_MSG(nullptr != appDir,
609                       "tzplatform_context_getenv failed"
610                           << "for getting sys rw app of user <" << user.getUserName() << ">");
611
612     return appDir;
613 }
614
615 static const std::string nonAppDirPath(const TemporaryTestUser &user)
616 {
617     return TMP_DIR + "/" + user.getUserName();
618 }
619
620 static const std::string uidToStr(const uid_t uid)
621 {
622     return std::to_string(static_cast<unsigned int>(uid));
623 }
624
625 static void install_and_check(const char *const sm_app_id,
626                               const char *const sm_pkg_id,
627                               const TemporaryTestUser& user,
628                               const std::string &appDir,
629                               bool requestUid)
630 {
631     InstallRequest requestPublic;
632
633     //install app for non-root user and try to register public path (should fail)
634     prepare_request(requestPublic, sm_app_id, sm_pkg_id,
635                     SECURITY_MANAGER_PATH_PUBLIC, appDir.c_str(),
636                     requestUid ? user.getUid() : 0);
637
638     Api::install(requestPublic, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
639
640     InstallRequest requestPrivate;
641
642     //install app for non-root user
643     //should fail (users may only register folders inside their home)
644     prepare_request(requestPrivate, sm_app_id, sm_pkg_id,
645                     SECURITY_MANAGER_PATH_RW, SM_RW_PATH,
646                     requestUid ? user.getUid() : 0);
647
648     Api::install(requestPrivate, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
649
650     InstallRequest requestPrivateUser;
651
652     //install app for non-root user
653     //should succeed - this time i register folder inside user's home dir
654     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
655                     SECURITY_MANAGER_PATH_RW, appDir.c_str(),
656                     requestUid ? user.getUid() : 0);
657
658     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
659         requestPrivateUser.addPrivilege(privilege.c_str());
660
661     Api::install(requestPrivateUser);
662
663     check_app_permissions(sm_app_id, sm_pkg_id,
664                           uidToStr(user.getUid()).c_str(),
665                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
666 }
667
668 static void createTestDir(const std::string &dir)
669 {
670     mode_t dirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
671     mode_t execFileMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
672     mode_t normalFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
673
674     mkdirSafe(dir, dirMode);
675     creatSafe(dir + "/" + EXEC_FILE, execFileMode);
676     creatSafe(dir + "/" + NORMAL_FILE, normalFileMode);
677     symlinkSafe(dir + "/" + EXEC_FILE, dir + "/" + LINK_PREFIX + EXEC_FILE);
678     symlinkSafe(dir + "/" + NORMAL_FILE, dir + "/" + LINK_PREFIX + NORMAL_FILE);
679 }
680
681 static void createInnerAppDir(const std::string &dir, const std::string &nonAppDir)
682 {
683     createTestDir(dir);
684
685     symlinkSafe(nonAppDir, dir + "/" + LINK_PREFIX + "non_app_dir");
686     symlinkSafe(nonAppDir + "/" + EXEC_FILE,
687                 dir + "/" + LINK_PREFIX + "non_app_" + EXEC_FILE);
688     symlinkSafe(nonAppDir + "/" + NORMAL_FILE,
689                 dir + "/" + LINK_PREFIX + "non_app_" + NORMAL_FILE);
690 }
691
692 static void generateAppDir(const TemporaryTestUser &user)
693 {
694     const std::string dir = appDirPath(user);
695     const std::string nonAppDir = nonAppDirPath(user);
696
697     createInnerAppDir(dir, nonAppDir);
698     createInnerAppDir(dir + "/.inner_dir", nonAppDir);
699     createInnerAppDir(dir + "/inner_dir", nonAppDir);
700 }
701
702 static void generateNonAppDir(const TemporaryTestUser &user)
703 {
704     const std::string dir = nonAppDirPath(user);
705
706     createTestDir(dir);
707     createTestDir(dir + "/.inner_dir");
708     createTestDir(dir + "/inner_dir");
709 }
710
711 static void createTestDirs(const TemporaryTestUser &user)
712 {
713     generateAppDir(user);
714     generateNonAppDir(user);
715 }
716
717 static void removeTestDirs(const TemporaryTestUser &user)
718 {
719     removeDir(appDirPath(user));
720     removeDir(nonAppDirPath(user));
721 }
722
723 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
724 {
725     int result;
726     const char *const sm_app_id = "sm_test_04a_app_id_uid";
727     const char *const sm_pkg_id = "sm_test_04a_pkg_id_uid";
728     const std::string new_user_name = "sm_test_04a_user_name";
729
730     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
731     testUser.create();
732
733     removeTestDirs(testUser);
734     createTestDirs(testUser);
735
736     const std::string userAppDirPath = appDirPath(testUser);
737
738     //switch user to non-root
739     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
740     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
741
742     install_and_check(sm_app_id, sm_pkg_id, testUser, userAppDirPath, false);
743
744     //uninstall app as non-root user
745     InstallRequest request;
746     request.setAppId(sm_app_id);
747
748     Api::uninstall(request);
749
750     check_app_permissions(sm_app_id, sm_pkg_id,
751                           uidToStr(testUser.getUid()).c_str(),
752                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
753 }
754
755 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user)
756 {
757     int result;
758     const char *const sm_app_id = "sm_test_04b_app_id_uid";
759     const char *const sm_pkg_id = "sm_test_04b_pkg_id_uid";
760     const std::string new_user_name = "sm_test_04b_user_name";
761
762     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
763     testUser.create();
764
765     removeTestDirs(testUser);
766     createTestDirs(testUser);
767
768     install_and_check(sm_app_id, sm_pkg_id, testUser, appDirPath(testUser), true);
769
770     //switch user to non-root - root may not uninstall apps for specified users
771     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
772     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
773
774     //uninstall app as non-root user
775     InstallRequest request;
776     request.setAppId(sm_app_id);
777
778     Api::uninstall(request);
779
780     check_app_permissions(sm_app_id, sm_pkg_id,
781                           uidToStr(testUser.getUid()).c_str(),
782                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
783 }
784
785
786 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
787 {
788     int result;
789     CapsSetsUniquePtr caps, caps_empty(cap_init());
790
791     caps.reset(cap_from_text("all=eip"));
792     RUNNER_ASSERT_MSG(caps, "can't convert capabilities from text");
793     result = cap_set_proc(caps.get());
794     RUNNER_ASSERT_MSG(result == 0,
795         "can't set capabilities. Result: " << result);
796
797     Api::dropProcessPrivileges();
798
799     caps.reset(cap_get_proc());
800     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
801
802     result = cap_compare(caps.get(), caps_empty.get());
803     RUNNER_ASSERT_MSG(result == 0,
804         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
805 }
806
807 RUNNER_CHILD_TEST(security_manager_06_install_app_offline)
808 {
809     const char *const app_id = "sm_test_06_app_id_install_app_offline";
810     const char *const pkg_id = "sm_test_06_pkg_id_install_app_offline";
811     ServiceManager serviceManager("security-manager.service");
812
813     uninstall_app(app_id, pkg_id, true);
814     serviceManager.maskService();
815     serviceManager.stopService();
816
817     install_app(app_id, pkg_id);
818
819     serviceManager.unmaskService();
820     serviceManager.startService();
821
822     uninstall_app(app_id, pkg_id, true);
823 }
824
825 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
826 {
827     const char *const sm_app_id = "sm_test_07_app_id_user";
828     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
829     const std::string new_user_name = "sm_test_07_user_name";
830     std::string uid_string;
831     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
832     test_user.create();
833     test_user.getUidString(uid_string);
834
835     removeTestDirs(test_user);
836     createTestDirs(test_user);
837
838     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
839
840     check_app_after_install(sm_app_id, sm_pkg_id);
841
842     test_user.remove();
843
844     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
845
846     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
847 }
848
849 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
850 {
851     UserRequest addUserRequest;
852
853     const char *const sm_app_id = "sm_test_08_app_id_user";
854     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
855     const std::string new_user_name = "sm_test_08_user_name";
856     std::string uid_string;
857
858     // gumd user add
859     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
860     test_user.create();
861     test_user.getUidString(uid_string);
862
863     removeTestDirs(test_user);
864     createTestDirs(test_user);
865
866     addUserRequest.setUid(test_user.getUid());
867     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
868
869     //sm user add
870     Api::addUser(addUserRequest);
871
872     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
873
874     check_app_after_install(sm_app_id, sm_pkg_id);
875
876     test_user.remove();
877
878     UserRequest deleteUserRequest;
879     deleteUserRequest.setUid(test_user.getUid());
880
881     Api::deleteUser(deleteUserRequest);
882
883     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
884
885     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
886 }
887
888 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
889 {
890     const char *const app_id = "security_manager_09_add_user_offline_app";
891     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
892     const std::string new_user_name("sm_test_09_user_name");
893     ServiceManager serviceManager("security-manager.service");
894     serviceManager.maskService();
895     serviceManager.stopService();
896
897     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, true);
898     test_user.create();
899
900     removeTestDirs(test_user);
901     createTestDirs(test_user);
902
903     install_app(app_id, pkg_id, test_user.getUid());
904
905     check_app_after_install(app_id, pkg_id);
906
907     serviceManager.unmaskService();
908     serviceManager.startService();
909
910     test_user.remove();
911
912     check_app_after_uninstall(app_id, pkg_id, true);
913 }
914
915 RUNNER_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
916 {
917     //TEST DATA
918     const std::string username("sm_test_10_user_name");
919     unsigned int privileges_count = 0;
920
921     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
922     std::map<std::string, std::set<std::string>> apps2PrivsMap;
923
924     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
925         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
926             MANY_APPS.at(i), std::set<std::string>(
927                 MANY_APPS_PRIVILEGES.at(i).begin(),
928                 MANY_APPS_PRIVILEGES.at(i).end())));
929         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
930     };
931
932     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
933         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
934     ++privileges_count;
935     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
936     //TEST DATA END
937
938     sem_t *mutex;
939     errno = 0;
940     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
941     errno = 0;
942     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
943     pid_t pid = fork();
944
945     if (pid != 0) { //parent process
946         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
947         tmpUser.create();
948
949         for(const auto &user : users2AppsMap) {
950
951             for(const auto &app : user.second) {
952                 InstallRequest requestInst;
953                 requestInst.setAppId(app.first.c_str());
954                 try {
955                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
956                 } catch (const std::out_of_range &e) {
957                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
958                 };
959                 requestInst.setUid(tmpUser.getUid());
960
961                 for (const auto &privilege : app.second) {
962                     requestInst.addPrivilege(privilege.c_str());
963                 };
964
965                 Api::install(requestInst);
966             };
967
968             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
969         };
970         //Start child process
971         errno = 0;
972         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
973
974         int status;
975         wait(&status);
976
977         tmpUser.remove();
978     };
979
980     if (pid == 0) { //child process
981         errno = 0;
982         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
983         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
984
985         struct passwd *pw = getUserStruct(username);
986         register_current_process_as_privilege_manager(pw->pw_uid);
987         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
988         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
989
990         std::vector<PolicyEntry> policyEntries;
991         PolicyEntry filter;
992         Api::getPolicy(filter, policyEntries);
993
994         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
995         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
996
997         for (const auto &policyEntry : policyEntries) {
998             std::string user = policyEntry.getUser();
999             std::string app = policyEntry.getAppId();
1000             std::string privilege = policyEntry.getPrivilege();
1001
1002             try {
1003                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1004                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1005                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1006                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1007             } catch (const std::out_of_range &e) {
1008                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1009             } catch (const std::invalid_argument& e) {
1010                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1011             };
1012         };
1013         exit(0);
1014     };
1015 }
1016
1017 RUNNER_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1018 {
1019     //TEST DATA
1020     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1021     unsigned int privileges_count = 0;
1022
1023     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1024     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1025
1026     for (const auto &username : usernames) {
1027         //Only entries for one of the users will be listed
1028         privileges_count = 0;
1029
1030         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1031             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1032                 MANY_APPS.at(i), std::set<std::string>(
1033                     MANY_APPS_PRIVILEGES.at(i).begin(),
1034                     MANY_APPS_PRIVILEGES.at(i).end())));
1035             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1036         };
1037
1038         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1039     };
1040
1041     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1042         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1043
1044     ++privileges_count;
1045     //TEST DATA END
1046
1047     sem_t *mutex;
1048     errno = 0;
1049     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1050     errno = 0;
1051     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1052     pid_t pid = fork();
1053
1054     if (pid != 0) { //parent process
1055         std::vector<TemporaryTestUser> users = {
1056             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1057             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1058             };
1059
1060         users.at(0).create();
1061         users.at(1).create();
1062
1063         //Install apps for both users
1064         for(const auto &user : users) {
1065             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1066                 InstallRequest requestInst;
1067                 requestInst.setAppId(app.first.c_str());
1068                 try {
1069                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1070                 } catch (const std::out_of_range &e) {
1071                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1072                 };
1073                 requestInst.setUid(user.getUid());
1074
1075                 for (const auto &privilege : app.second) {
1076                     requestInst.addPrivilege(privilege.c_str());
1077                 };
1078
1079                 Api::install(requestInst);
1080             };
1081
1082             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1083         };
1084         //Start child
1085         errno = 0;
1086         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1087
1088         int status;
1089         wait(&status);
1090
1091         for(auto &user : users) {
1092             user.remove();
1093         };
1094     };
1095
1096     if (pid == 0) {
1097         errno = 0;
1098         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1099         struct passwd *pw = getUserStruct(usernames.at(0));
1100         register_current_process_as_privilege_manager(pw->pw_uid);
1101
1102         //change uid to normal user
1103         errno = 0;
1104         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1105         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1106
1107         std::vector<PolicyEntry> policyEntries;
1108         PolicyEntry filter;
1109
1110         //this call should only return privileges belonging to the current uid
1111         Api::getPolicy(filter, policyEntries);
1112
1113         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1114         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1115
1116         for (const auto &policyEntry : policyEntries) {
1117             std::string user = policyEntry.getUser();
1118             std::string app = policyEntry.getAppId();
1119             std::string privilege = policyEntry.getPrivilege();
1120
1121             try {
1122                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1123                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1124                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1125                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1126             } catch (const std::out_of_range &e) {
1127                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1128             } catch (const std::invalid_argument& e) {
1129                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1130             };
1131         };
1132         exit(0);
1133     };
1134 }
1135
1136 RUNNER_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1137 {
1138     //TEST DATA
1139     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1140     unsigned int privileges_count = 0;
1141
1142     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1143     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1144
1145     for (const auto &username : usernames) {
1146
1147         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1148             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1149                 MANY_APPS.at(i), std::set<std::string>(
1150                     MANY_APPS_PRIVILEGES.at(i).begin(),
1151                     MANY_APPS_PRIVILEGES.at(i).end())));
1152             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1153         };
1154
1155         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1156     };
1157
1158     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1159         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1160
1161     privileges_count += 2;
1162     //TEST DATA END
1163
1164     sem_t *mutex;
1165     errno = 0;
1166     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1167     errno = 0;
1168     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1169     pid_t pid = fork();
1170
1171     if (pid != 0) { //parent process
1172         std::vector<TemporaryTestUser> users = {
1173             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1174             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1175             };
1176
1177         users.at(0).create();
1178         users.at(1).create();
1179         //Install apps for both users
1180         for(const auto &user : users) {
1181             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1182                 InstallRequest requestInst;
1183                 requestInst.setAppId(app.first.c_str());
1184                 try {
1185                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1186                 } catch (const std::out_of_range &e) {
1187                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1188                 };
1189                 requestInst.setUid(user.getUid());
1190
1191                 for (const auto &privilege : app.second) {
1192                     requestInst.addPrivilege(privilege.c_str());
1193                 };
1194
1195                 Api::install(requestInst);
1196             };
1197
1198             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1199         };
1200
1201         //Start child
1202         errno = 0;
1203         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1204
1205         //Wait for child to finish
1206         int status;
1207         wait(&status);
1208
1209         for(auto &user : users) {
1210             user.remove();
1211         };
1212     };
1213
1214     if (pid == 0) { //child process
1215         errno = 0;
1216         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1217
1218         struct passwd *pw = getUserStruct(usernames.at(1));
1219         register_current_process_as_privilege_manager(pw->pw_uid, true);
1220
1221         //change uid to normal user
1222         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1223         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1224
1225         std::vector<PolicyEntry> policyEntries;
1226         PolicyEntry filter;
1227         //this call should succeed as the calling user is privileged
1228         Api::getPolicy(filter, policyEntries);
1229
1230         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1231         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1232
1233         for (const auto &policyEntry : policyEntries) {
1234             std::string user = policyEntry.getUser();
1235             std::string app = policyEntry.getAppId();
1236             std::string privilege = policyEntry.getPrivilege();
1237
1238             try {
1239                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1240                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1241                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1242                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1243             } catch (const std::out_of_range &e) {
1244                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1245             } catch (const std::invalid_argument& e) {
1246                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1247             };
1248         };
1249
1250         exit(0);
1251     };
1252 }
1253
1254 RUNNER_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1255 {
1256     //TEST DATA
1257     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1258
1259     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1260     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1261
1262     for (const auto &username : usernames) {
1263
1264         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1265             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1266                 MANY_APPS.at(i), std::set<std::string>(
1267                     MANY_APPS_PRIVILEGES.at(i).begin(),
1268                     MANY_APPS_PRIVILEGES.at(i).end())));
1269         };
1270
1271         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1272     };
1273
1274     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1275         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1276
1277     //TEST DATA END
1278
1279     pid_t pid[2];
1280     sem_t *mutex[2];
1281     errno = 0;
1282     RUNNER_ASSERT_MSG(((mutex[0] = sem_open("mutex_1", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #1, errno: " << errno);
1283     errno = 0;
1284     RUNNER_ASSERT_MSG(((mutex[1] = sem_open("mutex_2", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #2, errno: " << errno);
1285     errno = 0;
1286     RUNNER_ASSERT_MSG(sem_init(mutex[0], 1, 0) == 0, "failed to setup mutex #1, errno: " << errno);
1287     errno = 0;
1288     RUNNER_ASSERT_MSG(sem_init(mutex[1], 1, 0) == 0, "failed to setup mutex #2, errno: " << errno);
1289     std::vector<PolicyEntry> policyEntries;
1290
1291     pid[0] = fork();
1292
1293     if(pid[0] == 0) { //child #1 process
1294         RUNNER_ASSERT_MSG(sem_wait(mutex[0]) == 0, "sem_wait in child #1 failed, errno: " << errno);
1295         struct passwd *pw = getUserStruct(usernames.at(0));
1296         register_current_process_as_privilege_manager(pw->pw_uid);
1297
1298         //change uid to normal user
1299         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1300         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1301
1302         PolicyEntry filter;
1303         PolicyRequest policyRequest;
1304         //this call should succeed as the calling user is privileged
1305         Api::getPolicyForSelf(filter, policyEntries);
1306
1307         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1308
1309         PolicyEntry policyEntry(
1310                 MANY_APPS[0],
1311                 std::to_string(pw->pw_uid),
1312                 "http://tizen.org/privilege/internet"
1313                 );
1314         policyEntry.setLevel("Deny");
1315
1316         policyRequest.addEntry(policyEntry);
1317         policyEntry = PolicyEntry(
1318                 MANY_APPS[1],
1319                 std::to_string(pw->pw_uid),
1320                 "http://tizen.org/privilege/location"
1321                 );
1322         policyEntry.setLevel("Deny");
1323
1324         policyRequest.addEntry(policyEntry);
1325         Api::sendPolicy(policyRequest);
1326         Api::getPolicyForSelf(filter, policyEntries);
1327
1328         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1329         exit(0);
1330     };
1331
1332     if (pid[0] != 0) {//parent process
1333         pid[1] = fork();
1334
1335         if (pid[1] == 0) { //child #2 process
1336             errno = 0;
1337             RUNNER_ASSERT_MSG(sem_wait(mutex[1]) == 0, "sem_wait in child #2 failed, errno: " << errno);
1338             struct passwd *pw_target = getUserStruct(usernames.at(0));
1339             struct passwd *pw = getUserStruct(usernames.at(1));
1340             register_current_process_as_privilege_manager(pw->pw_uid);
1341
1342             //change uid to normal user
1343             int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1344             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1345
1346             PolicyEntry filter = PolicyEntry(
1347                         SECURITY_MANAGER_ANY,
1348                         std::to_string(pw_target->pw_uid),
1349                         SECURITY_MANAGER_ANY
1350                         );
1351
1352             //U2 requests contents of U1 privacy manager - should fail
1353             Api::getPolicyForSelf(filter, policyEntries);
1354             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1355
1356             filter = PolicyEntry(
1357                         SECURITY_MANAGER_ANY,
1358                         SECURITY_MANAGER_ANY,
1359                         SECURITY_MANAGER_ANY
1360                         );
1361
1362             policyEntries.clear();
1363
1364             //U2 requests contents of ADMIN bucket - should fail
1365             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1366             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1367             exit(0);
1368         };
1369
1370         if (pid[1] != 0) { //parent
1371
1372             std::vector<TemporaryTestUser> users = {
1373                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1374                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1375                 };
1376
1377             users.at(0).create();
1378             users.at(1).create();
1379
1380             //Install apps for both users
1381             for(const auto &user : users2AppsMap) {
1382
1383                 for(const auto &app : user.second) {
1384                     InstallRequest requestInst;
1385                     requestInst.setAppId(app.first.c_str());
1386                     try {
1387                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).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(users.at(0).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             int status;
1404             //Start child #1
1405             errno = 0;
1406             RUNNER_ASSERT_MSG(sem_post(mutex[0]) ==  0, "Error while opening mutex #1, errno: " << errno);
1407
1408             //Wait until child #1 finishes
1409             pid_t ret = wait(&status);
1410             RUNNER_ASSERT_MSG((ret != -1) && WIFEXITED(status), "Updating privileges failed");
1411
1412             //Start child #2
1413             errno = 0;
1414             RUNNER_ASSERT_MSG(sem_post(mutex[1]) ==  0, "Error while opening mutex #2, errno: " << errno);
1415             //Wait until child #2 finishes
1416             ret = wait(&status);
1417             RUNNER_ASSERT_MSG((ret =-1) && WIFEXITED(status), "Listing privileges failed");
1418
1419             for(auto &user : users) {
1420                 user.remove();
1421             };
1422
1423             sem_close(mutex[0]);
1424             sem_close(mutex[1]);
1425         };
1426     };
1427 }
1428
1429 RUNNER_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1430 {
1431     //TEST DATA
1432     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1433     unsigned int privileges_count = 0;
1434
1435     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1436     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1437
1438     for (const auto &username : usernames) {
1439
1440         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1441             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1442                 MANY_APPS.at(i), std::set<std::string>(
1443                     MANY_APPS_PRIVILEGES.at(i).begin(),
1444                     MANY_APPS_PRIVILEGES.at(i).end())));
1445             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1446         };
1447
1448         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1449     };
1450
1451     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1452         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1453
1454     privileges_count += 2;
1455     //TEST DATA END
1456     sem_t *mutex;
1457     errno = 0;
1458     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1459     errno = 0;
1460     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1461
1462     pid_t pid = fork();
1463     if (pid != 0) {
1464         std::vector<TemporaryTestUser> users = {
1465             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1466             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1467             };
1468
1469         users.at(0).create();
1470         users.at(1).create();
1471
1472         //Install apps for both users
1473         for(const auto &user : users) {
1474
1475             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1476                 InstallRequest requestInst;
1477                 requestInst.setAppId(app.first.c_str());
1478                 try {
1479                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1480                 } catch (const std::out_of_range &e) {
1481                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1482                 };
1483                 requestInst.setUid(user.getUid());
1484
1485                 for (const auto &privilege : app.second) {
1486                     requestInst.addPrivilege(privilege.c_str());
1487                 };
1488
1489                 Api::install(requestInst);
1490             };
1491         };
1492         //Start child process
1493         errno = 0;
1494         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1495         int status;
1496         //Wait for child process to finish
1497         wait(&status);
1498
1499         //switch back to root
1500         for(auto &user : users) {
1501             user.remove();
1502         };
1503
1504         sem_close(mutex);
1505     }
1506
1507     if (pid == 0) { //child process
1508         errno = 0;
1509         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
1510
1511         struct passwd *pw = getUserStruct(usernames.at(0));
1512         register_current_process_as_privilege_manager(pw->pw_uid, true);
1513
1514         //change uid to normal user
1515         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1516         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1517
1518         PolicyRequest *policyRequest = new PolicyRequest();
1519         PolicyEntry filter;
1520         std::vector<PolicyEntry> policyEntries;
1521         //this call should succeed as the calling user is privileged
1522         Api::getPolicyForSelf(filter, policyEntries);
1523
1524         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1525
1526         PolicyEntry policyEntry(
1527                 SECURITY_MANAGER_ANY,
1528                 SECURITY_MANAGER_ANY,
1529                 "http://tizen.org/privilege/internet"
1530                 );
1531         policyEntry.setMaxLevel("Deny");
1532
1533         policyRequest->addEntry(policyEntry);
1534         policyEntry = PolicyEntry(
1535                 SECURITY_MANAGER_ANY,
1536                 SECURITY_MANAGER_ANY,
1537                 "http://tizen.org/privilege/location"
1538                 );
1539         policyEntry.setMaxLevel("Deny");
1540
1541         policyRequest->addEntry(policyEntry);
1542         Api::sendPolicy(*policyRequest);
1543         Api::getPolicyForAdmin(filter, policyEntries);
1544
1545         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1546
1547         delete policyRequest;
1548         policyRequest = new PolicyRequest();
1549         policyEntry = PolicyEntry(
1550                 SECURITY_MANAGER_ANY,
1551                 SECURITY_MANAGER_ANY,
1552                 "http://tizen.org/privilege/internet"
1553                 );
1554         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1555         policyRequest->addEntry(policyEntry);
1556
1557         policyEntry = PolicyEntry(
1558                 SECURITY_MANAGER_ANY,
1559                 SECURITY_MANAGER_ANY,
1560                 "http://tizen.org/privilege/location"
1561                 );
1562         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1563
1564         policyRequest->addEntry(policyEntry);
1565         Api::sendPolicy(*policyRequest);
1566
1567         policyEntries.clear();
1568         Api::getPolicyForAdmin(filter, policyEntries);
1569         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1570
1571         delete policyRequest;
1572
1573         exit(0);
1574     };
1575
1576 }
1577
1578 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1579 {
1580     const char *const update_app_id = "security_manager_15_update_app_id";
1581     const char *const update_privilege = "http://tizen.org/privilege/led";
1582     const char *const check_start_bucket = "ADMIN";
1583     const std::string username("sm_test_15_username");
1584     PolicyRequest addPolicyRequest;
1585     CynaraTestAdmin::Admin admin;
1586
1587     std::string smackLabel;
1588     generateAppLabel(update_app_id, smackLabel);
1589
1590     struct message {
1591         uid_t uid;
1592         gid_t gid;
1593     } msg;
1594
1595     int pipefd[2];
1596     pid_t pid;
1597     int result = 0;
1598
1599     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1600
1601     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1602     user.create();
1603
1604     pid = fork();
1605     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1606     if (pid != 0)//parent process
1607     {
1608         FdUniquePtr pipeptr(pipefd+1);
1609         close(pipefd[0]);
1610
1611         register_current_process_as_privilege_manager(user.getUid(), true);
1612
1613         //send info to child
1614         msg.uid = user.getUid();
1615         msg.gid = user.getGid();
1616
1617         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1618         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1619
1620         //wait for child
1621         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1622
1623         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1624                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1625     }
1626     if(pid == 0)
1627     {
1628         FdUniquePtr pipeptr(pipefd);
1629         close(pipefd[1]);
1630
1631         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1632         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1633
1634         //become admin privacy manager manager
1635         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1636         result = drop_root_privileges(msg.uid, msg.gid);
1637         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1638
1639         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1640         entry.setMaxLevel("Allow");
1641
1642         addPolicyRequest.addEntry(entry);
1643         Api::sendPolicy(addPolicyRequest);
1644         exit(0);
1645     }
1646 }
1647
1648 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1649 {
1650     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1651     const char *const update_privilege = "http://tizen.org/privilege/led";
1652     const char *const check_start_bucket = "ADMIN";
1653     const std::string username("sm_test_15_username");
1654     PolicyRequest addPolicyRequest;
1655     CynaraTestAdmin::Admin admin;
1656
1657     std::string smackLabel;
1658     generateAppLabel(update_other_app_id, smackLabel);
1659
1660     struct message {
1661         uid_t uid;
1662         gid_t gid;
1663     } msg;
1664
1665     int pipefd[2];
1666     pid_t pid;
1667     int result = 0;
1668
1669     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1670
1671     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1672     user.create();
1673
1674     pid = fork();
1675     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1676     if (pid != 0)//parent process
1677     {
1678         FdUniquePtr pipeptr(pipefd+1);
1679         close(pipefd[0]);
1680
1681         register_current_process_as_privilege_manager(user.getUid(), true);
1682
1683         //send info to child
1684         msg.uid = user.getUid();
1685         msg.gid = user.getGid();
1686
1687         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1688         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1689
1690         //wait for child
1691         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1692
1693         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1694                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1695     }
1696     if(pid == 0)
1697     {
1698         FdUniquePtr pipeptr(pipefd);
1699         close(pipefd[1]);
1700
1701         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1702         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1703
1704         //become admin privacy manager manager
1705         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1706         result = drop_root_privileges(msg.uid, msg.gid);
1707         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1708
1709         // use wildcard as appId
1710         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1711         entry.setMaxLevel("Allow");
1712
1713         addPolicyRequest.addEntry(entry);
1714         Api::sendPolicy(addPolicyRequest);
1715         exit(0);
1716     }
1717 }
1718
1719 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1720 {
1721     const char *const update_app_id = "security_manager_15_update_app_id";
1722     const char *const update_privilege = "http://tizen.org/privilege/led";
1723     const char *const check_start_bucket = "";
1724     const std::string username("sm_test_15_username");
1725     PolicyRequest addPolicyRequest;
1726     CynaraTestAdmin::Admin admin;
1727
1728     std::string smackLabel;
1729     generateAppLabel(update_app_id, smackLabel);
1730
1731     struct message {
1732         uid_t uid;
1733         gid_t gid;
1734     } msg;
1735
1736     int pipefd[2];
1737     pid_t pid;
1738     int result = 0;
1739
1740     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1741
1742     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1743     user.create();
1744
1745     pid = fork();
1746     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1747     if (pid != 0)//parent process
1748     {
1749         FdUniquePtr pipeptr(pipefd+1);
1750         close(pipefd[0]);
1751
1752         register_current_process_as_privilege_manager(user.getUid(), false);
1753
1754         //send info to child
1755         msg.uid = user.getUid();
1756         msg.gid = user.getGid();
1757
1758         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1759         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1760
1761         //wait for child
1762         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1763
1764         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1765                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1766     }
1767     if(pid == 0)
1768     {
1769         FdUniquePtr pipeptr(pipefd);
1770         close(pipefd[1]);
1771
1772         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1773         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1774
1775         //become admin privacy manager manager
1776         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1777         result = drop_root_privileges(msg.uid, msg.gid);
1778         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1779
1780         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1781         entry.setLevel("Allow");
1782
1783         addPolicyRequest.addEntry(entry);
1784         Api::sendPolicy(addPolicyRequest);
1785         exit(0);
1786     }
1787 }
1788
1789 RUNNER_MULTIPROCESS_TEST(security_manager_16_policy_levels_get)
1790 {
1791     const std::string username("sm_test_16_user_cynara_policy");
1792     CynaraTestAdmin::Admin admin;
1793     int pipefd[2];
1794     pid_t pid;
1795     int result = 0;
1796
1797     struct message {
1798         uid_t uid;
1799         gid_t gid;
1800     } msg;
1801
1802     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1803
1804     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1805     user.create();
1806
1807     pid = fork();
1808     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1809     if (pid != 0)//parent process
1810     {
1811         FdUniquePtr pipeptr(pipefd+1);
1812         close(pipefd[0]);
1813
1814         //send info to child
1815         msg.uid = user.getUid();
1816         msg.gid = user.getGid();
1817
1818         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1819         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1820
1821         //wait for child
1822         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1823     }
1824     if(pid == 0)
1825     {
1826         int ret;
1827         char** levels;
1828         std::string allow_policy, deny_policy;
1829         size_t count;
1830         FdUniquePtr pipeptr(pipefd);
1831         close(pipefd[1]);
1832
1833         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1834         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1835
1836         //become admin privacy manager manager
1837         result = drop_root_privileges(msg.uid, msg.gid);
1838         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1839
1840         // without plugins there should only be 2 policies - Allow and Deny
1841         ret = security_manager_policy_levels_get(&levels, &count);
1842
1843         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
1844                 "Invlid return code: " << ret);
1845
1846         RUNNER_ASSERT_MSG(count == 2, "Invalid number of policy levels. Should be 2, instead there is: " << static_cast<int>(count));
1847
1848         deny_policy = std::string(levels[0]);
1849         allow_policy = std::string(levels[count-1]);
1850
1851         // first should always be Deny
1852         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
1853                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
1854
1855         // last should always be Allow
1856         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
1857                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
1858
1859         security_manager_policy_levels_free(levels, count);
1860         exit(0);
1861     }
1862 }
1863
1864 RUNNER_CHILD_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
1865 {
1866     const char *const update_app_id = "security_manager_17_update_app_id";
1867     const char *const update_privilege = "http://tizen.org/privilege/led";
1868     const char *const check_start_bucket = "";
1869     const std::string username("sm_test_17_username");
1870     PolicyRequest addPolicyRequest;
1871     CynaraTestAdmin::Admin admin;
1872
1873     std::string smackLabel;
1874     generateAppLabel(update_app_id, smackLabel);
1875
1876     struct message {
1877         uid_t uid;
1878         gid_t gid;
1879     } msg;
1880
1881     int pipefd[2];
1882     int pipefd2[2];
1883     pid_t pid;
1884     int result = 0;
1885
1886     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1887     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
1888
1889     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1890     user.create();
1891
1892     pid = fork();
1893     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1894     if (pid != 0)//parent process
1895     {
1896         FdUniquePtr pipeptr(pipefd+1);
1897         close(pipefd[0]);
1898
1899         register_current_process_as_privilege_manager(user.getUid(), false);
1900
1901         //send info to child
1902         msg.uid = user.getUid();
1903         msg.gid = user.getGid();
1904
1905         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1906         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1907
1908         //wait for child
1909         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1910
1911         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1912                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1913
1914         pid = fork();
1915         if (pid != 0)//parent process
1916         {
1917             FdUniquePtr pipeptr(pipefd2+1);
1918             close(pipefd2[0]);
1919
1920             //send info to child
1921             msg.uid = user.getUid();
1922             msg.gid = user.getGid();
1923
1924             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
1925             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1926
1927             //wait for child
1928             RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1929
1930             //wait for child
1931             waitpid(-1, &result, 0);
1932
1933             admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1934                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
1935         }
1936         if(pid == 0)
1937         {
1938             FdUniquePtr pipeptr(pipefd2);
1939             close(pipefd2[1]);
1940
1941             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
1942             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1943
1944             //become admin privacy manager manager
1945             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1946             result = drop_root_privileges(msg.uid, msg.gid);
1947             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1948
1949             // delete this entry
1950             PolicyRequest deletePolicyRequest;
1951             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1952             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
1953
1954             deletePolicyRequest.addEntry(deleteEntry);
1955             Api::sendPolicy(deletePolicyRequest);
1956             exit(0);
1957         }
1958     }
1959     if(pid == 0)
1960     {
1961         FdUniquePtr pipeptr(pipefd);
1962         close(pipefd[1]);
1963
1964         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1965         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1966
1967         //become admin privacy manager manager
1968         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1969         result = drop_root_privileges(msg.uid, msg.gid);
1970         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1971
1972         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1973         entry.setLevel("Allow");
1974
1975         addPolicyRequest.addEntry(entry);
1976         Api::sendPolicy(addPolicyRequest);
1977         exit(0);
1978     }
1979 }
1980
1981 RUNNER_CHILD_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
1982 {
1983     const std::string username("sm_test_17_user_name");
1984
1985     struct message {
1986         uid_t uid;
1987         gid_t gid;
1988         unsigned int privileges_count;
1989     } msg;
1990
1991     int pipefd[2];
1992     pid_t pid;
1993     int result = 0;
1994
1995     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1996
1997     pid = fork();
1998     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1999     if (pid != 0)//parent process
2000     {
2001         FdUniquePtr pipeptr(pipefd+1);
2002         close(pipefd[0]);
2003
2004         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2005         user.create();
2006
2007         unsigned int privileges_count = 0;
2008
2009         register_current_process_as_privilege_manager(user.getUid(), false);
2010         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2011         ++privileges_count;
2012
2013         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2014             InstallRequest requestInst;
2015             requestInst.setAppId(MANY_APPS[i].c_str());
2016             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).c_str());
2017             requestInst.setUid(user.getUid());
2018
2019             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2020                 requestInst.addPrivilege(priv.c_str());
2021             };
2022
2023             Api::install(requestInst);
2024             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2025         };
2026
2027         //send info to child
2028         msg.uid = user.getUid();
2029         msg.gid = user.getGid();
2030         msg.privileges_count = privileges_count;
2031
2032         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2033         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2034
2035         //wait for child
2036         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2037     }
2038     if(pid == 0)
2039     {
2040         FdUniquePtr pipeptr(pipefd);
2041         close(pipefd[1]);
2042
2043         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2044         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2045
2046         //become admin privacy manager manager
2047         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2048         result = drop_root_privileges(msg.uid, msg.gid);
2049         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2050
2051         // filter by privilege
2052         std::vector<PolicyEntry> policyEntries;
2053         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2054         Api::getPolicy(filter, policyEntries);
2055
2056         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2057         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2058
2059         // filter by other privilege
2060         policyEntries.clear();
2061         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2062         Api::getPolicy(filter2, policyEntries);
2063
2064         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2065         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2066
2067         // filter by appId
2068         policyEntries.clear();
2069         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2070         Api::getPolicy(filter3, policyEntries);
2071
2072         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2073         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2074     }
2075 }
2076
2077 RUNNER_CHILD_TEST(security_manager_10_user_cynara_policy)
2078 {
2079     const char *const MAIN_BUCKET = "MAIN";
2080     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2081     const char *const ADMIN_BUCKET = "ADMIN";
2082     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2083     const std::string username("sm_test_10_user_cynara_policy");
2084     CynaraTestAdmin::Admin admin;
2085     std::string uid_string;
2086     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2087     user.create();
2088     user.getUidString(uid_string);
2089
2090     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2091     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2092     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2093
2094     user.remove();
2095     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2096
2097     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2098     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2099     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2100     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2101 }
2102
2103 RUNNER_CHILD_TEST(security_manager_11_security_manager_cmd_install)
2104 {
2105     int ret;
2106     const int SUCCESS = 0;
2107     const int FAILURE = 256;
2108     const std::string app_id = "security_manager_10_app";
2109     const std::string pkg_id = "security_manager_10_pkg";
2110     const std::string username("sm_test_10_user_name");
2111     std::string uid_string;
2112     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2113     user.create();
2114     user.getUidString(uid_string);
2115     const std::string path1 = "/home/" + username + "/p1";
2116     const std::string path2 = "/home/" + username + "/p2";
2117     const std::string pkgopt = " --pkg=" + pkg_id;
2118     const std::string appopt = " --app=" + app_id;
2119     const std::string uidopt = " --uid=" + uid_string;
2120
2121     mkdir(path1.c_str(), 0);
2122     mkdir(path2.c_str(), 0);
2123
2124     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2125
2126     struct operation {
2127         std::string command;
2128         int expected_result;
2129     };
2130     std::vector<struct operation> operations = {
2131             {"security-manager-cmd", FAILURE},//no option
2132             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2133             {"security-manager-cmd --help", SUCCESS},
2134             {"security-manager-cmd --install", FAILURE},//no params
2135             {"security-manager-cmd -i", FAILURE},//no params
2136             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2137             {installcmd, SUCCESS},
2138             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2139             {installcmd + " --path " + path1 + " private", SUCCESS},
2140             {installcmd + " --path " + path1, FAILURE},//no path type
2141             {installcmd + " --path " + path1 + " private" + " --path " + path2 + " private", SUCCESS},
2142             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " public", FAILURE},//wrong path type
2143             {installcmd + " --path " + path1 + " private" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2144     };
2145
2146     for (auto &op : operations) {
2147         ret = system(op.command.c_str());
2148         RUNNER_ASSERT_MSG(ret == op.expected_result,
2149                 "Unexpected result for command '" << op.command <<"': "
2150                 << ret << " Expected was: "<< op.expected_result);
2151     }
2152 }
2153
2154 RUNNER_CHILD_TEST(security_manager_12_security_manager_cmd_users)
2155 {
2156     int ret;
2157     const int SUCCESS = 0;
2158     const int FAILURE = 256;
2159     const std::string username("sm_test_11_user_name");
2160     std::string uid_string;
2161     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2162     user.create();
2163     user.getUidString(uid_string);
2164     const std::string uidopt = " --uid=" + uid_string;
2165
2166     struct operation {
2167         std::string command;
2168         int expected_result;
2169     };
2170     std::vector<struct operation> operations = {
2171             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2172             {"security-manager-cmd -m", FAILURE},//no params
2173             {"security-manager-cmd -mr", FAILURE},//no uid
2174             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2175             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2176             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2177             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2178             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2179             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2180             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2181             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2182     };
2183
2184     for (auto &op : operations) {
2185         ret = system(op.command.c_str());
2186         RUNNER_ASSERT_MSG(ret == op.expected_result,
2187                 "Unexpected result for command '" << op.command <<"': "
2188                 << ret << " Expected was: "<< op.expected_result);
2189     }
2190 }
2191
2192 RUNNER_MULTIPROCESS_TEST(security_manager_13_security_manager_admin_deny_user_priv)
2193 {
2194     const int BUFFER_SIZE = 128;
2195     struct message {
2196         uid_t uid;
2197         gid_t gid;
2198         char buf[BUFFER_SIZE];
2199     } msg;
2200
2201     privileges_t admin_required_privs = {
2202             "http://tizen.org/privilege/systemsettings.admin",
2203             "http://tizen.org/privilege/systemsettings"};
2204     privileges_t manifest_privs = {
2205             "http://tizen.org/privilege/internet",
2206             "http://tizen.org/privilege/camera"};
2207     privileges_t real_privs_allow = {"http://tizen.org/privilege/camera"};
2208     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2209
2210     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2211     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2212     const std::string app_id = "sm_test_13_SOME_APP";
2213     const std::string pkg_id = "sm_test_13_SOME_PKG";
2214
2215     int pipefd[2];
2216     pid_t pid;
2217     int result = 0;
2218
2219     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2220     pid = fork();
2221     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2222     if (pid != 0)//parent process
2223     {
2224         std::string childuidstr;
2225         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, true);
2226         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, true);
2227
2228         InstallRequest request,request2;
2229         FdUniquePtr pipeptr(pipefd+1);
2230         close(pipefd[0]);
2231
2232         admin.create();
2233         child.create();
2234         child.getUidString(childuidstr);
2235
2236         //install privacy manager for admin
2237         request.setAppId(pirivman_id.c_str());
2238         request.setPkgId(pirivman_pkg_id.c_str());
2239         request.setUid(admin.getUid());
2240         for (auto &priv: admin_required_privs)
2241             request.addPrivilege(priv.c_str());
2242         Api::install(request);
2243
2244         //install app for child that has internet privilege
2245         request2.setAppId(app_id.c_str());
2246         request2.setPkgId(pkg_id.c_str());
2247         request2.setUid(child.getUid());
2248         for (auto &priv: manifest_privs)
2249             request2.addPrivilege(priv.c_str());
2250         Api::install(request2);
2251
2252         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2253                               manifest_privs, SM_NO_PRIVILEGES);
2254
2255         //send info to child
2256         msg.uid = admin.getUid();
2257         msg.gid = admin.getGid();
2258         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2259
2260         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2261         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2262
2263         //wait for child
2264         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2265
2266         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2267                               real_privs_allow, real_privs_deny);
2268     }
2269     if (pid == 0)//child
2270     {
2271         FdUniquePtr pipeptr(pipefd);
2272         close(pipefd[1]);
2273
2274         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2275         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2276
2277         //become admin privacy manager manager
2278         Api::setProcessLabel(pirivman_id.c_str());
2279         result = drop_root_privileges(msg.uid, msg.gid);
2280         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2281         PolicyRequest addPolicyReq;
2282         //change rights
2283         for (auto &denypriv:real_privs_deny) {
2284             /*this entry will deny some privileges for user whose uid (as c string)
2285               was sent in message's buf field.
2286               That user would be denying internet for child in this case*/
2287             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2288             entry.setMaxLevel("Deny");
2289             addPolicyReq.addEntry(entry);
2290         }
2291         Api::sendPolicy(addPolicyReq);
2292         exit(0);
2293     }
2294 }
2295
2296 int main(int argc, char *argv[])
2297 {
2298     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
2299 }