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