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