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