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