Fix security_manager_11_security_manager_cmd_install
[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         const std::string &appId, const std::string &pkgId)
601 {
602     struct tzplatform_context *tzCtxPtr = nullptr;
603
604     RUNNER_ASSERT(0 == tzplatform_context_create(&tzCtxPtr));
605     TzPlatformContextPtr tzCtxPtrSmart(tzCtxPtr);
606
607     RUNNER_ASSERT_MSG(0 == tzplatform_context_set_user(tzCtxPtr, user.getUid()),
608                       "Unable to set user <" << user.getUserName() << "> for tzplatform context");
609
610     const char *appDir = tzplatform_context_getenv(tzCtxPtr,
611                                 getGlobalUserId() == user.getUid() ? TZ_SYS_RW_APP : TZ_USER_APP);
612     RUNNER_ASSERT_MSG(nullptr != appDir,
613                       "tzplatform_context_getenv failed"
614                           << "for getting sys rw app of user <" << user.getUserName() << ">");
615
616     return std::string(appDir) + "/" + pkgId + "/" + appId;
617 }
618
619 static const std::string nonAppDirPath(const TemporaryTestUser &user)
620 {
621     return TMP_DIR + "/" + user.getUserName();
622 }
623
624 static const std::string uidToStr(const uid_t uid)
625 {
626     return std::to_string(static_cast<unsigned int>(uid));
627 }
628
629 static void install_and_check(const char *const sm_app_id,
630                               const char *const sm_pkg_id,
631                               const TemporaryTestUser& user,
632                               const std::string &appDir,
633                               bool requestUid)
634 {
635     InstallRequest requestPublic;
636
637     //install app for non-root user and try to register public path (should fail)
638     prepare_request(requestPublic, sm_app_id, sm_pkg_id,
639                     SECURITY_MANAGER_PATH_PUBLIC, appDir.c_str(),
640                     requestUid ? user.getUid() : 0);
641
642     Api::install(requestPublic, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
643
644     InstallRequest requestPrivate;
645
646     //install app for non-root user
647     //should fail (users may only register folders inside their home)
648     prepare_request(requestPrivate, sm_app_id, sm_pkg_id,
649                     SECURITY_MANAGER_PATH_RW, SM_RW_PATH,
650                     requestUid ? user.getUid() : 0);
651
652     Api::install(requestPrivate, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
653
654     InstallRequest requestPrivateUser;
655
656     //install app for non-root user
657     //should succeed - this time i register folder inside user's home dir
658     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
659                     SECURITY_MANAGER_PATH_RW, appDir.c_str(),
660                     requestUid ? user.getUid() : 0);
661
662     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
663         requestPrivateUser.addPrivilege(privilege.c_str());
664
665     Api::install(requestPrivateUser);
666
667     check_app_permissions(sm_app_id, sm_pkg_id,
668                           uidToStr(user.getUid()).c_str(),
669                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
670 }
671
672 static void createTestDir(const std::string &dir)
673 {
674     mode_t dirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
675     mode_t execFileMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
676     mode_t normalFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
677
678     mktreeSafe(dir, dirMode);
679     creatSafe(dir + "/" + EXEC_FILE, execFileMode);
680     creatSafe(dir + "/" + NORMAL_FILE, normalFileMode);
681     symlinkSafe(dir + "/" + EXEC_FILE, dir + "/" + LINK_PREFIX + EXEC_FILE);
682     symlinkSafe(dir + "/" + NORMAL_FILE, dir + "/" + LINK_PREFIX + NORMAL_FILE);
683 }
684
685 static void createInnerAppDir(const std::string &dir, const std::string &nonAppDir)
686 {
687     createTestDir(dir);
688
689     symlinkSafe(nonAppDir, dir + "/" + LINK_PREFIX + "non_app_dir");
690     symlinkSafe(nonAppDir + "/" + EXEC_FILE,
691                 dir + "/" + LINK_PREFIX + "non_app_" + EXEC_FILE);
692     symlinkSafe(nonAppDir + "/" + NORMAL_FILE,
693                 dir + "/" + LINK_PREFIX + "non_app_" + NORMAL_FILE);
694 }
695
696 static void generateAppDir(const TemporaryTestUser &user,
697        const std::string &appId, const std::string &pkgId)
698 {
699     const std::string dir = appDirPath(user, appId, pkgId);
700     const std::string nonAppDir = nonAppDirPath(user);
701
702     createInnerAppDir(dir, nonAppDir);
703     createInnerAppDir(dir + "/.inner_dir", nonAppDir);
704     createInnerAppDir(dir + "/inner_dir", nonAppDir);
705 }
706
707 static void generateNonAppDir(const TemporaryTestUser &user)
708 {
709     const std::string dir = nonAppDirPath(user);
710
711     createTestDir(dir);
712     createTestDir(dir + "/.inner_dir");
713     createTestDir(dir + "/inner_dir");
714 }
715
716 static void createTestDirs(const TemporaryTestUser &user,
717        const std::string &appId, const std::string &pkgId)
718 {
719     generateAppDir(user, appId, pkgId);
720     generateNonAppDir(user);
721 }
722
723 static void removeTestDirs(const TemporaryTestUser &user,
724        const std::string &appId, const std::string &pkgId)
725 {
726     removeDir(appDirPath(user, appId, pkgId));
727     removeDir(nonAppDirPath(user));
728 }
729
730 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
731 {
732     int result;
733     const char *const sm_app_id = "sm_test_04a_app_id_uid";
734     const char *const sm_pkg_id = "sm_test_04a_pkg_id_uid";
735     const std::string new_user_name = "sm_test_04a_user_name";
736
737     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
738     testUser.create();
739
740     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
741     createTestDirs(testUser, sm_app_id, sm_pkg_id);
742
743     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
744
745     //switch user to non-root
746     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
747     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
748
749     install_and_check(sm_app_id, sm_pkg_id, testUser, userAppDirPath, false);
750
751     //uninstall app as non-root user
752     InstallRequest request;
753     request.setAppId(sm_app_id);
754
755     Api::uninstall(request);
756
757     check_app_permissions(sm_app_id, sm_pkg_id,
758                           uidToStr(testUser.getUid()).c_str(),
759                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
760 }
761
762 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user)
763 {
764     int result;
765     const char *const sm_app_id = "sm_test_04b_app_id_uid";
766     const char *const sm_pkg_id = "sm_test_04b_pkg_id_uid";
767     const std::string new_user_name = "sm_test_04b_user_name";
768
769     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
770     testUser.create();
771
772     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
773     createTestDirs(testUser, sm_app_id, sm_pkg_id);
774
775     install_and_check(sm_app_id, sm_pkg_id, testUser, appDirPath(testUser, sm_app_id, sm_pkg_id), true);
776
777     //switch user to non-root - root may not uninstall apps for specified users
778     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
779     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
780
781     //uninstall app as non-root user
782     InstallRequest request;
783     request.setAppId(sm_app_id);
784
785     Api::uninstall(request);
786
787     check_app_permissions(sm_app_id, sm_pkg_id,
788                           uidToStr(testUser.getUid()).c_str(),
789                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
790 }
791
792
793 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
794 {
795     int result;
796     CapsSetsUniquePtr caps, caps_empty(cap_init());
797
798     caps.reset(cap_from_text("all=eip"));
799     RUNNER_ASSERT_MSG(caps, "can't convert capabilities from text");
800     result = cap_set_proc(caps.get());
801     RUNNER_ASSERT_MSG(result == 0,
802         "can't set capabilities. Result: " << result);
803
804     Api::dropProcessPrivileges();
805
806     caps.reset(cap_get_proc());
807     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
808
809     result = cap_compare(caps.get(), caps_empty.get());
810     RUNNER_ASSERT_MSG(result == 0,
811         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
812 }
813
814 RUNNER_CHILD_TEST(security_manager_06_install_app_offline)
815 {
816     const char *const app_id = "sm_test_06_app_id_install_app_offline";
817     const char *const pkg_id = "sm_test_06_pkg_id_install_app_offline";
818
819     // Uninstall app on-line, off-line mode doesn't support it
820     uninstall_app(app_id, pkg_id, true);
821
822     ServiceManager("security-manager.service").stopService();
823
824     ServiceManager serviceManager("security-manager.socket");
825     serviceManager.stopService();
826
827     install_app(app_id, pkg_id);
828
829     serviceManager.startService();
830
831     uninstall_app(app_id, pkg_id, true);
832 }
833
834 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
835 {
836     const char *const sm_app_id = "sm_test_07_app_id_user";
837     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
838     const std::string new_user_name = "sm_test_07_user_name";
839     std::string uid_string;
840     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
841     test_user.create();
842     test_user.getUidString(uid_string);
843
844     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
845     createTestDirs(test_user, sm_app_id, sm_pkg_id);
846
847     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
848
849     check_app_after_install(sm_app_id, sm_pkg_id);
850
851     test_user.remove();
852
853     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
854
855     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
856 }
857
858 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
859 {
860     UserRequest addUserRequest;
861
862     const char *const sm_app_id = "sm_test_08_app_id_user";
863     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
864     const std::string new_user_name = "sm_test_08_user_name";
865     std::string uid_string;
866
867     // gumd user add
868     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
869     test_user.create();
870     test_user.getUidString(uid_string);
871
872     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
873     createTestDirs(test_user, sm_app_id, sm_pkg_id);
874
875     addUserRequest.setUid(test_user.getUid());
876     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
877
878     //sm user add
879     Api::addUser(addUserRequest);
880
881     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
882
883     check_app_after_install(sm_app_id, sm_pkg_id);
884
885     test_user.remove();
886
887     UserRequest deleteUserRequest;
888     deleteUserRequest.setUid(test_user.getUid());
889
890     Api::deleteUser(deleteUserRequest);
891
892     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
893
894     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
895 }
896
897 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
898 {
899     const char *const app_id = "security_manager_09_add_user_offline_app";
900     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
901     const std::string new_user_name("sm_test_09_user_name");
902
903     ServiceManager("security-manager.service").stopService();
904
905     ServiceManager serviceManager("security-manager.socket");
906     serviceManager.stopService();
907
908     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, true);
909     test_user.create();
910
911     removeTestDirs(test_user, app_id, pkg_id);
912     createTestDirs(test_user, app_id, pkg_id);
913
914     install_app(app_id, pkg_id, test_user.getUid());
915
916     check_app_after_install(app_id, pkg_id);
917
918     serviceManager.startService();
919
920     test_user.remove();
921
922     check_app_after_uninstall(app_id, pkg_id, true);
923 }
924
925 RUNNER_MULTIPROCESS_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
926 {
927     //TEST DATA
928     const std::string username("sm_test_10_user_name");
929     unsigned int privileges_count = 0;
930
931     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
932     std::map<std::string, std::set<std::string>> apps2PrivsMap;
933
934     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
935         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
936             MANY_APPS.at(i), std::set<std::string>(
937                 MANY_APPS_PRIVILEGES.at(i).begin(),
938                 MANY_APPS_PRIVILEGES.at(i).end())));
939         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
940     };
941
942     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
943         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
944     ++privileges_count;
945     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
946     //TEST DATA END
947
948     sem_t *mutex;
949     errno = 0;
950     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
951     errno = 0;
952     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
953     pid_t pid = fork();
954
955     if (pid != 0) { //parent process
956         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
957         tmpUser.create();
958
959         for(const auto &user : users2AppsMap) {
960
961             for(const auto &app : user.second) {
962                 InstallRequest requestInst;
963                 requestInst.setAppId(app.first.c_str());
964                 try {
965                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
966                 } catch (const std::out_of_range &e) {
967                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
968                 };
969                 requestInst.setUid(tmpUser.getUid());
970
971                 for (const auto &privilege : app.second) {
972                     requestInst.addPrivilege(privilege.c_str());
973                 };
974
975                 Api::install(requestInst);
976             };
977
978             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
979         };
980         //Start child process
981         errno = 0;
982         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
983
984         int status;
985         wait(&status);
986
987         tmpUser.remove();
988     };
989
990     if (pid == 0) { //child process
991         errno = 0;
992         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
993         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
994
995         struct passwd *pw = getUserStruct(username);
996         register_current_process_as_privilege_manager(pw->pw_uid);
997         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
998         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
999
1000         std::vector<PolicyEntry> policyEntries;
1001         PolicyEntry filter;
1002         Api::getPolicy(filter, policyEntries);
1003
1004         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1005         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1006
1007         for (const auto &policyEntry : policyEntries) {
1008             std::string user = policyEntry.getUser();
1009             std::string app = policyEntry.getAppId();
1010             std::string privilege = policyEntry.getPrivilege();
1011
1012             try {
1013                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1014                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1015                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1016                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1017             } catch (const std::out_of_range &e) {
1018                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1019             } catch (const std::invalid_argument& e) {
1020                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1021             };
1022         };
1023         exit(0);
1024     };
1025 }
1026
1027 RUNNER_MULTIPROCESS_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1028 {
1029     //TEST DATA
1030     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1031     unsigned int privileges_count = 0;
1032
1033     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1034     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1035
1036     for (const auto &username : usernames) {
1037         //Only entries for one of the users will be listed
1038         privileges_count = 0;
1039
1040         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1041             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1042                 MANY_APPS.at(i), std::set<std::string>(
1043                     MANY_APPS_PRIVILEGES.at(i).begin(),
1044                     MANY_APPS_PRIVILEGES.at(i).end())));
1045             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1046         };
1047
1048         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1049     };
1050
1051     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1052         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1053
1054     ++privileges_count;
1055     //TEST DATA END
1056
1057     sem_t *mutex;
1058     errno = 0;
1059     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1060     errno = 0;
1061     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1062     pid_t pid = fork();
1063
1064     if (pid != 0) { //parent process
1065         std::vector<TemporaryTestUser> users = {
1066             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1067             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1068             };
1069
1070         users.at(0).create();
1071         users.at(1).create();
1072
1073         //Install apps for both users
1074         for(const auto &user : users) {
1075             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1076                 InstallRequest requestInst;
1077                 requestInst.setAppId(app.first.c_str());
1078                 try {
1079                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1080                 } catch (const std::out_of_range &e) {
1081                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1082                 };
1083                 requestInst.setUid(user.getUid());
1084
1085                 for (const auto &privilege : app.second) {
1086                     requestInst.addPrivilege(privilege.c_str());
1087                 };
1088
1089                 Api::install(requestInst);
1090             };
1091
1092             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1093         };
1094         //Start child
1095         errno = 0;
1096         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1097
1098         int status;
1099         wait(&status);
1100
1101         for(auto &user : users) {
1102             user.remove();
1103         };
1104     };
1105
1106     if (pid == 0) {
1107         errno = 0;
1108         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1109         struct passwd *pw = getUserStruct(usernames.at(0));
1110         register_current_process_as_privilege_manager(pw->pw_uid);
1111
1112         //change uid to normal user
1113         errno = 0;
1114         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1115         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1116
1117         std::vector<PolicyEntry> policyEntries;
1118         PolicyEntry filter;
1119
1120         //this call should only return privileges belonging to the current uid
1121         Api::getPolicy(filter, policyEntries);
1122
1123         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1124         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1125
1126         for (const auto &policyEntry : policyEntries) {
1127             std::string user = policyEntry.getUser();
1128             std::string app = policyEntry.getAppId();
1129             std::string privilege = policyEntry.getPrivilege();
1130
1131             try {
1132                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1133                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1134                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1135                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1136             } catch (const std::out_of_range &e) {
1137                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1138             } catch (const std::invalid_argument& e) {
1139                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1140             };
1141         };
1142         exit(0);
1143     };
1144 }
1145
1146 RUNNER_MULTIPROCESS_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1147 {
1148     //TEST DATA
1149     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1150     unsigned int privileges_count = 0;
1151
1152     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1153     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1154
1155     for (const auto &username : usernames) {
1156
1157         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1158             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1159                 MANY_APPS.at(i), std::set<std::string>(
1160                     MANY_APPS_PRIVILEGES.at(i).begin(),
1161                     MANY_APPS_PRIVILEGES.at(i).end())));
1162             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1163         };
1164
1165         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1166     };
1167
1168     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1169         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1170
1171     privileges_count += 2;
1172     //TEST DATA END
1173
1174     sem_t *mutex;
1175     errno = 0;
1176     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1177     errno = 0;
1178     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1179     pid_t pid = fork();
1180
1181     if (pid != 0) { //parent process
1182         std::vector<TemporaryTestUser> users = {
1183             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1184             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1185             };
1186
1187         users.at(0).create();
1188         users.at(1).create();
1189         //Install apps for both users
1190         for(const auto &user : users) {
1191             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1192                 InstallRequest requestInst;
1193                 requestInst.setAppId(app.first.c_str());
1194                 try {
1195                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1196                 } catch (const std::out_of_range &e) {
1197                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1198                 };
1199                 requestInst.setUid(user.getUid());
1200
1201                 for (const auto &privilege : app.second) {
1202                     requestInst.addPrivilege(privilege.c_str());
1203                 };
1204
1205                 Api::install(requestInst);
1206             };
1207
1208             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1209         };
1210
1211         //Start child
1212         errno = 0;
1213         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1214
1215         //Wait for child to finish
1216         int status;
1217         wait(&status);
1218
1219         for(auto &user : users) {
1220             user.remove();
1221         };
1222     };
1223
1224     if (pid == 0) { //child process
1225         errno = 0;
1226         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1227
1228         struct passwd *pw = getUserStruct(usernames.at(1));
1229         register_current_process_as_privilege_manager(pw->pw_uid, true);
1230
1231         //change uid to normal user
1232         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1233         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1234
1235         std::vector<PolicyEntry> policyEntries;
1236         PolicyEntry filter;
1237         //this call should succeed as the calling user is privileged
1238         Api::getPolicy(filter, policyEntries);
1239
1240         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1241         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1242
1243         for (const auto &policyEntry : policyEntries) {
1244             std::string user = policyEntry.getUser();
1245             std::string app = policyEntry.getAppId();
1246             std::string privilege = policyEntry.getPrivilege();
1247
1248             try {
1249                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1250                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1251                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1252                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1253             } catch (const std::out_of_range &e) {
1254                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1255             } catch (const std::invalid_argument& e) {
1256                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1257             };
1258         };
1259
1260         exit(0);
1261     };
1262 }
1263
1264 RUNNER_MULTIPROCESS_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1265 {
1266     //TEST DATA
1267     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1268
1269     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1270     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1271
1272     for (const auto &username : usernames) {
1273
1274         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1275             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1276                 MANY_APPS.at(i), std::set<std::string>(
1277                     MANY_APPS_PRIVILEGES.at(i).begin(),
1278                     MANY_APPS_PRIVILEGES.at(i).end())));
1279         };
1280
1281         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1282     };
1283
1284     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1285         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1286
1287     //TEST DATA END
1288
1289     pid_t pid[2];
1290     sem_t *mutex[2];
1291     errno = 0;
1292     RUNNER_ASSERT_MSG(((mutex[0] = sem_open("mutex_1", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #1, errno: " << errno);
1293     errno = 0;
1294     RUNNER_ASSERT_MSG(((mutex[1] = sem_open("mutex_2", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #2, errno: " << errno);
1295     errno = 0;
1296     RUNNER_ASSERT_MSG(sem_init(mutex[0], 1, 0) == 0, "failed to setup mutex #1, errno: " << errno);
1297     errno = 0;
1298     RUNNER_ASSERT_MSG(sem_init(mutex[1], 1, 0) == 0, "failed to setup mutex #2, errno: " << errno);
1299     std::vector<PolicyEntry> policyEntries;
1300
1301     pid[0] = fork();
1302
1303     if(pid[0] == 0) { //child #1 process
1304         RUNNER_ASSERT_MSG(sem_wait(mutex[0]) == 0, "sem_wait in child #1 failed, errno: " << errno);
1305         struct passwd *pw = getUserStruct(usernames.at(0));
1306         register_current_process_as_privilege_manager(pw->pw_uid);
1307
1308         //change uid to normal user
1309         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1310         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1311
1312         PolicyEntry filter;
1313         PolicyRequest policyRequest;
1314         //this call should succeed as the calling user is privileged
1315         Api::getPolicyForSelf(filter, policyEntries);
1316
1317         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1318
1319         PolicyEntry policyEntry(
1320                 MANY_APPS[0],
1321                 std::to_string(pw->pw_uid),
1322                 "http://tizen.org/privilege/internet"
1323                 );
1324         policyEntry.setLevel("Deny");
1325
1326         policyRequest.addEntry(policyEntry);
1327         policyEntry = PolicyEntry(
1328                 MANY_APPS[1],
1329                 std::to_string(pw->pw_uid),
1330                 "http://tizen.org/privilege/location"
1331                 );
1332         policyEntry.setLevel("Deny");
1333
1334         policyRequest.addEntry(policyEntry);
1335         Api::sendPolicy(policyRequest);
1336         Api::getPolicyForSelf(filter, policyEntries);
1337
1338         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1339         exit(0);
1340     };
1341
1342     if (pid[0] != 0) {//parent process
1343         pid[1] = fork();
1344
1345         if (pid[1] == 0) { //child #2 process
1346             errno = 0;
1347             RUNNER_ASSERT_MSG(sem_wait(mutex[1]) == 0, "sem_wait in child #2 failed, errno: " << errno);
1348             struct passwd *pw_target = getUserStruct(usernames.at(0));
1349             struct passwd *pw = getUserStruct(usernames.at(1));
1350             register_current_process_as_privilege_manager(pw->pw_uid);
1351
1352             //change uid to normal user
1353             int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1354             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1355
1356             PolicyEntry filter = PolicyEntry(
1357                         SECURITY_MANAGER_ANY,
1358                         std::to_string(pw_target->pw_uid),
1359                         SECURITY_MANAGER_ANY
1360                         );
1361
1362             //U2 requests contents of U1 privacy manager - should fail
1363             Api::getPolicyForSelf(filter, policyEntries);
1364             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1365
1366             filter = PolicyEntry(
1367                         SECURITY_MANAGER_ANY,
1368                         SECURITY_MANAGER_ANY,
1369                         SECURITY_MANAGER_ANY
1370                         );
1371
1372             policyEntries.clear();
1373
1374             //U2 requests contents of ADMIN bucket - should fail
1375             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1376             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1377             exit(0);
1378         };
1379
1380         if (pid[1] != 0) { //parent
1381
1382             std::vector<TemporaryTestUser> users = {
1383                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1384                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1385                 };
1386
1387             users.at(0).create();
1388             users.at(1).create();
1389
1390             //Install apps for both users
1391             for(const auto &user : users2AppsMap) {
1392
1393                 for(const auto &app : user.second) {
1394                     InstallRequest requestInst;
1395                     requestInst.setAppId(app.first.c_str());
1396                     try {
1397                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1398                     } catch (const std::out_of_range &e) {
1399                         RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1400                     };
1401                     requestInst.setUid(users.at(0).getUid());
1402
1403                     for (const auto &privilege : app.second) {
1404                         requestInst.addPrivilege(privilege.c_str());
1405                     };
1406
1407                     Api::install(requestInst);
1408                 };
1409
1410                 //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1411             };
1412
1413             int status;
1414             //Start child #1
1415             errno = 0;
1416             RUNNER_ASSERT_MSG(sem_post(mutex[0]) ==  0, "Error while opening mutex #1, errno: " << errno);
1417
1418             //Wait until child #1 finishes
1419             pid_t ret = wait(&status);
1420             RUNNER_ASSERT_MSG((ret != -1) && WIFEXITED(status), "Updating privileges failed");
1421
1422             //Start child #2
1423             errno = 0;
1424             RUNNER_ASSERT_MSG(sem_post(mutex[1]) ==  0, "Error while opening mutex #2, errno: " << errno);
1425             //Wait until child #2 finishes
1426             ret = wait(&status);
1427             RUNNER_ASSERT_MSG((ret =-1) && WIFEXITED(status), "Listing privileges failed");
1428
1429             for(auto &user : users) {
1430                 user.remove();
1431             };
1432
1433             sem_close(mutex[0]);
1434             sem_close(mutex[1]);
1435         };
1436     };
1437 }
1438
1439 RUNNER_MULTIPROCESS_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1440 {
1441     //TEST DATA
1442     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1443     unsigned int privileges_count = 0;
1444
1445     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1446     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1447
1448     for (const auto &username : usernames) {
1449
1450         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1451             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1452                 MANY_APPS.at(i), std::set<std::string>(
1453                     MANY_APPS_PRIVILEGES.at(i).begin(),
1454                     MANY_APPS_PRIVILEGES.at(i).end())));
1455             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1456         };
1457
1458         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1459     };
1460
1461     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1462         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1463
1464     privileges_count += 2;
1465     //TEST DATA END
1466     sem_t *mutex;
1467     errno = 0;
1468     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1469     errno = 0;
1470     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1471
1472     pid_t pid = fork();
1473     if (pid != 0) {
1474         std::vector<TemporaryTestUser> users = {
1475             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1476             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1477             };
1478
1479         users.at(0).create();
1480         users.at(1).create();
1481
1482         //Install apps for both users
1483         for(const auto &user : users) {
1484
1485             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1486                 InstallRequest requestInst;
1487                 requestInst.setAppId(app.first.c_str());
1488                 try {
1489                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1490                 } catch (const std::out_of_range &e) {
1491                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1492                 };
1493                 requestInst.setUid(user.getUid());
1494
1495                 for (const auto &privilege : app.second) {
1496                     requestInst.addPrivilege(privilege.c_str());
1497                 };
1498
1499                 Api::install(requestInst);
1500             };
1501         };
1502         //Start child process
1503         errno = 0;
1504         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1505         int status;
1506         //Wait for child process to finish
1507         wait(&status);
1508
1509         //switch back to root
1510         for(auto &user : users) {
1511             user.remove();
1512         };
1513
1514         sem_close(mutex);
1515     }
1516
1517     if (pid == 0) { //child process
1518         errno = 0;
1519         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
1520
1521         struct passwd *pw = getUserStruct(usernames.at(0));
1522         register_current_process_as_privilege_manager(pw->pw_uid, true);
1523
1524         //change uid to normal user
1525         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1526         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1527
1528         PolicyRequest *policyRequest = new PolicyRequest();
1529         PolicyEntry filter;
1530         std::vector<PolicyEntry> policyEntries;
1531         //this call should succeed as the calling user is privileged
1532         Api::getPolicyForSelf(filter, policyEntries);
1533
1534         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1535
1536         PolicyEntry policyEntry(
1537                 SECURITY_MANAGER_ANY,
1538                 SECURITY_MANAGER_ANY,
1539                 "http://tizen.org/privilege/internet"
1540                 );
1541         policyEntry.setMaxLevel("Deny");
1542
1543         policyRequest->addEntry(policyEntry);
1544         policyEntry = PolicyEntry(
1545                 SECURITY_MANAGER_ANY,
1546                 SECURITY_MANAGER_ANY,
1547                 "http://tizen.org/privilege/location"
1548                 );
1549         policyEntry.setMaxLevel("Deny");
1550
1551         policyRequest->addEntry(policyEntry);
1552         Api::sendPolicy(*policyRequest);
1553         Api::getPolicyForAdmin(filter, policyEntries);
1554
1555         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1556
1557         delete policyRequest;
1558         policyRequest = new PolicyRequest();
1559         policyEntry = PolicyEntry(
1560                 SECURITY_MANAGER_ANY,
1561                 SECURITY_MANAGER_ANY,
1562                 "http://tizen.org/privilege/internet"
1563                 );
1564         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1565         policyRequest->addEntry(policyEntry);
1566
1567         policyEntry = PolicyEntry(
1568                 SECURITY_MANAGER_ANY,
1569                 SECURITY_MANAGER_ANY,
1570                 "http://tizen.org/privilege/location"
1571                 );
1572         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1573
1574         policyRequest->addEntry(policyEntry);
1575         Api::sendPolicy(*policyRequest);
1576
1577         policyEntries.clear();
1578         Api::getPolicyForAdmin(filter, policyEntries);
1579         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1580
1581         delete policyRequest;
1582
1583         exit(0);
1584     };
1585
1586 }
1587
1588 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1589 {
1590     const char *const update_app_id = "security_manager_15_update_app_id";
1591     const char *const update_privilege = "http://tizen.org/privilege/led";
1592     const char *const check_start_bucket = "ADMIN";
1593     const std::string username("sm_test_15_username");
1594     PolicyRequest addPolicyRequest;
1595     CynaraTestAdmin::Admin admin;
1596
1597     struct message {
1598         uid_t uid;
1599         gid_t gid;
1600     } msg;
1601
1602     int pipefd[2];
1603     pid_t pid;
1604     int result = 0;
1605
1606     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1607
1608     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1609     user.create();
1610
1611     pid = fork();
1612     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1613     if (pid != 0)//parent process
1614     {
1615         FdUniquePtr pipeptr(pipefd+1);
1616         close(pipefd[0]);
1617
1618         register_current_process_as_privilege_manager(user.getUid(), true);
1619
1620         //send info to child
1621         msg.uid = user.getUid();
1622         msg.gid = user.getGid();
1623
1624         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1625         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1626
1627         //wait for child
1628         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1629
1630         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1631                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1632     }
1633     if(pid == 0)
1634     {
1635         FdUniquePtr pipeptr(pipefd);
1636         close(pipefd[1]);
1637
1638         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1639         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1640
1641         //become admin privacy manager manager
1642         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1643         result = drop_root_privileges(msg.uid, msg.gid);
1644         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1645
1646         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1647         entry.setMaxLevel("Allow");
1648
1649         addPolicyRequest.addEntry(entry);
1650         Api::sendPolicy(addPolicyRequest);
1651         exit(0);
1652     }
1653 }
1654
1655 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1656 {
1657     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1658     const char *const update_privilege = "http://tizen.org/privilege/led";
1659     const char *const check_start_bucket = "ADMIN";
1660     const std::string username("sm_test_15_username");
1661     PolicyRequest addPolicyRequest;
1662     CynaraTestAdmin::Admin admin;
1663
1664     struct message {
1665         uid_t uid;
1666         gid_t gid;
1667     } msg;
1668
1669     int pipefd[2];
1670     pid_t pid;
1671     int result = 0;
1672
1673     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1674
1675     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1676     user.create();
1677
1678     pid = fork();
1679     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1680     if (pid != 0)//parent process
1681     {
1682         FdUniquePtr pipeptr(pipefd+1);
1683         close(pipefd[0]);
1684
1685         register_current_process_as_privilege_manager(user.getUid(), true);
1686
1687         //send info to child
1688         msg.uid = user.getUid();
1689         msg.gid = user.getGid();
1690
1691         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1692         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1693
1694         //wait for child
1695         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1696
1697         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_other_app_id).c_str(),
1698                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1699     }
1700     if(pid == 0)
1701     {
1702         FdUniquePtr pipeptr(pipefd);
1703         close(pipefd[1]);
1704
1705         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1706         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1707
1708         //become admin privacy manager manager
1709         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1710         result = drop_root_privileges(msg.uid, msg.gid);
1711         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1712
1713         // use wildcard as appId
1714         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1715         entry.setMaxLevel("Allow");
1716
1717         addPolicyRequest.addEntry(entry);
1718         Api::sendPolicy(addPolicyRequest);
1719         exit(0);
1720     }
1721 }
1722
1723 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1724 {
1725     const char *const update_app_id = "security_manager_15_update_app_id";
1726     const char *const update_privilege = "http://tizen.org/privilege/led";
1727     const char *const check_start_bucket = "";
1728     const std::string username("sm_test_15_username");
1729     PolicyRequest addPolicyRequest;
1730     CynaraTestAdmin::Admin admin;
1731
1732     struct message {
1733         uid_t uid;
1734         gid_t gid;
1735     } msg;
1736
1737     int pipefd[2];
1738     pid_t pid;
1739     int result = 0;
1740
1741     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1742
1743     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1744     user.create();
1745
1746     pid = fork();
1747     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1748     if (pid != 0)//parent process
1749     {
1750         FdUniquePtr pipeptr(pipefd+1);
1751         close(pipefd[0]);
1752
1753         register_current_process_as_privilege_manager(user.getUid(), false);
1754
1755         //send info to child
1756         msg.uid = user.getUid();
1757         msg.gid = user.getGid();
1758
1759         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1760         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1761
1762         //wait for child
1763         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1764
1765         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1766                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1767     }
1768     if(pid == 0)
1769     {
1770         FdUniquePtr pipeptr(pipefd);
1771         close(pipefd[1]);
1772
1773         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1774         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1775
1776         //become admin privacy manager manager
1777         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1778         result = drop_root_privileges(msg.uid, msg.gid);
1779         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1780
1781         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1782         entry.setLevel("Allow");
1783
1784         addPolicyRequest.addEntry(entry);
1785         Api::sendPolicy(addPolicyRequest);
1786         exit(0);
1787     }
1788 }
1789
1790 RUNNER_MULTIPROCESS_TEST(security_manager_16_policy_levels_get)
1791 {
1792     const std::string username("sm_test_16_user_cynara_policy");
1793     CynaraTestAdmin::Admin admin;
1794     int pipefd[2];
1795     pid_t pid;
1796     int result = 0;
1797
1798     struct message {
1799         uid_t uid;
1800         gid_t gid;
1801     } msg;
1802
1803     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1804
1805     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1806     user.create();
1807
1808     pid = fork();
1809     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1810     if (pid != 0)//parent process
1811     {
1812         FdUniquePtr pipeptr(pipefd+1);
1813         close(pipefd[0]);
1814
1815         //send info to child
1816         msg.uid = user.getUid();
1817         msg.gid = user.getGid();
1818
1819         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1820         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1821
1822         //wait for child
1823         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1824     }
1825     if(pid == 0)
1826     {
1827         int ret;
1828         char** levels;
1829         std::string allow_policy, deny_policy;
1830         size_t count;
1831         FdUniquePtr pipeptr(pipefd);
1832         close(pipefd[1]);
1833
1834         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1835         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1836
1837         //become admin privacy manager manager
1838         result = drop_root_privileges(msg.uid, msg.gid);
1839         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1840
1841         // without plugins there should only be 2 policies - Allow and Deny
1842         ret = security_manager_policy_levels_get(&levels, &count);
1843
1844         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
1845                 "Invlid return code: " << ret);
1846
1847         RUNNER_ASSERT_MSG(count == 2, "Invalid number of policy levels. Should be 2, instead there is: " << static_cast<int>(count));
1848
1849         deny_policy = std::string(levels[0]);
1850         allow_policy = std::string(levels[count-1]);
1851
1852         // first should always be Deny
1853         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
1854                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
1855
1856         // last should always be Allow
1857         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
1858                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
1859
1860         security_manager_policy_levels_free(levels, count);
1861         exit(0);
1862     }
1863 }
1864
1865 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
1866 {
1867     const char *const update_app_id = "security_manager_17_update_app_id";
1868     const char *const update_privilege = "http://tizen.org/privilege/led";
1869     const char *const check_start_bucket = "";
1870     const std::string username("sm_test_17_username");
1871     PolicyRequest addPolicyRequest;
1872     CynaraTestAdmin::Admin admin;
1873
1874     struct message {
1875         uid_t uid;
1876         gid_t gid;
1877     } msg;
1878
1879     int pipefd[2];
1880     int pipefd2[2];
1881     pid_t pid;
1882     int result = 0;
1883
1884     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1885     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
1886
1887     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1888     user.create();
1889
1890     pid = fork();
1891     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1892     if (pid != 0)//parent process
1893     {
1894         FdUniquePtr pipeptr(pipefd+1);
1895         close(pipefd[0]);
1896
1897         register_current_process_as_privilege_manager(user.getUid(), false);
1898
1899         //send info to child
1900         msg.uid = user.getUid();
1901         msg.gid = user.getGid();
1902
1903         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1904         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1905
1906         //wait for child
1907         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1908
1909         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1910                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1911
1912         pid = fork();
1913         if (pid != 0)//parent process
1914         {
1915             FdUniquePtr pipeptr(pipefd2+1);
1916             close(pipefd2[0]);
1917
1918             //send info to child
1919             msg.uid = user.getUid();
1920             msg.gid = user.getGid();
1921
1922             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
1923             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1924
1925             //wait for child
1926             RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1927
1928             //wait for child
1929             waitpid(-1, &result, 0);
1930
1931             admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1932                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
1933         }
1934         if(pid == 0)
1935         {
1936             FdUniquePtr pipeptr(pipefd2);
1937             close(pipefd2[1]);
1938
1939             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
1940             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1941
1942             //become admin privacy manager manager
1943             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1944             result = drop_root_privileges(msg.uid, msg.gid);
1945             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1946
1947             // delete this entry
1948             PolicyRequest deletePolicyRequest;
1949             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1950             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
1951
1952             deletePolicyRequest.addEntry(deleteEntry);
1953             Api::sendPolicy(deletePolicyRequest);
1954             exit(0);
1955         }
1956     }
1957     if(pid == 0)
1958     {
1959         FdUniquePtr pipeptr(pipefd);
1960         close(pipefd[1]);
1961
1962         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1963         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1964
1965         //become admin privacy manager manager
1966         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1967         result = drop_root_privileges(msg.uid, msg.gid);
1968         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1969
1970         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1971         entry.setLevel("Allow");
1972
1973         addPolicyRequest.addEntry(entry);
1974         Api::sendPolicy(addPolicyRequest);
1975         exit(0);
1976     }
1977 }
1978
1979 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
1980 {
1981     const std::string username("sm_test_17_user_name");
1982
1983     struct message {
1984         uid_t uid;
1985         gid_t gid;
1986         unsigned int privileges_count;
1987     } msg;
1988
1989     int pipefd[2];
1990     pid_t pid;
1991     int result = 0;
1992
1993     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1994
1995     pid = fork();
1996     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1997     if (pid != 0)//parent process
1998     {
1999         FdUniquePtr pipeptr(pipefd+1);
2000         close(pipefd[0]);
2001
2002         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2003         user.create();
2004
2005         unsigned int privileges_count = 0;
2006
2007         register_current_process_as_privilege_manager(user.getUid(), false);
2008         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2009         ++privileges_count;
2010
2011         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2012             InstallRequest requestInst;
2013             requestInst.setAppId(MANY_APPS[i].c_str());
2014             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).c_str());
2015             requestInst.setUid(user.getUid());
2016
2017             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2018                 requestInst.addPrivilege(priv.c_str());
2019             };
2020
2021             Api::install(requestInst);
2022             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2023         };
2024
2025         //send info to child
2026         msg.uid = user.getUid();
2027         msg.gid = user.getGid();
2028         msg.privileges_count = privileges_count;
2029
2030         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2031         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2032
2033         //wait for child
2034         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2035     }
2036     if(pid == 0)
2037     {
2038         FdUniquePtr pipeptr(pipefd);
2039         close(pipefd[1]);
2040
2041         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2042         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2043
2044         //become admin privacy manager manager
2045         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2046         result = drop_root_privileges(msg.uid, msg.gid);
2047         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2048
2049         // filter by privilege
2050         std::vector<PolicyEntry> policyEntries;
2051         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2052         Api::getPolicy(filter, policyEntries);
2053
2054         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2055         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2056
2057         // filter by other privilege
2058         policyEntries.clear();
2059         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2060         Api::getPolicy(filter2, policyEntries);
2061
2062         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2063         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2064
2065         // filter by appId
2066         policyEntries.clear();
2067         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2068         Api::getPolicy(filter3, policyEntries);
2069
2070         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2071         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2072     }
2073 }
2074
2075 RUNNER_CHILD_TEST(security_manager_10_user_cynara_policy)
2076 {
2077     const char *const MAIN_BUCKET = "MAIN";
2078     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2079     const char *const ADMIN_BUCKET = "ADMIN";
2080     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2081     const std::string username("sm_test_10_user_cynara_policy");
2082     CynaraTestAdmin::Admin admin;
2083     std::string uid_string;
2084     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2085     user.create();
2086     user.getUidString(uid_string);
2087
2088     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2089     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2090     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2091
2092     user.remove();
2093     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2094
2095     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2096     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2097     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2098     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2099 }
2100
2101 RUNNER_CHILD_TEST(security_manager_11_security_manager_cmd_install)
2102 {
2103     int ret;
2104     const int SUCCESS = 0;
2105     const int FAILURE = 256;
2106     const std::string app_id = "security_manager_10_app";
2107     const std::string pkg_id = "security_manager_10_pkg";
2108     const std::string username("sm_test_10_user_name");
2109     std::string uid_string;
2110     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2111     user.create();
2112     user.getUidString(uid_string);
2113     const std::string path1 = appDirPath(user, app_id, pkg_id) + "/p1";
2114     const std::string path2 = appDirPath(user, app_id, pkg_id) + "/p2";
2115     const std::string pkgopt = " --pkg=" + pkg_id;
2116     const std::string appopt = " --app=" + app_id;
2117     const std::string uidopt = " --uid=" + uid_string;
2118
2119     mktreeSafe(path1.c_str(), 0);
2120     mktreeSafe(path2.c_str(), 0);
2121
2122     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2123
2124     struct operation {
2125         std::string command;
2126         int expected_result;
2127     };
2128     std::vector<struct operation> operations = {
2129             {"security-manager-cmd", FAILURE},//no option
2130             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2131             {"security-manager-cmd --help", SUCCESS},
2132             {"security-manager-cmd --install", FAILURE},//no params
2133             {"security-manager-cmd -i", FAILURE},//no params
2134             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2135             {installcmd, SUCCESS},
2136             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2137             {installcmd + " --path " + path1 + " writable", SUCCESS},
2138             {installcmd + " --path " + path1, FAILURE},//no path type
2139             {installcmd + " --path " + path1 + " writable" + " --path " + path2 + " readable", SUCCESS},
2140             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " readable", FAILURE},//wrong path type
2141             {installcmd + " --path " + path1 + " writable" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2142     };
2143
2144     for (auto &op : operations) {
2145         ret = system(op.command.c_str());
2146         RUNNER_ASSERT_MSG(ret == op.expected_result,
2147                 "Unexpected result for command '" << op.command <<"': "
2148                 << ret << " Expected was: "<< op.expected_result);
2149     }
2150 }
2151
2152 RUNNER_CHILD_TEST(security_manager_12_security_manager_cmd_users)
2153 {
2154     int ret;
2155     const int SUCCESS = 0;
2156     const int FAILURE = 256;
2157     const std::string username("sm_test_11_user_name");
2158     std::string uid_string;
2159     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2160     user.create();
2161     user.getUidString(uid_string);
2162     const std::string uidopt = " --uid=" + uid_string;
2163
2164     struct operation {
2165         std::string command;
2166         int expected_result;
2167     };
2168     std::vector<struct operation> operations = {
2169             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2170             {"security-manager-cmd -m", FAILURE},//no params
2171             {"security-manager-cmd -mr", FAILURE},//no uid
2172             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2173             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2174             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2175             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2176             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2177             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2178             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2179             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2180     };
2181
2182     for (auto &op : operations) {
2183         ret = system(op.command.c_str());
2184         RUNNER_ASSERT_MSG(ret == op.expected_result,
2185                 "Unexpected result for command '" << op.command <<"': "
2186                 << ret << " Expected was: "<< op.expected_result);
2187     }
2188 }
2189
2190 RUNNER_MULTIPROCESS_TEST(security_manager_13_security_manager_admin_deny_user_priv)
2191 {
2192     const int BUFFER_SIZE = 128;
2193     struct message {
2194         uid_t uid;
2195         gid_t gid;
2196         char buf[BUFFER_SIZE];
2197     } msg;
2198
2199     privileges_t admin_required_privs = {
2200             "http://tizen.org/privilege/systemsettings.admin",
2201             "http://tizen.org/privilege/systemsettings"};
2202     privileges_t manifest_privs = {
2203             "http://tizen.org/privilege/internet",
2204             "http://tizen.org/privilege/camera"};
2205     privileges_t real_privs_allow = {"http://tizen.org/privilege/camera"};
2206     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2207
2208     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2209     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2210     const std::string app_id = "sm_test_13_SOME_APP";
2211     const std::string pkg_id = "sm_test_13_SOME_PKG";
2212
2213     int pipefd[2];
2214     pid_t pid;
2215     int result = 0;
2216
2217     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2218     pid = fork();
2219     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2220     if (pid != 0)//parent process
2221     {
2222         std::string childuidstr;
2223         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, true);
2224         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, true);
2225
2226         InstallRequest request,request2;
2227         FdUniquePtr pipeptr(pipefd+1);
2228         close(pipefd[0]);
2229
2230         admin.create();
2231         child.create();
2232         child.getUidString(childuidstr);
2233
2234         //install privacy manager for admin
2235         request.setAppId(pirivman_id.c_str());
2236         request.setPkgId(pirivman_pkg_id.c_str());
2237         request.setUid(admin.getUid());
2238         for (auto &priv: admin_required_privs)
2239             request.addPrivilege(priv.c_str());
2240         Api::install(request);
2241
2242         //install app for child that has internet privilege
2243         request2.setAppId(app_id.c_str());
2244         request2.setPkgId(pkg_id.c_str());
2245         request2.setUid(child.getUid());
2246         for (auto &priv: manifest_privs)
2247             request2.addPrivilege(priv.c_str());
2248         Api::install(request2);
2249
2250         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2251                               manifest_privs, SM_NO_PRIVILEGES);
2252
2253         //send info to child
2254         msg.uid = admin.getUid();
2255         msg.gid = admin.getGid();
2256         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2257
2258         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2259         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2260
2261         //wait for child
2262         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2263
2264         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2265                               real_privs_allow, real_privs_deny);
2266     }
2267     if (pid == 0)//child
2268     {
2269         FdUniquePtr pipeptr(pipefd);
2270         close(pipefd[1]);
2271
2272         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2273         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2274
2275         //become admin privacy manager manager
2276         Api::setProcessLabel(pirivman_id.c_str());
2277         result = drop_root_privileges(msg.uid, msg.gid);
2278         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2279         PolicyRequest addPolicyReq;
2280         //change rights
2281         for (auto &denypriv:real_privs_deny) {
2282             /*this entry will deny some privileges for user whose uid (as c string)
2283               was sent in message's buf field.
2284               That user would be denying internet for child in this case*/
2285             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2286             entry.setMaxLevel("Deny");
2287             addPolicyReq.addEntry(entry);
2288         }
2289         Api::sendPolicy(addPolicyReq);
2290         exit(0);
2291     }
2292 }
2293
2294 int main(int argc, char *argv[])
2295 {
2296     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
2297 }