2da86899593dc5acd31db1aba0e50f5823efc95c
[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 <sys/socket.h>
12 #include <sys/un.h>
13 #include <attr/xattr.h>
14 #include <linux/xattr.h>
15
16 #include <unistd.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19
20 #include <grp.h>
21 #include <pwd.h>
22
23 #include <libprivilege-control_test_common.h>
24 #include <tests_common.h>
25
26 #include <tzplatform_config.h>
27 #include <security-manager.h>
28 #include <sm_api.h>
29 #include <sm_db.h>
30 #include <sm_request.h>
31 #include <sm_user_request.h>
32 #include <temp_test_user.h>
33 #include <cynara_test_client.h>
34 #include <cynara_test_admin.h>
35 #include <service_manager.h>
36
37 using namespace SecurityManagerTest;
38
39 DEFINE_SMARTPTR(cap_free, _cap_struct, CapsSetsUniquePtr);
40 DEFINE_SMARTPTR(tzplatform_context_destroy, tzplatform_context, TzPlatformContextPtr);
41
42 static const privileges_t SM_ALLOWED_PRIVILEGES = {
43     "http://tizen.org/privilege/location",
44     "http://tizen.org/privilege/camera"
45 };
46
47 static const privileges_t SM_DENIED_PRIVILEGES  = {
48     "http://tizen.org/privilege/bluetooth",
49     "http://tizen.org/privilege/power"
50 };
51
52 static const privileges_t SM_NO_PRIVILEGES  = {
53 };
54
55 static const std::vector<std::string> SM_ALLOWED_GROUPS = {"db_browser", "db_alarm"};
56
57 static const char *const SM_PRIVATE_PATH = "/usr/apps/test_DIR/app_dir";
58 static const char *const SM_PUBLIC_RO_PATH = "/usr/apps/test_DIR/app_dir_public_ro";
59 static const char *const SM_DENIED_PATH = "/usr/apps/test_DIR/non_app_dir";
60 static const char *const ANY_USER_REPRESENTATION = "anyuser";/*this may be actually any string*/
61 static const std::string EXEC_FILE("exec");
62 static const std::string NORMAL_FILE("normal");
63 static const std::string LINK_PREFIX("link_to_");
64
65 static const std::string PRIVILEGE_MANAGER_APP = "privilege_manager";
66 static const std::string PRIVILEGE_MANAGER_PKG = "privilege_manager";
67 static const std::string PRIVILEGE_MANAGER_SELF_PRIVILEGE = "http://tizen.org/privilege/systemsettings";
68 static const std::string PRIVILEGE_MANAGER_ADMIN_PRIVILEGE = "http://tizen.org/privilege/systemsettings.admin";
69
70 static const std::vector<std::string> MANY_APPS = {
71     "security_manager_10_app_1",
72     "security_manager_10_app_2",
73     "security_manager_10_app_3",
74     "security_manager_10_app_4",
75     "security_manager_10_app_5"
76 };
77
78 static const std::map<std::string, std::string> MANY_APPS_PKGS = {
79     {"security_manager_10_app_1", "security_manager_10_pkg_1"},
80     {"security_manager_10_app_2", "security_manager_10_pkg_2"},
81     {"security_manager_10_app_3", "security_manager_10_pkg_3"},
82     {"security_manager_10_app_4", "security_manager_10_pkg_4"},
83     {"security_manager_10_app_5", "security_manager_10_pkg_5"},
84     {PRIVILEGE_MANAGER_APP, PRIVILEGE_MANAGER_PKG}
85 };
86
87 static const std::vector<privileges_t> MANY_APPS_PRIVILEGES = {
88     {
89         "http://tizen.org/privilege/internet",
90         "http://tizen.org/privilege/location"
91     },
92     {
93         "http://tizen.org/privilege/telephony",
94         "http://tizen.org/privilege/camera"
95     },
96     {
97         "http://tizen.org/privilege/contact.read",
98         "http://tizen.org/privilege/led",
99         "http://tizen.org/privilege/email"
100     },
101     {
102         "http://tizen.org/privilege/led",
103         "http://tizen.org/privilege/email",
104         "http://tizen.org/privilege/telephony",
105         "http://tizen.org/privilege/camera"
106     },
107     {
108         "http://tizen.org/privilege/internet",
109         "http://tizen.org/privilege/location",
110         "http://tizen.org/privilege/led",
111         "http://tizen.org/privilege/email"
112     }
113 };
114
115 static void generateAppLabel(const std::string &pkgId, std::string &label)
116 {
117     (void) pkgId;
118     label = "User";
119 }
120
121 static int nftw_check_sm_labels_app_dir(const char *fpath, const struct stat *sb,
122                               const char* correctLabel, bool transmute_test, bool exec_test)
123 {
124     int result;
125     CStringPtr labelPtr;
126     char* label = nullptr;
127
128     /* ACCESS */
129     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
130     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
131     labelPtr.reset(label);
132     RUNNER_ASSERT_MSG(label != nullptr, "ACCESS label on " << fpath << " is not set");
133     result = strcmp(correctLabel, label);
134     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is incorrect"
135             " (should be '" << correctLabel << "' and is '" << label << "')");
136
137
138     /* EXEC */
139     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
140     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
141     labelPtr.reset(label);
142
143     if (S_ISREG(sb->st_mode) && (sb->st_mode & S_IXUSR) && exec_test) {
144         RUNNER_ASSERT_MSG(label != nullptr, "EXEC label on " << fpath << " is not set");
145         result = strcmp(correctLabel, label);
146         RUNNER_ASSERT_MSG(result == 0, "Incorrect EXEC label on executable file " << fpath);
147     } else
148         RUNNER_ASSERT_MSG(label == nullptr, "EXEC label on " << fpath << " is set");
149
150
151     /* TRANSMUTE */
152     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
153     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
154     labelPtr.reset(label);
155
156     if (S_ISDIR(sb->st_mode) && transmute_test == true) {
157         RUNNER_ASSERT_MSG(label != nullptr, "TRANSMUTE label on " << fpath << " is not set at all");
158         RUNNER_ASSERT_MSG(strcmp(label,"TRUE") == 0,
159                 "TRANSMUTE label on " << fpath << " is not set properly: '"<<label<<"'");
160     } else {
161         RUNNER_ASSERT_MSG(label == nullptr, "TRANSMUTE label on " << fpath << " is set");
162     }
163
164     return 0;
165 }
166
167
168 static int nftw_check_sm_labels_app_private_dir(const char *fpath, const struct stat *sb,
169                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
170 {
171     return nftw_check_sm_labels_app_dir(fpath, sb, USER_APP_ID, false, true);
172 }
173
174 static int nftw_check_sm_labels_app_floor_dir(const char *fpath, const struct stat *sb,
175                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
176 {
177
178     return nftw_check_sm_labels_app_dir(fpath, sb, "_", false, false);
179 }
180
181 static void prepare_app_path()
182 {
183     int result;
184
185     result = nftw(SM_PRIVATE_PATH, &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
186     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_PRIVATE_PATH);
187
188     result = nftw(SM_PUBLIC_RO_PATH, &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
189     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_PUBLIC_RO_PATH);
190
191     result = nftw(SM_DENIED_PATH, &nftw_set_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
192     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_DENIED_PATH);
193 }
194
195 static void prepare_app_env()
196 {
197     prepare_app_path();
198 }
199
200 /* TODO: add parameters to this function */
201 static void check_app_path_after_install()
202 {
203     int result;
204
205     result = nftw(SM_PRIVATE_PATH, &nftw_check_sm_labels_app_private_dir, FTW_MAX_FDS, FTW_PHYS);
206     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_PRIVATE_PATH);
207
208     result = nftw(SM_PUBLIC_RO_PATH, &nftw_check_sm_labels_app_floor_dir, FTW_MAX_FDS, FTW_PHYS);
209     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_PUBLIC_RO_PATH);
210
211     result = nftw(SM_DENIED_PATH, &nftw_check_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
212     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_DENIED_PATH);
213 }
214
215
216 static void check_app_permissions(const char *const app_id, const char *const pkg_id, const char *const user,
217                                   const privileges_t &allowed_privs, const privileges_t &denied_privs)
218 {
219     (void) app_id;
220     std::string smackLabel;
221     generateAppLabel(pkg_id, smackLabel);
222
223     CynaraTestClient::Client ctc;
224
225     for (auto &priv : allowed_privs) {
226         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_ALLOWED);
227     }
228
229     for (auto &priv : denied_privs) {
230         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_DENIED);
231     }
232 }
233
234 static void check_app_gids(const char *const app_id, const std::vector<gid_t> &allowed_gids)
235 {
236     int ret;
237     gid_t main_gid = getgid();
238     std::unordered_set<gid_t> reference_gids(allowed_gids.begin(), allowed_gids.end());
239
240     // Reset supplementary groups
241     ret = setgroups(0, NULL);
242     RUNNER_ASSERT_MSG(ret != -1, "Unable to set supplementary groups");
243
244     Api::setProcessGroups(app_id);
245
246     ret = getgroups(0, nullptr);
247     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
248
249     std::vector<gid_t> actual_gids(ret);
250     ret = getgroups(ret, actual_gids.data());
251     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
252
253     for (const auto &gid : actual_gids) {
254         RUNNER_ASSERT_MSG(gid == main_gid || reference_gids.count(gid) > 0,
255             "Application shouldn't get access to group " << gid);
256         reference_gids.erase(gid);
257     }
258
259     RUNNER_ASSERT_MSG(reference_gids.empty(), "Application didn't get access to some groups");
260 }
261
262 static void check_app_after_install(const char *const app_id, const char *const pkg_id,
263                                     const privileges_t &allowed_privs,
264                                     const privileges_t &denied_privs,
265                                     const std::vector<std::string> &allowed_groups)
266 {
267     TestSecurityManagerDatabase dbtest;
268     dbtest.test_db_after__app_install(app_id, pkg_id, allowed_privs);
269     dbtest.check_privileges_removed(app_id, pkg_id, denied_privs);
270
271     /*Privileges should be granted to all users if root installs app*/
272     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, allowed_privs, denied_privs);
273
274     /* Setup mapping of gids to privileges */
275     /* Do this for each privilege for extra check */
276     for (const auto &privilege : allowed_privs) {
277         dbtest.setup_privilege_groups(privilege, allowed_groups);
278     }
279
280     std::vector<gid_t> allowed_gids;
281
282     for (const auto &groupName : allowed_groups) {
283         errno = 0;
284         struct group* grp = getgrnam(groupName.c_str());
285         RUNNER_ASSERT_ERRNO_MSG(grp, "Group: " << groupName << " not found");
286         allowed_gids.push_back(grp->gr_gid);
287     }
288
289     check_app_gids(app_id, allowed_gids);
290 }
291
292 static void check_app_after_install(const char *const app_id, const char *const pkg_id)
293 {
294     TestSecurityManagerDatabase dbtest;
295     dbtest.test_db_after__app_install(app_id, pkg_id);
296 }
297
298 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
299                                       const privileges_t &privileges, const bool is_pkg_removed)
300 {
301     TestSecurityManagerDatabase dbtest;
302     dbtest.test_db_after__app_uninstall(app_id, pkg_id, privileges, is_pkg_removed);
303
304
305     /*Privileges should not be granted anymore to any user*/
306     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, SM_NO_PRIVILEGES, privileges);
307 }
308
309 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
310                                       const bool is_pkg_removed)
311 {
312     TestSecurityManagerDatabase dbtest;
313     dbtest.test_db_after__app_uninstall(app_id, pkg_id, is_pkg_removed);
314 }
315
316 static void install_app(const char *app_id, const char *pkg_id, uid_t uid = 0)
317 {
318     InstallRequest request;
319     request.setAppId(app_id);
320     request.setPkgId(pkg_id);
321     request.setUid(uid);
322     Api::install(request);
323
324     check_app_after_install(app_id, pkg_id);
325
326 }
327
328 static void uninstall_app(const char *app_id, const char *pkg_id, bool expect_pkg_removed)
329 {
330     InstallRequest request;
331     request.setAppId(app_id);
332
333     Api::uninstall(request);
334
335     check_app_after_uninstall(app_id, pkg_id, expect_pkg_removed);
336 }
337
338 static inline void register_current_process_as_privilege_manager(uid_t uid, bool forAdmin = false)
339 {
340     InstallRequest request;
341     request.setAppId(PRIVILEGE_MANAGER_APP.c_str());
342     request.setPkgId(PRIVILEGE_MANAGER_PKG.c_str());
343     request.setUid(uid);
344     request.addPrivilege(PRIVILEGE_MANAGER_SELF_PRIVILEGE.c_str());
345     if (forAdmin)
346         request.addPrivilege(PRIVILEGE_MANAGER_ADMIN_PRIVILEGE.c_str());
347     Api::install(request);
348     Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
349 };
350
351 static inline struct passwd *getUserStruct(const std::string &userName) {
352     struct passwd *pw = nullptr;
353     errno = 0;
354
355     while(!(pw = getpwnam(userName.c_str()))) {
356         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
357     };
358
359     return pw;
360 };
361
362 static inline struct passwd *getUserStruct(const uid_t uid) {
363     struct passwd *pw = nullptr;
364     errno = 0;
365
366     while(!(pw = getpwuid(uid))) {
367         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
368     };
369
370     return pw;
371 };
372
373 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER)
374
375
376 RUNNER_TEST(security_manager_01a_app_double_install_double_uninstall)
377 {
378     const char *const sm_app_id = "sm_test_01a_app_id_double";
379     const char *const sm_pkg_id = "sm_test_01a_pkg_id_double";
380
381     InstallRequest requestInst;
382     requestInst.setAppId(sm_app_id);
383     requestInst.setPkgId(sm_pkg_id);
384
385     Api::install(requestInst);
386     Api::install(requestInst);
387
388     /* Check records in the security-manager database */
389     check_app_after_install(sm_app_id, sm_pkg_id);
390
391     InstallRequest requestUninst;
392     requestUninst.setAppId(sm_app_id);
393
394     Api::uninstall(requestUninst);
395     Api::uninstall(requestUninst);
396
397     /* Check records in the security-manager database */
398     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
399 }
400
401
402 RUNNER_TEST(security_manager_01b_app_double_install_wrong_pkg_id)
403 {
404     const char *const sm_app_id = "sm_test_01b_app";
405     const char *const sm_pkg_id = "sm_test_01b_pkg";
406     const char *const sm_pkg_id_wrong = "sm_test_01b_pkg_BAD";
407
408     InstallRequest requestInst;
409     requestInst.setAppId(sm_app_id);
410     requestInst.setPkgId(sm_pkg_id);
411
412     Api::install(requestInst);
413
414     InstallRequest requestInst2;
415     requestInst2.setAppId(sm_app_id);
416     requestInst2.setPkgId(sm_pkg_id_wrong);
417
418     Api::install(requestInst2, SECURITY_MANAGER_ERROR_INPUT_PARAM);
419
420
421     /* Check records in the security-manager database */
422     check_app_after_install(sm_app_id, sm_pkg_id);
423
424     InstallRequest requestUninst;
425     requestUninst.setAppId(sm_app_id);
426
427     Api::uninstall(requestUninst);
428
429
430     /* Check records in the security-manager database */
431     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
432
433 }
434
435 RUNNER_TEST(security_manager_01c_app_uninstall_pkg_id_ignored)
436 {
437     const char * const  sm_app_id = "SM_TEST_01c_APPID";
438     const char * const  sm_pkg_id = "SM_TEST_01c_PKGID";
439     const char * const  sm_pkg_id_wrong = "SM_TEST_01c_PKGID_wrong";
440
441     InstallRequest requestInst;
442     requestInst.setAppId(sm_app_id);
443     requestInst.setPkgId(sm_pkg_id);
444
445     Api::install(requestInst);
446
447     /* Check records in the security-manager database */
448     check_app_after_install(sm_app_id, sm_pkg_id);
449
450     InstallRequest requestUninst;
451     requestUninst.setAppId(sm_app_id);
452     requestUninst.setPkgId(sm_pkg_id_wrong);
453
454     Api::uninstall(requestUninst);
455
456     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
457
458 }
459
460 RUNNER_TEST(security_manager_02_app_install_uninstall_full)
461 {
462     const char *const sm_app_id = "sm_test_02_app_id_full";
463     const char *const sm_pkg_id = "sm_test_02_pkg_id_full";
464
465     prepare_app_env();
466
467     InstallRequest requestInst;
468     requestInst.setAppId(sm_app_id);
469     requestInst.setPkgId(sm_pkg_id);
470     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
471     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
472     requestInst.addPath(SM_PRIVATE_PATH, SECURITY_MANAGER_PATH_PRIVATE);
473     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
474
475     Api::install(requestInst);
476
477     /* Check records in the security-manager database */
478     check_app_after_install(sm_app_id, sm_pkg_id,
479                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
480
481     /* TODO: add parameters to this function */
482     check_app_path_after_install();
483
484     InstallRequest requestUninst;
485     requestUninst.setAppId(sm_app_id);
486
487     Api::uninstall(requestUninst);
488
489     /* Check records in the security-manager database,
490      * all previously allowed privileges should be removed */
491     check_app_after_uninstall(sm_app_id, sm_pkg_id,
492                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
493 }
494
495 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
496 {
497     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_smack";
498     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_smack";
499     const char *const expected_label = USER_APP_ID;
500     const char *const socketLabel = "not_expected_label";
501     char *label = nullptr;
502     CStringPtr labelPtr;
503     int result;
504
505     uninstall_app(app_id, pkg_id, true);
506     install_app(app_id, pkg_id);
507
508     struct sockaddr_un sockaddr = {AF_UNIX, SOCK_PATH};
509     //Clean up before creating socket
510     unlink(SOCK_PATH);
511     int sock = socket(AF_UNIX, SOCK_STREAM, 0);
512     RUNNER_ASSERT_ERRNO_MSG(sock >= 0, "socket failed");
513     SockUniquePtr sockPtr(&sock);
514     //Bind socket to address
515     result = bind(sock, (struct sockaddr*) &sockaddr, sizeof(struct sockaddr_un));
516     RUNNER_ASSERT_ERRNO_MSG(result == 0, "bind failed");
517     //Set socket label to something different than expecedLabel
518     result = fsetxattr(sock, XATTR_NAME_SMACKIPIN, socketLabel,
519         strlen(socketLabel), 0);
520     RUNNER_ASSERT_ERRNO_MSG(result == 0,
521         "Can't set socket label. Result: " << result);
522     result = fsetxattr(sock, XATTR_NAME_SMACKIPOUT, socketLabel,
523         strlen(socketLabel), 0);
524     RUNNER_ASSERT_ERRNO_MSG(result == 0,
525         "Can't set socket label. Result: " << result);
526
527     Api::setProcessLabel(app_id);
528
529     char value[SMACK_LABEL_LEN + 1];
530     ssize_t size;
531     size = fgetxattr(sock, XATTR_NAME_SMACKIPIN, value, sizeof(value));
532     RUNNER_ASSERT_ERRNO_MSG(size != -1, "fgetxattr failed: " << value);
533     result = strcmp(expected_label, value);
534     RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
535         expected_label << " Actual: " << value);
536
537     size = fgetxattr(sock, XATTR_NAME_SMACKIPOUT, value, sizeof(value));
538     RUNNER_ASSERT_ERRNO_MSG(size != -1, "fgetxattr failed: " << value);
539     result = strcmp(expected_label, value);
540     RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
541         expected_label << " Actual: " << value);
542
543     result = smack_new_label_from_self(&label);
544     RUNNER_ASSERT_MSG(result >= 0,
545             " Error getting current process label");
546     RUNNER_ASSERT_MSG(label != nullptr,
547             " Process label is not set");
548     labelPtr.reset(label);
549
550     result = strcmp(expected_label, label);
551     RUNNER_ASSERT_MSG(result == 0,
552             " Process label is incorrect. Expected: \"" << expected_label <<
553             "\" Actual: \"" << label << "\"");
554
555     uninstall_app(app_id, pkg_id, true);
556 }
557
558 RUNNER_CHILD_TEST_NOSMACK(security_manager_03_set_label_from_appid_nosmack)
559 {
560     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_nosmack";
561     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_nosmack";
562
563     uninstall_app(app_id, pkg_id, true);
564     install_app(app_id, pkg_id);
565
566     Api::setProcessLabel(app_id);
567
568     uninstall_app(app_id, pkg_id, true);
569 }
570
571 static void prepare_request(InstallRequest &request,
572               const char *const app_id,
573               const char *const pkg_id,
574               app_install_path_type pathType,
575               const char *const path,
576               uid_t uid)
577 {
578     request.setAppId(app_id);
579     request.setPkgId(pkg_id);
580     request.addPath(path, pathType);
581
582     if (uid != 0)
583         request.setUid(uid);
584 }
585
586 static uid_t getGlobalUserId(void)
587 {
588     return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
589 }
590
591 static const std::string appDirPath(const TemporaryTestUser &user)
592 {
593     struct tzplatform_context *tzCtxPtr = nullptr;
594
595     RUNNER_ASSERT(0 == tzplatform_context_create(&tzCtxPtr));
596     TzPlatformContextPtr tzCtxPtrSmart(tzCtxPtr);
597
598     RUNNER_ASSERT_MSG(0 == tzplatform_context_set_user(tzCtxPtr, user.getUid()),
599                       "Unable to set user <" << user.getUserName() << "> for tzplatform context");
600
601     const char *appDir = tzplatform_context_getenv(tzCtxPtr,
602                                 getGlobalUserId() == user.getUid() ? TZ_SYS_RW_APP : TZ_USER_APP);
603     RUNNER_ASSERT_MSG(nullptr != appDir,
604                       "tzplatform_context_getenv failed"
605                           << "for getting sys rw app of user <" << user.getUserName() << ">");
606
607     return appDir;
608 }
609
610 static const std::string nonAppDirPath(const TemporaryTestUser &user)
611 {
612     return TMP_DIR + "/" + user.getUserName();
613 }
614
615 static const std::string uidToStr(const uid_t uid)
616 {
617     return std::to_string(static_cast<unsigned int>(uid));
618 }
619
620 static void install_and_check(const char *const sm_app_id,
621                               const char *const sm_pkg_id,
622                               const TemporaryTestUser& user,
623                               const std::string &appDir,
624                               bool requestUid)
625 {
626     InstallRequest requestPublic;
627
628     //install app for non-root user and try to register public path (should fail)
629     prepare_request(requestPublic, sm_app_id, sm_pkg_id,
630                     SECURITY_MANAGER_PATH_PUBLIC, appDir.c_str(),
631                     requestUid ? user.getUid() : 0);
632
633     Api::install(requestPublic, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
634
635     InstallRequest requestPrivate;
636
637     //install app for non-root user
638     //should fail (users may only register folders inside their home)
639     prepare_request(requestPrivate, sm_app_id, sm_pkg_id,
640                     SECURITY_MANAGER_PATH_PRIVATE, SM_PRIVATE_PATH,
641                     requestUid ? user.getUid() : 0);
642
643     Api::install(requestPrivate, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
644
645     InstallRequest requestPrivateUser;
646
647     //install app for non-root user
648     //should succeed - this time i register folder inside user's home dir
649     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
650                     SECURITY_MANAGER_PATH_PRIVATE, appDir.c_str(),
651                     requestUid ? user.getUid() : 0);
652
653     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
654         requestPrivateUser.addPrivilege(privilege.c_str());
655
656     Api::install(requestPrivateUser);
657
658     check_app_permissions(sm_app_id, sm_pkg_id,
659                           uidToStr(user.getUid()).c_str(),
660                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
661 }
662
663 static void createTestDir(const std::string &dir)
664 {
665     mode_t dirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
666     mode_t execFileMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
667     mode_t normalFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
668
669     mkdirSafe(dir, dirMode);
670     creatSafe(dir + "/" + EXEC_FILE, execFileMode);
671     creatSafe(dir + "/" + NORMAL_FILE, normalFileMode);
672     symlinkSafe(dir + "/" + EXEC_FILE, dir + "/" + LINK_PREFIX + EXEC_FILE);
673     symlinkSafe(dir + "/" + NORMAL_FILE, dir + "/" + LINK_PREFIX + NORMAL_FILE);
674 }
675
676 static void createInnerAppDir(const std::string &dir, const std::string &nonAppDir)
677 {
678     createTestDir(dir);
679
680     symlinkSafe(nonAppDir, dir + "/" + LINK_PREFIX + "non_app_dir");
681     symlinkSafe(nonAppDir + "/" + EXEC_FILE,
682                 dir + "/" + LINK_PREFIX + "non_app_" + EXEC_FILE);
683     symlinkSafe(nonAppDir + "/" + NORMAL_FILE,
684                 dir + "/" + LINK_PREFIX + "non_app_" + NORMAL_FILE);
685 }
686
687 static void generateAppDir(const TemporaryTestUser &user)
688 {
689     const std::string dir = appDirPath(user);
690     const std::string nonAppDir = nonAppDirPath(user);
691
692     createInnerAppDir(dir, nonAppDir);
693     createInnerAppDir(dir + "/.inner_dir", nonAppDir);
694     createInnerAppDir(dir + "/inner_dir", nonAppDir);
695 }
696
697 static void generateNonAppDir(const TemporaryTestUser &user)
698 {
699     const std::string dir = nonAppDirPath(user);
700
701     createTestDir(dir);
702     createTestDir(dir + "/.inner_dir");
703     createTestDir(dir + "/inner_dir");
704 }
705
706 static void createTestDirs(const TemporaryTestUser &user)
707 {
708     generateAppDir(user);
709     generateNonAppDir(user);
710 }
711
712 static void removeTestDirs(const TemporaryTestUser &user)
713 {
714     removeDir(appDirPath(user));
715     removeDir(nonAppDirPath(user));
716 }
717
718 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
719 {
720     int result;
721     const char *const sm_app_id = "sm_test_04a_app_id_uid";
722     const char *const sm_pkg_id = "sm_test_04a_pkg_id_uid";
723     const std::string new_user_name = "sm_test_04a_user_name";
724
725     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
726     testUser.create();
727
728     removeTestDirs(testUser);
729     createTestDirs(testUser);
730
731     const std::string userAppDirPath = appDirPath(testUser);
732
733     //switch user to non-root
734     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
735     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
736
737     install_and_check(sm_app_id, sm_pkg_id, testUser, userAppDirPath, false);
738
739     //uninstall app as non-root user
740     InstallRequest request;
741     request.setAppId(sm_app_id);
742
743     Api::uninstall(request);
744
745     check_app_permissions(sm_app_id, sm_pkg_id,
746                           uidToStr(testUser.getUid()).c_str(),
747                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
748 }
749
750 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user)
751 {
752     int result;
753     const char *const sm_app_id = "sm_test_04b_app_id_uid";
754     const char *const sm_pkg_id = "sm_test_04b_pkg_id_uid";
755     const std::string new_user_name = "sm_test_04b_user_name";
756
757     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
758     testUser.create();
759
760     removeTestDirs(testUser);
761     createTestDirs(testUser);
762
763     install_and_check(sm_app_id, sm_pkg_id, testUser, appDirPath(testUser), true);
764
765     //switch user to non-root - root may not uninstall apps for specified users
766     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
767     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
768
769     //uninstall app as non-root user
770     InstallRequest request;
771     request.setAppId(sm_app_id);
772
773     Api::uninstall(request);
774
775     check_app_permissions(sm_app_id, sm_pkg_id,
776                           uidToStr(testUser.getUid()).c_str(),
777                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
778 }
779
780
781 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
782 {
783     int result;
784     CapsSetsUniquePtr caps, caps_empty(cap_init());
785
786     caps.reset(cap_from_text("all=eip"));
787     RUNNER_ASSERT_MSG(caps, "can't convert capabilities from text");
788     result = cap_set_proc(caps.get());
789     RUNNER_ASSERT_MSG(result == 0,
790         "can't set capabilities. Result: " << result);
791
792     Api::dropProcessPrivileges();
793
794     caps.reset(cap_get_proc());
795     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
796
797     result = cap_compare(caps.get(), caps_empty.get());
798     RUNNER_ASSERT_MSG(result == 0,
799         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
800 }
801
802 RUNNER_CHILD_TEST(security_manager_06_install_app_offline)
803 {
804     const char *const app_id = "sm_test_06_app_id_install_app_offline";
805     const char *const pkg_id = "sm_test_06_pkg_id_install_app_offline";
806     ServiceManager serviceManager("security-manager.service");
807
808     uninstall_app(app_id, pkg_id, true);
809     serviceManager.maskService();
810     serviceManager.stopService();
811
812     install_app(app_id, pkg_id);
813
814     serviceManager.unmaskService();
815     serviceManager.startService();
816
817     uninstall_app(app_id, pkg_id, true);
818 }
819
820 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
821 {
822     const char *const sm_app_id = "sm_test_07_app_id_user";
823     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
824     const std::string new_user_name = "sm_test_07_user_name";
825     std::string uid_string;
826     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
827     test_user.create();
828     uid_string =  std::to_string(static_cast<unsigned int>(test_user.getUid()));
829
830     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
831
832     check_app_after_install(sm_app_id, sm_pkg_id);
833
834     test_user.remove();
835
836     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
837
838     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
839 }
840
841 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
842 {
843     UserRequest addUserRequest;
844
845     const char *const sm_app_id = "sm_test_08_app_id_user";
846     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
847     const char *const new_user_name = "sm_test_08_user_name";
848     std::string uid_string;
849
850     // gumd user add
851     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
852     test_user.create();
853     uid_string =  std::to_string(static_cast<unsigned int>(test_user.getUid()));
854
855     addUserRequest.setUid(test_user.getUid());
856     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
857
858     //sm user add
859     Api::addUser(addUserRequest);
860
861     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
862
863     check_app_after_install(sm_app_id, sm_pkg_id);
864
865     test_user.remove();
866
867     UserRequest deleteUserRequest;
868     deleteUserRequest.setUid(test_user.getUid());
869
870     Api::deleteUser(deleteUserRequest);
871
872     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
873
874     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
875 }
876
877 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
878 {
879     const char *const app_id = "security_manager_09_add_user_offline_app";
880     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
881     const std::string username("sm_test_09_user_name");
882     ServiceManager serviceManager("security-manager.service");
883     serviceManager.maskService();
884     serviceManager.stopService();
885
886     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
887     user.create();
888
889     install_app(app_id, pkg_id, user.getUid());
890
891     check_app_after_install(app_id, pkg_id);
892
893     serviceManager.unmaskService();
894     serviceManager.startService();
895
896     user.remove();
897
898     check_app_after_uninstall(app_id, pkg_id, true);
899 }
900
901 RUNNER_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
902 {
903     //TEST DATA
904     const std::string username("sm_test_10_user_name");
905     unsigned int privileges_count = 0;
906
907     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
908     std::map<std::string, std::set<std::string>> apps2PrivsMap;
909
910     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
911         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
912             MANY_APPS.at(i), std::set<std::string>(
913                 MANY_APPS_PRIVILEGES.at(i).begin(),
914                 MANY_APPS_PRIVILEGES.at(i).end())));
915         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
916     };
917
918     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
919         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
920     ++privileges_count;
921     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
922     //TEST DATA END
923
924     sem_t *mutex;
925     errno = 0;
926     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
927     errno = 0;
928     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
929     pid_t pid = fork();
930
931     if (pid != 0) { //parent process
932         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
933         tmpUser.create();
934
935         for(const auto &user : users2AppsMap) {
936
937             for(const auto &app : user.second) {
938                 InstallRequest requestInst;
939                 requestInst.setAppId(app.first.c_str());
940                 try {
941                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
942                 } catch (const std::out_of_range &e) {
943                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
944                 };
945                 requestInst.setUid(tmpUser.getUid());
946
947                 for (const auto &privilege : app.second) {
948                     requestInst.addPrivilege(privilege.c_str());
949                 };
950
951                 Api::install(requestInst);
952             };
953
954             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
955         };
956         //Start child process
957         errno = 0;
958         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
959
960         int status;
961         wait(&status);
962
963         tmpUser.remove();
964     };
965
966     if (pid == 0) { //child process
967         errno = 0;
968         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
969         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
970
971         struct passwd *pw = getUserStruct(username);
972         register_current_process_as_privilege_manager(pw->pw_uid);
973         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
974         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
975
976         std::vector<PolicyEntry> policyEntries;
977         PolicyEntry filter;
978         Api::getPolicy(filter, policyEntries);
979
980         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
981         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
982
983         for (const auto &policyEntry : policyEntries) {
984             std::string user = policyEntry.getUser();
985             std::string app = policyEntry.getAppId();
986             std::string privilege = policyEntry.getPrivilege();
987
988             try {
989                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
990                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
991                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
992                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
993             } catch (const std::out_of_range &e) {
994                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
995             } catch (const std::invalid_argument& e) {
996                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
997             };
998         };
999         exit(0);
1000     };
1001 }
1002
1003 RUNNER_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1004 {
1005     //TEST DATA
1006     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1007     unsigned int privileges_count = 0;
1008
1009     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1010     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1011
1012     for (const auto &username : usernames) {
1013         //Only entries for one of the users will be listed
1014         privileges_count = 0;
1015
1016         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1017             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1018                 MANY_APPS.at(i), std::set<std::string>(
1019                     MANY_APPS_PRIVILEGES.at(i).begin(),
1020                     MANY_APPS_PRIVILEGES.at(i).end())));
1021             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1022         };
1023
1024         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1025     };
1026
1027     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1028         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1029
1030     ++privileges_count;
1031     //TEST DATA END
1032
1033     sem_t *mutex;
1034     errno = 0;
1035     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1036     errno = 0;
1037     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1038     pid_t pid = fork();
1039
1040     if (pid != 0) { //parent process
1041         std::vector<TemporaryTestUser> users = {
1042             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1043             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1044             };
1045
1046         users.at(0).create();
1047         users.at(1).create();
1048
1049         //Install apps for both users
1050         for(const auto &user : users) {
1051             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1052                 InstallRequest requestInst;
1053                 requestInst.setAppId(app.first.c_str());
1054                 try {
1055                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1056                 } catch (const std::out_of_range &e) {
1057                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1058                 };
1059                 requestInst.setUid(user.getUid());
1060
1061                 for (const auto &privilege : app.second) {
1062                     requestInst.addPrivilege(privilege.c_str());
1063                 };
1064
1065                 Api::install(requestInst);
1066             };
1067
1068             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1069         };
1070         //Start child
1071         errno = 0;
1072         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1073
1074         int status;
1075         wait(&status);
1076
1077         for(auto &user : users) {
1078             user.remove();
1079         };
1080     };
1081
1082     if (pid == 0) {
1083         errno = 0;
1084         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1085         struct passwd *pw = getUserStruct(usernames.at(0));
1086         register_current_process_as_privilege_manager(pw->pw_uid);
1087
1088         //change uid to normal user
1089         errno = 0;
1090         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1091         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1092
1093         std::vector<PolicyEntry> policyEntries;
1094         PolicyEntry filter;
1095
1096         //this call should only return privileges belonging to the current uid
1097         Api::getPolicy(filter, policyEntries);
1098
1099         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1100         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1101
1102         for (const auto &policyEntry : policyEntries) {
1103             std::string user = policyEntry.getUser();
1104             std::string app = policyEntry.getAppId();
1105             std::string privilege = policyEntry.getPrivilege();
1106
1107             try {
1108                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1109                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1110                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1111                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1112             } catch (const std::out_of_range &e) {
1113                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1114             } catch (const std::invalid_argument& e) {
1115                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1116             };
1117         };
1118         exit(0);
1119     };
1120 }
1121
1122 RUNNER_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1123 {
1124     //TEST DATA
1125     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1126     unsigned int privileges_count = 0;
1127
1128     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1129     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1130
1131     for (const auto &username : usernames) {
1132
1133         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1134             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1135                 MANY_APPS.at(i), std::set<std::string>(
1136                     MANY_APPS_PRIVILEGES.at(i).begin(),
1137                     MANY_APPS_PRIVILEGES.at(i).end())));
1138             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1139         };
1140
1141         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1142     };
1143
1144     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1145         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1146
1147     privileges_count += 2;
1148     //TEST DATA END
1149
1150     sem_t *mutex;
1151     errno = 0;
1152     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1153     errno = 0;
1154     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1155     pid_t pid = fork();
1156
1157     if (pid != 0) { //parent process
1158         std::vector<TemporaryTestUser> users = {
1159             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1160             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1161             };
1162
1163         users.at(0).create();
1164         users.at(1).create();
1165         //Install apps for both users
1166         for(const auto &user : users) {
1167             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1168                 InstallRequest requestInst;
1169                 requestInst.setAppId(app.first.c_str());
1170                 try {
1171                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1172                 } catch (const std::out_of_range &e) {
1173                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1174                 };
1175                 requestInst.setUid(user.getUid());
1176
1177                 for (const auto &privilege : app.second) {
1178                     requestInst.addPrivilege(privilege.c_str());
1179                 };
1180
1181                 Api::install(requestInst);
1182             };
1183
1184             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1185         };
1186
1187         //Start child
1188         errno = 0;
1189         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1190
1191         //Wait for child to finish
1192         int status;
1193         wait(&status);
1194
1195         for(auto &user : users) {
1196             user.remove();
1197         };
1198     };
1199
1200     if (pid == 0) { //child process
1201         errno = 0;
1202         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1203
1204         struct passwd *pw = getUserStruct(usernames.at(1));
1205         register_current_process_as_privilege_manager(pw->pw_uid, true);
1206
1207         //change uid to normal user
1208         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1209         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1210
1211         std::vector<PolicyEntry> policyEntries;
1212         PolicyEntry filter;
1213         //this call should succeed as the calling user is privileged
1214         Api::getPolicy(filter, policyEntries);
1215
1216         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1217         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1218
1219         for (const auto &policyEntry : policyEntries) {
1220             std::string user = policyEntry.getUser();
1221             std::string app = policyEntry.getAppId();
1222             std::string privilege = policyEntry.getPrivilege();
1223
1224             try {
1225                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1226                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1227                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1228                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1229             } catch (const std::out_of_range &e) {
1230                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1231             } catch (const std::invalid_argument& e) {
1232                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1233             };
1234         };
1235
1236         exit(0);
1237     };
1238 }
1239
1240 RUNNER_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1241 {
1242     //TEST DATA
1243     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1244
1245     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1246     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1247
1248     for (const auto &username : usernames) {
1249
1250         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1251             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1252                 MANY_APPS.at(i), std::set<std::string>(
1253                     MANY_APPS_PRIVILEGES.at(i).begin(),
1254                     MANY_APPS_PRIVILEGES.at(i).end())));
1255         };
1256
1257         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1258     };
1259
1260     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1261         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1262
1263     //TEST DATA END
1264
1265     pid_t pid[2];
1266     sem_t *mutex[2];
1267     errno = 0;
1268     RUNNER_ASSERT_MSG(((mutex[0] = sem_open("mutex_1", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #1, errno: " << errno);
1269     errno = 0;
1270     RUNNER_ASSERT_MSG(((mutex[1] = sem_open("mutex_2", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #2, errno: " << errno);
1271     errno = 0;
1272     RUNNER_ASSERT_MSG(sem_init(mutex[0], 1, 0) == 0, "failed to setup mutex #1, errno: " << errno);
1273     errno = 0;
1274     RUNNER_ASSERT_MSG(sem_init(mutex[1], 1, 0) == 0, "failed to setup mutex #2, errno: " << errno);
1275     std::vector<PolicyEntry> policyEntries;
1276
1277     pid[0] = fork();
1278
1279     if(pid[0] == 0) { //child #1 process
1280         RUNNER_ASSERT_MSG(sem_wait(mutex[0]) == 0, "sem_wait in child #1 failed, errno: " << errno);
1281         struct passwd *pw = getUserStruct(usernames.at(0));
1282         register_current_process_as_privilege_manager(pw->pw_uid);
1283
1284         //change uid to normal user
1285         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1286         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1287
1288         PolicyEntry filter;
1289         PolicyRequest policyRequest;
1290         //this call should succeed as the calling user is privileged
1291         Api::getPolicyForSelf(filter, policyEntries);
1292
1293         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1294
1295         PolicyEntry policyEntry(
1296                 MANY_APPS[0],
1297                 std::to_string(pw->pw_uid),
1298                 "http://tizen.org/privilege/internet"
1299                 );
1300         policyEntry.setLevel("Deny");
1301
1302         policyRequest.addEntry(policyEntry);
1303         policyEntry = PolicyEntry(
1304                 MANY_APPS[1],
1305                 std::to_string(pw->pw_uid),
1306                 "http://tizen.org/privilege/location"
1307                 );
1308         policyEntry.setLevel("Deny");
1309
1310         policyRequest.addEntry(policyEntry);
1311         Api::sendPolicy(policyRequest);
1312         Api::getPolicyForSelf(filter, policyEntries);
1313
1314         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1315         exit(0);
1316     };
1317
1318     if (pid[0] != 0) {//parent process
1319         pid[1] = fork();
1320
1321         if (pid[1] == 0) { //child #2 process
1322             errno = 0;
1323             RUNNER_ASSERT_MSG(sem_wait(mutex[1]) == 0, "sem_wait in child #2 failed, errno: " << errno);
1324             struct passwd *pw_target = getUserStruct(usernames.at(0));
1325             struct passwd *pw = getUserStruct(usernames.at(1));
1326             register_current_process_as_privilege_manager(pw->pw_uid);
1327
1328             //change uid to normal user
1329             int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1330             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1331
1332             PolicyEntry filter = PolicyEntry(
1333                         SECURITY_MANAGER_ANY,
1334                         std::to_string(pw_target->pw_uid),
1335                         SECURITY_MANAGER_ANY
1336                         );
1337
1338             //U2 requests contents of U1 privacy manager - should fail
1339             Api::getPolicyForSelf(filter, policyEntries);
1340             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1341
1342             filter = PolicyEntry(
1343                         SECURITY_MANAGER_ANY,
1344                         SECURITY_MANAGER_ANY,
1345                         SECURITY_MANAGER_ANY
1346                         );
1347
1348             policyEntries.clear();
1349
1350             //U2 requests contents of ADMIN bucket - should fail
1351             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1352             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1353             exit(0);
1354         };
1355
1356         if (pid[1] != 0) { //parent
1357
1358             std::vector<TemporaryTestUser> users = {
1359                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1360                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1361                 };
1362
1363             users.at(0).create();
1364             users.at(1).create();
1365
1366             //Install apps for both users
1367             for(const auto &user : users2AppsMap) {
1368
1369                 for(const auto &app : user.second) {
1370                     InstallRequest requestInst;
1371                     requestInst.setAppId(app.first.c_str());
1372                     try {
1373                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1374                     } catch (const std::out_of_range &e) {
1375                         RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1376                     };
1377                     requestInst.setUid(users.at(0).getUid());
1378
1379                     for (const auto &privilege : app.second) {
1380                         requestInst.addPrivilege(privilege.c_str());
1381                     };
1382
1383                     Api::install(requestInst);
1384                 };
1385
1386                 //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1387             };
1388
1389             int status;
1390             //Start child #1
1391             errno = 0;
1392             RUNNER_ASSERT_MSG(sem_post(mutex[0]) ==  0, "Error while opening mutex #1, errno: " << errno);
1393
1394             //Wait until child #1 finishes
1395             pid_t ret = wait(&status);
1396             RUNNER_ASSERT_MSG((ret != -1) && WIFEXITED(status), "Updating privileges failed");
1397
1398             //Start child #2
1399             errno = 0;
1400             RUNNER_ASSERT_MSG(sem_post(mutex[1]) ==  0, "Error while opening mutex #2, errno: " << errno);
1401             //Wait until child #2 finishes
1402             ret = wait(&status);
1403             RUNNER_ASSERT_MSG((ret =-1) && WIFEXITED(status), "Listing privileges failed");
1404
1405             for(auto &user : users) {
1406                 user.remove();
1407             };
1408
1409             sem_close(mutex[0]);
1410             sem_close(mutex[1]);
1411         };
1412     };
1413 }
1414
1415 RUNNER_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1416 {
1417     //TEST DATA
1418     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1419     unsigned int privileges_count = 0;
1420
1421     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1422     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1423
1424     for (const auto &username : usernames) {
1425
1426         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1427             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1428                 MANY_APPS.at(i), std::set<std::string>(
1429                     MANY_APPS_PRIVILEGES.at(i).begin(),
1430                     MANY_APPS_PRIVILEGES.at(i).end())));
1431             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1432         };
1433
1434         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1435     };
1436
1437     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1438         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1439
1440     privileges_count += 2;
1441     //TEST DATA END
1442     sem_t *mutex;
1443     errno = 0;
1444     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1445     errno = 0;
1446     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1447
1448     pid_t pid = fork();
1449     if (pid != 0) {
1450         std::vector<TemporaryTestUser> users = {
1451             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1452             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1453             };
1454
1455         users.at(0).create();
1456         users.at(1).create();
1457
1458         //Install apps for both users
1459         for(const auto &user : users) {
1460
1461             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1462                 InstallRequest requestInst;
1463                 requestInst.setAppId(app.first.c_str());
1464                 try {
1465                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1466                 } catch (const std::out_of_range &e) {
1467                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1468                 };
1469                 requestInst.setUid(user.getUid());
1470
1471                 for (const auto &privilege : app.second) {
1472                     requestInst.addPrivilege(privilege.c_str());
1473                 };
1474
1475                 Api::install(requestInst);
1476             };
1477         };
1478         //Start child process
1479         errno = 0;
1480         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1481         int status;
1482         //Wait for child process to finish
1483         wait(&status);
1484
1485         //switch back to root
1486         for(auto &user : users) {
1487             user.remove();
1488         };
1489
1490         sem_close(mutex);
1491     }
1492
1493     if (pid == 0) { //child process
1494         errno = 0;
1495         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
1496
1497         struct passwd *pw = getUserStruct(usernames.at(0));
1498         register_current_process_as_privilege_manager(pw->pw_uid, true);
1499
1500         //change uid to normal user
1501         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1502         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1503
1504         PolicyRequest *policyRequest = new PolicyRequest();
1505         PolicyEntry filter;
1506         std::vector<PolicyEntry> policyEntries;
1507         //this call should succeed as the calling user is privileged
1508         Api::getPolicyForSelf(filter, policyEntries);
1509
1510         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1511
1512         PolicyEntry policyEntry(
1513                 SECURITY_MANAGER_ANY,
1514                 SECURITY_MANAGER_ANY,
1515                 "http://tizen.org/privilege/internet"
1516                 );
1517         policyEntry.setMaxLevel("Deny");
1518
1519         policyRequest->addEntry(policyEntry);
1520         policyEntry = PolicyEntry(
1521                 SECURITY_MANAGER_ANY,
1522                 SECURITY_MANAGER_ANY,
1523                 "http://tizen.org/privilege/location"
1524                 );
1525         policyEntry.setMaxLevel("Deny");
1526
1527         policyRequest->addEntry(policyEntry);
1528         Api::sendPolicy(*policyRequest);
1529         Api::getPolicyForAdmin(filter, policyEntries);
1530
1531         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1532
1533         delete policyRequest;
1534         policyRequest = new PolicyRequest();
1535         policyEntry = PolicyEntry(
1536                 SECURITY_MANAGER_ANY,
1537                 SECURITY_MANAGER_ANY,
1538                 "http://tizen.org/privilege/internet"
1539                 );
1540         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1541         policyRequest->addEntry(policyEntry);
1542
1543         policyEntry = PolicyEntry(
1544                 SECURITY_MANAGER_ANY,
1545                 SECURITY_MANAGER_ANY,
1546                 "http://tizen.org/privilege/location"
1547                 );
1548         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1549
1550         policyRequest->addEntry(policyEntry);
1551         Api::sendPolicy(*policyRequest);
1552
1553         policyEntries.clear();
1554         Api::getPolicyForAdmin(filter, policyEntries);
1555         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1556
1557         delete policyRequest;
1558
1559         exit(0);
1560     };
1561
1562 }
1563
1564 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1565 {
1566     const char *const update_app_id = "security_manager_15_update_app_id";
1567     const char *const update_privilege = "http://tizen.org/privilege/led";
1568     const char *const check_start_bucket = "ADMIN";
1569     const std::string username("sm_test_15_username");
1570     PolicyRequest addPolicyRequest;
1571     CynaraTestAdmin::Admin admin;
1572
1573     std::string smackLabel;
1574     generateAppLabel(update_app_id, smackLabel);
1575
1576     struct message {
1577         uid_t uid;
1578         gid_t gid;
1579     } msg;
1580
1581     int pipefd[2];
1582     pid_t pid;
1583     int result = 0;
1584
1585     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1586
1587     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1588     user.create();
1589
1590     pid = fork();
1591     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1592     if (pid != 0)//parent process
1593     {
1594         FdUniquePtr pipeptr(pipefd+1);
1595         close(pipefd[0]);
1596
1597         register_current_process_as_privilege_manager(user.getUid(), true);
1598
1599         //send info to child
1600         msg.uid = user.getUid();
1601         msg.gid = user.getGid();
1602
1603         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1604         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1605
1606         //wait for child
1607         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1608
1609         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1610                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1611     }
1612     if(pid == 0)
1613     {
1614         FdUniquePtr pipeptr(pipefd);
1615         close(pipefd[1]);
1616
1617         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1618         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1619
1620         //become admin privacy manager manager
1621         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1622         result = drop_root_privileges(msg.uid, msg.gid);
1623         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1624
1625         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1626         entry.setMaxLevel("Allow");
1627
1628         addPolicyRequest.addEntry(entry);
1629         Api::sendPolicy(addPolicyRequest);
1630         exit(0);
1631     }
1632 }
1633
1634 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1635 {
1636     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1637     const char *const update_privilege = "http://tizen.org/privilege/led";
1638     const char *const check_start_bucket = "ADMIN";
1639     const std::string username("sm_test_15_username");
1640     PolicyRequest addPolicyRequest;
1641     CynaraTestAdmin::Admin admin;
1642
1643     std::string smackLabel;
1644     generateAppLabel(update_other_app_id, smackLabel);
1645
1646     struct message {
1647         uid_t uid;
1648         gid_t gid;
1649     } msg;
1650
1651     int pipefd[2];
1652     pid_t pid;
1653     int result = 0;
1654
1655     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1656
1657     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1658     user.create();
1659
1660     pid = fork();
1661     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1662     if (pid != 0)//parent process
1663     {
1664         FdUniquePtr pipeptr(pipefd+1);
1665         close(pipefd[0]);
1666
1667         register_current_process_as_privilege_manager(user.getUid(), true);
1668
1669         //send info to child
1670         msg.uid = user.getUid();
1671         msg.gid = user.getGid();
1672
1673         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1674         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1675
1676         //wait for child
1677         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1678
1679         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1680                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1681     }
1682     if(pid == 0)
1683     {
1684         FdUniquePtr pipeptr(pipefd);
1685         close(pipefd[1]);
1686
1687         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1688         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1689
1690         //become admin privacy manager manager
1691         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1692         result = drop_root_privileges(msg.uid, msg.gid);
1693         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1694
1695         // use wildcard as appId
1696         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1697         entry.setMaxLevel("Allow");
1698
1699         addPolicyRequest.addEntry(entry);
1700         Api::sendPolicy(addPolicyRequest);
1701         exit(0);
1702     }
1703 }
1704
1705 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1706 {
1707     const char *const update_app_id = "security_manager_15_update_app_id";
1708     const char *const update_privilege = "http://tizen.org/privilege/led";
1709     const char *const check_start_bucket = "";
1710     const std::string username("sm_test_15_username");
1711     PolicyRequest addPolicyRequest;
1712     CynaraTestAdmin::Admin admin;
1713
1714     std::string smackLabel;
1715     generateAppLabel(update_app_id, smackLabel);
1716
1717     struct message {
1718         uid_t uid;
1719         gid_t gid;
1720     } msg;
1721
1722     int pipefd[2];
1723     pid_t pid;
1724     int result = 0;
1725
1726     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1727
1728     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1729     user.create();
1730
1731     pid = fork();
1732     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1733     if (pid != 0)//parent process
1734     {
1735         FdUniquePtr pipeptr(pipefd+1);
1736         close(pipefd[0]);
1737
1738         register_current_process_as_privilege_manager(user.getUid(), false);
1739
1740         //send info to child
1741         msg.uid = user.getUid();
1742         msg.gid = user.getGid();
1743
1744         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1745         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1746
1747         //wait for child
1748         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1749
1750         admin.adminCheck(check_start_bucket, false, smackLabel.c_str(),
1751                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1752     }
1753     if(pid == 0)
1754     {
1755         FdUniquePtr pipeptr(pipefd);
1756         close(pipefd[1]);
1757
1758         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1759         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1760
1761         //become admin privacy manager manager
1762         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1763         result = drop_root_privileges(msg.uid, msg.gid);
1764         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1765
1766         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1767         entry.setLevel("Allow");
1768
1769         addPolicyRequest.addEntry(entry);
1770         Api::sendPolicy(addPolicyRequest);
1771         exit(0);
1772     }
1773 }
1774
1775 int main(int argc, char *argv[])
1776 {
1777     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
1778 }