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