security-manager-tests: use full proper path for applications
[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     ServiceManager serviceManager("security-manager.service");
819
820     uninstall_app(app_id, pkg_id, true);
821     serviceManager.maskService();
822     serviceManager.stopService();
823
824     install_app(app_id, pkg_id);
825
826     serviceManager.unmaskService();
827     serviceManager.startService();
828
829     uninstall_app(app_id, pkg_id, true);
830 }
831
832 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
833 {
834     const char *const sm_app_id = "sm_test_07_app_id_user";
835     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
836     const std::string new_user_name = "sm_test_07_user_name";
837     std::string uid_string;
838     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
839     test_user.create();
840     test_user.getUidString(uid_string);
841
842     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
843     createTestDirs(test_user, sm_app_id, sm_pkg_id);
844
845     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
846
847     check_app_after_install(sm_app_id, sm_pkg_id);
848
849     test_user.remove();
850
851     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
852
853     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
854 }
855
856 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
857 {
858     UserRequest addUserRequest;
859
860     const char *const sm_app_id = "sm_test_08_app_id_user";
861     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
862     const std::string new_user_name = "sm_test_08_user_name";
863     std::string uid_string;
864
865     // gumd user add
866     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
867     test_user.create();
868     test_user.getUidString(uid_string);
869
870     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
871     createTestDirs(test_user, sm_app_id, sm_pkg_id);
872
873     addUserRequest.setUid(test_user.getUid());
874     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
875
876     //sm user add
877     Api::addUser(addUserRequest);
878
879     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
880
881     check_app_after_install(sm_app_id, sm_pkg_id);
882
883     test_user.remove();
884
885     UserRequest deleteUserRequest;
886     deleteUserRequest.setUid(test_user.getUid());
887
888     Api::deleteUser(deleteUserRequest);
889
890     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
891
892     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
893 }
894
895 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
896 {
897     const char *const app_id = "security_manager_09_add_user_offline_app";
898     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
899     const std::string new_user_name("sm_test_09_user_name");
900     ServiceManager serviceManager("security-manager.service");
901     serviceManager.maskService();
902     serviceManager.stopService();
903
904     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, true);
905     test_user.create();
906
907     removeTestDirs(test_user, app_id, pkg_id);
908     createTestDirs(test_user, app_id, pkg_id);
909
910     install_app(app_id, pkg_id, test_user.getUid());
911
912     check_app_after_install(app_id, pkg_id);
913
914     serviceManager.unmaskService();
915     serviceManager.startService();
916
917     test_user.remove();
918
919     check_app_after_uninstall(app_id, pkg_id, true);
920 }
921
922 RUNNER_MULTIPROCESS_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
923 {
924     //TEST DATA
925     const std::string username("sm_test_10_user_name");
926     unsigned int privileges_count = 0;
927
928     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
929     std::map<std::string, std::set<std::string>> apps2PrivsMap;
930
931     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
932         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
933             MANY_APPS.at(i), std::set<std::string>(
934                 MANY_APPS_PRIVILEGES.at(i).begin(),
935                 MANY_APPS_PRIVILEGES.at(i).end())));
936         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
937     };
938
939     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
940         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
941     ++privileges_count;
942     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
943     //TEST DATA END
944
945     sem_t *mutex;
946     errno = 0;
947     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
948     errno = 0;
949     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
950     pid_t pid = fork();
951
952     if (pid != 0) { //parent process
953         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
954         tmpUser.create();
955
956         for(const auto &user : users2AppsMap) {
957
958             for(const auto &app : user.second) {
959                 InstallRequest requestInst;
960                 requestInst.setAppId(app.first.c_str());
961                 try {
962                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
963                 } catch (const std::out_of_range &e) {
964                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
965                 };
966                 requestInst.setUid(tmpUser.getUid());
967
968                 for (const auto &privilege : app.second) {
969                     requestInst.addPrivilege(privilege.c_str());
970                 };
971
972                 Api::install(requestInst);
973             };
974
975             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
976         };
977         //Start child process
978         errno = 0;
979         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
980
981         int status;
982         wait(&status);
983
984         tmpUser.remove();
985     };
986
987     if (pid == 0) { //child process
988         errno = 0;
989         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
990         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
991
992         struct passwd *pw = getUserStruct(username);
993         register_current_process_as_privilege_manager(pw->pw_uid);
994         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
995         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
996
997         std::vector<PolicyEntry> policyEntries;
998         PolicyEntry filter;
999         Api::getPolicy(filter, policyEntries);
1000
1001         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1002         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1003
1004         for (const auto &policyEntry : policyEntries) {
1005             std::string user = policyEntry.getUser();
1006             std::string app = policyEntry.getAppId();
1007             std::string privilege = policyEntry.getPrivilege();
1008
1009             try {
1010                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1011                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1012                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1013                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1014             } catch (const std::out_of_range &e) {
1015                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1016             } catch (const std::invalid_argument& e) {
1017                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1018             };
1019         };
1020         exit(0);
1021     };
1022 }
1023
1024 RUNNER_MULTIPROCESS_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1025 {
1026     //TEST DATA
1027     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1028     unsigned int privileges_count = 0;
1029
1030     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1031     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1032
1033     for (const auto &username : usernames) {
1034         //Only entries for one of the users will be listed
1035         privileges_count = 0;
1036
1037         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1038             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1039                 MANY_APPS.at(i), std::set<std::string>(
1040                     MANY_APPS_PRIVILEGES.at(i).begin(),
1041                     MANY_APPS_PRIVILEGES.at(i).end())));
1042             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1043         };
1044
1045         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1046     };
1047
1048     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1049         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1050
1051     ++privileges_count;
1052     //TEST DATA END
1053
1054     sem_t *mutex;
1055     errno = 0;
1056     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1057     errno = 0;
1058     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1059     pid_t pid = fork();
1060
1061     if (pid != 0) { //parent process
1062         std::vector<TemporaryTestUser> users = {
1063             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1064             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1065             };
1066
1067         users.at(0).create();
1068         users.at(1).create();
1069
1070         //Install apps for both users
1071         for(const auto &user : users) {
1072             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1073                 InstallRequest requestInst;
1074                 requestInst.setAppId(app.first.c_str());
1075                 try {
1076                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1077                 } catch (const std::out_of_range &e) {
1078                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1079                 };
1080                 requestInst.setUid(user.getUid());
1081
1082                 for (const auto &privilege : app.second) {
1083                     requestInst.addPrivilege(privilege.c_str());
1084                 };
1085
1086                 Api::install(requestInst);
1087             };
1088
1089             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1090         };
1091         //Start child
1092         errno = 0;
1093         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1094
1095         int status;
1096         wait(&status);
1097
1098         for(auto &user : users) {
1099             user.remove();
1100         };
1101     };
1102
1103     if (pid == 0) {
1104         errno = 0;
1105         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1106         struct passwd *pw = getUserStruct(usernames.at(0));
1107         register_current_process_as_privilege_manager(pw->pw_uid);
1108
1109         //change uid to normal user
1110         errno = 0;
1111         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1112         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1113
1114         std::vector<PolicyEntry> policyEntries;
1115         PolicyEntry filter;
1116
1117         //this call should only return privileges belonging to the current uid
1118         Api::getPolicy(filter, policyEntries);
1119
1120         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1121         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1122
1123         for (const auto &policyEntry : policyEntries) {
1124             std::string user = policyEntry.getUser();
1125             std::string app = policyEntry.getAppId();
1126             std::string privilege = policyEntry.getPrivilege();
1127
1128             try {
1129                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1130                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1131                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1132                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1133             } catch (const std::out_of_range &e) {
1134                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1135             } catch (const std::invalid_argument& e) {
1136                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1137             };
1138         };
1139         exit(0);
1140     };
1141 }
1142
1143 RUNNER_MULTIPROCESS_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1144 {
1145     //TEST DATA
1146     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1147     unsigned int privileges_count = 0;
1148
1149     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1150     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1151
1152     for (const auto &username : usernames) {
1153
1154         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1155             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1156                 MANY_APPS.at(i), std::set<std::string>(
1157                     MANY_APPS_PRIVILEGES.at(i).begin(),
1158                     MANY_APPS_PRIVILEGES.at(i).end())));
1159             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1160         };
1161
1162         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1163     };
1164
1165     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1166         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1167
1168     privileges_count += 2;
1169     //TEST DATA END
1170
1171     sem_t *mutex;
1172     errno = 0;
1173     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1174     errno = 0;
1175     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1176     pid_t pid = fork();
1177
1178     if (pid != 0) { //parent process
1179         std::vector<TemporaryTestUser> users = {
1180             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1181             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1182             };
1183
1184         users.at(0).create();
1185         users.at(1).create();
1186         //Install apps for both users
1187         for(const auto &user : users) {
1188             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1189                 InstallRequest requestInst;
1190                 requestInst.setAppId(app.first.c_str());
1191                 try {
1192                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1193                 } catch (const std::out_of_range &e) {
1194                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1195                 };
1196                 requestInst.setUid(user.getUid());
1197
1198                 for (const auto &privilege : app.second) {
1199                     requestInst.addPrivilege(privilege.c_str());
1200                 };
1201
1202                 Api::install(requestInst);
1203             };
1204
1205             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1206         };
1207
1208         //Start child
1209         errno = 0;
1210         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1211
1212         //Wait for child to finish
1213         int status;
1214         wait(&status);
1215
1216         for(auto &user : users) {
1217             user.remove();
1218         };
1219     };
1220
1221     if (pid == 0) { //child process
1222         errno = 0;
1223         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1224
1225         struct passwd *pw = getUserStruct(usernames.at(1));
1226         register_current_process_as_privilege_manager(pw->pw_uid, true);
1227
1228         //change uid to normal user
1229         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1230         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1231
1232         std::vector<PolicyEntry> policyEntries;
1233         PolicyEntry filter;
1234         //this call should succeed as the calling user is privileged
1235         Api::getPolicy(filter, policyEntries);
1236
1237         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1238         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1239
1240         for (const auto &policyEntry : policyEntries) {
1241             std::string user = policyEntry.getUser();
1242             std::string app = policyEntry.getAppId();
1243             std::string privilege = policyEntry.getPrivilege();
1244
1245             try {
1246                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1247                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1248                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1249                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1250             } catch (const std::out_of_range &e) {
1251                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1252             } catch (const std::invalid_argument& e) {
1253                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1254             };
1255         };
1256
1257         exit(0);
1258     };
1259 }
1260
1261 RUNNER_MULTIPROCESS_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1262 {
1263     //TEST DATA
1264     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1265
1266     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1267     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1268
1269     for (const auto &username : usernames) {
1270
1271         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1272             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1273                 MANY_APPS.at(i), std::set<std::string>(
1274                     MANY_APPS_PRIVILEGES.at(i).begin(),
1275                     MANY_APPS_PRIVILEGES.at(i).end())));
1276         };
1277
1278         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1279     };
1280
1281     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1282         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1283
1284     //TEST DATA END
1285
1286     pid_t pid[2];
1287     sem_t *mutex[2];
1288     errno = 0;
1289     RUNNER_ASSERT_MSG(((mutex[0] = sem_open("mutex_1", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #1, errno: " << errno);
1290     errno = 0;
1291     RUNNER_ASSERT_MSG(((mutex[1] = sem_open("mutex_2", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #2, errno: " << errno);
1292     errno = 0;
1293     RUNNER_ASSERT_MSG(sem_init(mutex[0], 1, 0) == 0, "failed to setup mutex #1, errno: " << errno);
1294     errno = 0;
1295     RUNNER_ASSERT_MSG(sem_init(mutex[1], 1, 0) == 0, "failed to setup mutex #2, errno: " << errno);
1296     std::vector<PolicyEntry> policyEntries;
1297
1298     pid[0] = fork();
1299
1300     if(pid[0] == 0) { //child #1 process
1301         RUNNER_ASSERT_MSG(sem_wait(mutex[0]) == 0, "sem_wait in child #1 failed, errno: " << errno);
1302         struct passwd *pw = getUserStruct(usernames.at(0));
1303         register_current_process_as_privilege_manager(pw->pw_uid);
1304
1305         //change uid to normal user
1306         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1307         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1308
1309         PolicyEntry filter;
1310         PolicyRequest policyRequest;
1311         //this call should succeed as the calling user is privileged
1312         Api::getPolicyForSelf(filter, policyEntries);
1313
1314         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1315
1316         PolicyEntry policyEntry(
1317                 MANY_APPS[0],
1318                 std::to_string(pw->pw_uid),
1319                 "http://tizen.org/privilege/internet"
1320                 );
1321         policyEntry.setLevel("Deny");
1322
1323         policyRequest.addEntry(policyEntry);
1324         policyEntry = PolicyEntry(
1325                 MANY_APPS[1],
1326                 std::to_string(pw->pw_uid),
1327                 "http://tizen.org/privilege/location"
1328                 );
1329         policyEntry.setLevel("Deny");
1330
1331         policyRequest.addEntry(policyEntry);
1332         Api::sendPolicy(policyRequest);
1333         Api::getPolicyForSelf(filter, policyEntries);
1334
1335         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1336         exit(0);
1337     };
1338
1339     if (pid[0] != 0) {//parent process
1340         pid[1] = fork();
1341
1342         if (pid[1] == 0) { //child #2 process
1343             errno = 0;
1344             RUNNER_ASSERT_MSG(sem_wait(mutex[1]) == 0, "sem_wait in child #2 failed, errno: " << errno);
1345             struct passwd *pw_target = getUserStruct(usernames.at(0));
1346             struct passwd *pw = getUserStruct(usernames.at(1));
1347             register_current_process_as_privilege_manager(pw->pw_uid);
1348
1349             //change uid to normal user
1350             int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1351             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1352
1353             PolicyEntry filter = PolicyEntry(
1354                         SECURITY_MANAGER_ANY,
1355                         std::to_string(pw_target->pw_uid),
1356                         SECURITY_MANAGER_ANY
1357                         );
1358
1359             //U2 requests contents of U1 privacy manager - should fail
1360             Api::getPolicyForSelf(filter, policyEntries);
1361             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1362
1363             filter = PolicyEntry(
1364                         SECURITY_MANAGER_ANY,
1365                         SECURITY_MANAGER_ANY,
1366                         SECURITY_MANAGER_ANY
1367                         );
1368
1369             policyEntries.clear();
1370
1371             //U2 requests contents of ADMIN bucket - should fail
1372             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1373             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1374             exit(0);
1375         };
1376
1377         if (pid[1] != 0) { //parent
1378
1379             std::vector<TemporaryTestUser> users = {
1380                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1381                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1382                 };
1383
1384             users.at(0).create();
1385             users.at(1).create();
1386
1387             //Install apps for both users
1388             for(const auto &user : users2AppsMap) {
1389
1390                 for(const auto &app : user.second) {
1391                     InstallRequest requestInst;
1392                     requestInst.setAppId(app.first.c_str());
1393                     try {
1394                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1395                     } catch (const std::out_of_range &e) {
1396                         RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1397                     };
1398                     requestInst.setUid(users.at(0).getUid());
1399
1400                     for (const auto &privilege : app.second) {
1401                         requestInst.addPrivilege(privilege.c_str());
1402                     };
1403
1404                     Api::install(requestInst);
1405                 };
1406
1407                 //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1408             };
1409
1410             int status;
1411             //Start child #1
1412             errno = 0;
1413             RUNNER_ASSERT_MSG(sem_post(mutex[0]) ==  0, "Error while opening mutex #1, errno: " << errno);
1414
1415             //Wait until child #1 finishes
1416             pid_t ret = wait(&status);
1417             RUNNER_ASSERT_MSG((ret != -1) && WIFEXITED(status), "Updating privileges failed");
1418
1419             //Start child #2
1420             errno = 0;
1421             RUNNER_ASSERT_MSG(sem_post(mutex[1]) ==  0, "Error while opening mutex #2, errno: " << errno);
1422             //Wait until child #2 finishes
1423             ret = wait(&status);
1424             RUNNER_ASSERT_MSG((ret =-1) && WIFEXITED(status), "Listing privileges failed");
1425
1426             for(auto &user : users) {
1427                 user.remove();
1428             };
1429
1430             sem_close(mutex[0]);
1431             sem_close(mutex[1]);
1432         };
1433     };
1434 }
1435
1436 RUNNER_MULTIPROCESS_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1437 {
1438     //TEST DATA
1439     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1440     unsigned int privileges_count = 0;
1441
1442     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1443     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1444
1445     for (const auto &username : usernames) {
1446
1447         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1448             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1449                 MANY_APPS.at(i), std::set<std::string>(
1450                     MANY_APPS_PRIVILEGES.at(i).begin(),
1451                     MANY_APPS_PRIVILEGES.at(i).end())));
1452             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1453         };
1454
1455         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1456     };
1457
1458     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1459         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1460
1461     privileges_count += 2;
1462     //TEST DATA END
1463     sem_t *mutex;
1464     errno = 0;
1465     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1466     errno = 0;
1467     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1468
1469     pid_t pid = fork();
1470     if (pid != 0) {
1471         std::vector<TemporaryTestUser> users = {
1472             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1473             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1474             };
1475
1476         users.at(0).create();
1477         users.at(1).create();
1478
1479         //Install apps for both users
1480         for(const auto &user : users) {
1481
1482             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1483                 InstallRequest requestInst;
1484                 requestInst.setAppId(app.first.c_str());
1485                 try {
1486                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).c_str());
1487                 } catch (const std::out_of_range &e) {
1488                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1489                 };
1490                 requestInst.setUid(user.getUid());
1491
1492                 for (const auto &privilege : app.second) {
1493                     requestInst.addPrivilege(privilege.c_str());
1494                 };
1495
1496                 Api::install(requestInst);
1497             };
1498         };
1499         //Start child process
1500         errno = 0;
1501         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1502         int status;
1503         //Wait for child process to finish
1504         wait(&status);
1505
1506         //switch back to root
1507         for(auto &user : users) {
1508             user.remove();
1509         };
1510
1511         sem_close(mutex);
1512     }
1513
1514     if (pid == 0) { //child process
1515         errno = 0;
1516         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
1517
1518         struct passwd *pw = getUserStruct(usernames.at(0));
1519         register_current_process_as_privilege_manager(pw->pw_uid, true);
1520
1521         //change uid to normal user
1522         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1523         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1524
1525         PolicyRequest *policyRequest = new PolicyRequest();
1526         PolicyEntry filter;
1527         std::vector<PolicyEntry> policyEntries;
1528         //this call should succeed as the calling user is privileged
1529         Api::getPolicyForSelf(filter, policyEntries);
1530
1531         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1532
1533         PolicyEntry policyEntry(
1534                 SECURITY_MANAGER_ANY,
1535                 SECURITY_MANAGER_ANY,
1536                 "http://tizen.org/privilege/internet"
1537                 );
1538         policyEntry.setMaxLevel("Deny");
1539
1540         policyRequest->addEntry(policyEntry);
1541         policyEntry = PolicyEntry(
1542                 SECURITY_MANAGER_ANY,
1543                 SECURITY_MANAGER_ANY,
1544                 "http://tizen.org/privilege/location"
1545                 );
1546         policyEntry.setMaxLevel("Deny");
1547
1548         policyRequest->addEntry(policyEntry);
1549         Api::sendPolicy(*policyRequest);
1550         Api::getPolicyForAdmin(filter, policyEntries);
1551
1552         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1553
1554         delete policyRequest;
1555         policyRequest = new PolicyRequest();
1556         policyEntry = PolicyEntry(
1557                 SECURITY_MANAGER_ANY,
1558                 SECURITY_MANAGER_ANY,
1559                 "http://tizen.org/privilege/internet"
1560                 );
1561         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1562         policyRequest->addEntry(policyEntry);
1563
1564         policyEntry = PolicyEntry(
1565                 SECURITY_MANAGER_ANY,
1566                 SECURITY_MANAGER_ANY,
1567                 "http://tizen.org/privilege/location"
1568                 );
1569         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1570
1571         policyRequest->addEntry(policyEntry);
1572         Api::sendPolicy(*policyRequest);
1573
1574         policyEntries.clear();
1575         Api::getPolicyForAdmin(filter, policyEntries);
1576         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1577
1578         delete policyRequest;
1579
1580         exit(0);
1581     };
1582
1583 }
1584
1585 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1586 {
1587     const char *const update_app_id = "security_manager_15_update_app_id";
1588     const char *const update_privilege = "http://tizen.org/privilege/led";
1589     const char *const check_start_bucket = "ADMIN";
1590     const std::string username("sm_test_15_username");
1591     PolicyRequest addPolicyRequest;
1592     CynaraTestAdmin::Admin admin;
1593
1594     struct message {
1595         uid_t uid;
1596         gid_t gid;
1597     } msg;
1598
1599     int pipefd[2];
1600     pid_t pid;
1601     int result = 0;
1602
1603     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1604
1605     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1606     user.create();
1607
1608     pid = fork();
1609     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1610     if (pid != 0)//parent process
1611     {
1612         FdUniquePtr pipeptr(pipefd+1);
1613         close(pipefd[0]);
1614
1615         register_current_process_as_privilege_manager(user.getUid(), true);
1616
1617         //send info to child
1618         msg.uid = user.getUid();
1619         msg.gid = user.getGid();
1620
1621         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1622         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1623
1624         //wait for child
1625         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1626
1627         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1628                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1629     }
1630     if(pid == 0)
1631     {
1632         FdUniquePtr pipeptr(pipefd);
1633         close(pipefd[1]);
1634
1635         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1636         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1637
1638         //become admin privacy manager manager
1639         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1640         result = drop_root_privileges(msg.uid, msg.gid);
1641         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1642
1643         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1644         entry.setMaxLevel("Allow");
1645
1646         addPolicyRequest.addEntry(entry);
1647         Api::sendPolicy(addPolicyRequest);
1648         exit(0);
1649     }
1650 }
1651
1652 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1653 {
1654     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1655     const char *const update_privilege = "http://tizen.org/privilege/led";
1656     const char *const check_start_bucket = "ADMIN";
1657     const std::string username("sm_test_15_username");
1658     PolicyRequest addPolicyRequest;
1659     CynaraTestAdmin::Admin admin;
1660
1661     struct message {
1662         uid_t uid;
1663         gid_t gid;
1664     } msg;
1665
1666     int pipefd[2];
1667     pid_t pid;
1668     int result = 0;
1669
1670     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1671
1672     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1673     user.create();
1674
1675     pid = fork();
1676     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1677     if (pid != 0)//parent process
1678     {
1679         FdUniquePtr pipeptr(pipefd+1);
1680         close(pipefd[0]);
1681
1682         register_current_process_as_privilege_manager(user.getUid(), true);
1683
1684         //send info to child
1685         msg.uid = user.getUid();
1686         msg.gid = user.getGid();
1687
1688         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1689         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1690
1691         //wait for child
1692         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1693
1694         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_other_app_id).c_str(),
1695                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1696     }
1697     if(pid == 0)
1698     {
1699         FdUniquePtr pipeptr(pipefd);
1700         close(pipefd[1]);
1701
1702         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1703         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1704
1705         //become admin privacy manager manager
1706         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1707         result = drop_root_privileges(msg.uid, msg.gid);
1708         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1709
1710         // use wildcard as appId
1711         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1712         entry.setMaxLevel("Allow");
1713
1714         addPolicyRequest.addEntry(entry);
1715         Api::sendPolicy(addPolicyRequest);
1716         exit(0);
1717     }
1718 }
1719
1720 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1721 {
1722     const char *const update_app_id = "security_manager_15_update_app_id";
1723     const char *const update_privilege = "http://tizen.org/privilege/led";
1724     const char *const check_start_bucket = "";
1725     const std::string username("sm_test_15_username");
1726     PolicyRequest addPolicyRequest;
1727     CynaraTestAdmin::Admin admin;
1728
1729     struct message {
1730         uid_t uid;
1731         gid_t gid;
1732     } msg;
1733
1734     int pipefd[2];
1735     pid_t pid;
1736     int result = 0;
1737
1738     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1739
1740     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1741     user.create();
1742
1743     pid = fork();
1744     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1745     if (pid != 0)//parent process
1746     {
1747         FdUniquePtr pipeptr(pipefd+1);
1748         close(pipefd[0]);
1749
1750         register_current_process_as_privilege_manager(user.getUid(), false);
1751
1752         //send info to child
1753         msg.uid = user.getUid();
1754         msg.gid = user.getGid();
1755
1756         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1757         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1758
1759         //wait for child
1760         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1761
1762         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1763                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1764     }
1765     if(pid == 0)
1766     {
1767         FdUniquePtr pipeptr(pipefd);
1768         close(pipefd[1]);
1769
1770         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1771         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1772
1773         //become admin privacy manager manager
1774         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1775         result = drop_root_privileges(msg.uid, msg.gid);
1776         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1777
1778         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1779         entry.setLevel("Allow");
1780
1781         addPolicyRequest.addEntry(entry);
1782         Api::sendPolicy(addPolicyRequest);
1783         exit(0);
1784     }
1785 }
1786
1787 RUNNER_MULTIPROCESS_TEST(security_manager_16_policy_levels_get)
1788 {
1789     const std::string username("sm_test_16_user_cynara_policy");
1790     CynaraTestAdmin::Admin admin;
1791     int pipefd[2];
1792     pid_t pid;
1793     int result = 0;
1794
1795     struct message {
1796         uid_t uid;
1797         gid_t gid;
1798     } msg;
1799
1800     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1801
1802     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1803     user.create();
1804
1805     pid = fork();
1806     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1807     if (pid != 0)//parent process
1808     {
1809         FdUniquePtr pipeptr(pipefd+1);
1810         close(pipefd[0]);
1811
1812         //send info to child
1813         msg.uid = user.getUid();
1814         msg.gid = user.getGid();
1815
1816         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1817         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1818
1819         //wait for child
1820         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1821     }
1822     if(pid == 0)
1823     {
1824         int ret;
1825         char** levels;
1826         std::string allow_policy, deny_policy;
1827         size_t count;
1828         FdUniquePtr pipeptr(pipefd);
1829         close(pipefd[1]);
1830
1831         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1832         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1833
1834         //become admin privacy manager manager
1835         result = drop_root_privileges(msg.uid, msg.gid);
1836         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1837
1838         // without plugins there should only be 2 policies - Allow and Deny
1839         ret = security_manager_policy_levels_get(&levels, &count);
1840
1841         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
1842                 "Invlid return code: " << ret);
1843
1844         RUNNER_ASSERT_MSG(count == 2, "Invalid number of policy levels. Should be 2, instead there is: " << static_cast<int>(count));
1845
1846         deny_policy = std::string(levels[0]);
1847         allow_policy = std::string(levels[count-1]);
1848
1849         // first should always be Deny
1850         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
1851                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
1852
1853         // last should always be Allow
1854         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
1855                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
1856
1857         security_manager_policy_levels_free(levels, count);
1858         exit(0);
1859     }
1860 }
1861
1862 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
1863 {
1864     const char *const update_app_id = "security_manager_17_update_app_id";
1865     const char *const update_privilege = "http://tizen.org/privilege/led";
1866     const char *const check_start_bucket = "";
1867     const std::string username("sm_test_17_username");
1868     PolicyRequest addPolicyRequest;
1869     CynaraTestAdmin::Admin admin;
1870
1871     struct message {
1872         uid_t uid;
1873         gid_t gid;
1874     } msg;
1875
1876     int pipefd[2];
1877     int pipefd2[2];
1878     pid_t pid;
1879     int result = 0;
1880
1881     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1882     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
1883
1884     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1885     user.create();
1886
1887     pid = fork();
1888     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1889     if (pid != 0)//parent process
1890     {
1891         FdUniquePtr pipeptr(pipefd+1);
1892         close(pipefd[0]);
1893
1894         register_current_process_as_privilege_manager(user.getUid(), false);
1895
1896         //send info to child
1897         msg.uid = user.getUid();
1898         msg.gid = user.getGid();
1899
1900         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1901         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1902
1903         //wait for child
1904         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1905
1906         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1907                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1908
1909         pid = fork();
1910         if (pid != 0)//parent process
1911         {
1912             FdUniquePtr pipeptr(pipefd2+1);
1913             close(pipefd2[0]);
1914
1915             //send info to child
1916             msg.uid = user.getUid();
1917             msg.gid = user.getGid();
1918
1919             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
1920             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1921
1922             //wait for child
1923             RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1924
1925             //wait for child
1926             waitpid(-1, &result, 0);
1927
1928             admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1929                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
1930         }
1931         if(pid == 0)
1932         {
1933             FdUniquePtr pipeptr(pipefd2);
1934             close(pipefd2[1]);
1935
1936             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
1937             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1938
1939             //become admin privacy manager manager
1940             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1941             result = drop_root_privileges(msg.uid, msg.gid);
1942             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1943
1944             // delete this entry
1945             PolicyRequest deletePolicyRequest;
1946             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1947             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
1948
1949             deletePolicyRequest.addEntry(deleteEntry);
1950             Api::sendPolicy(deletePolicyRequest);
1951             exit(0);
1952         }
1953     }
1954     if(pid == 0)
1955     {
1956         FdUniquePtr pipeptr(pipefd);
1957         close(pipefd[1]);
1958
1959         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1960         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1961
1962         //become admin privacy manager manager
1963         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1964         result = drop_root_privileges(msg.uid, msg.gid);
1965         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1966
1967         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1968         entry.setLevel("Allow");
1969
1970         addPolicyRequest.addEntry(entry);
1971         Api::sendPolicy(addPolicyRequest);
1972         exit(0);
1973     }
1974 }
1975
1976 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
1977 {
1978     const std::string username("sm_test_17_user_name");
1979
1980     struct message {
1981         uid_t uid;
1982         gid_t gid;
1983         unsigned int privileges_count;
1984     } msg;
1985
1986     int pipefd[2];
1987     pid_t pid;
1988     int result = 0;
1989
1990     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1991
1992     pid = fork();
1993     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1994     if (pid != 0)//parent process
1995     {
1996         FdUniquePtr pipeptr(pipefd+1);
1997         close(pipefd[0]);
1998
1999         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2000         user.create();
2001
2002         unsigned int privileges_count = 0;
2003
2004         register_current_process_as_privilege_manager(user.getUid(), false);
2005         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2006         ++privileges_count;
2007
2008         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2009             InstallRequest requestInst;
2010             requestInst.setAppId(MANY_APPS[i].c_str());
2011             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).c_str());
2012             requestInst.setUid(user.getUid());
2013
2014             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2015                 requestInst.addPrivilege(priv.c_str());
2016             };
2017
2018             Api::install(requestInst);
2019             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2020         };
2021
2022         //send info to child
2023         msg.uid = user.getUid();
2024         msg.gid = user.getGid();
2025         msg.privileges_count = privileges_count;
2026
2027         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2028         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2029
2030         //wait for child
2031         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2032     }
2033     if(pid == 0)
2034     {
2035         FdUniquePtr pipeptr(pipefd);
2036         close(pipefd[1]);
2037
2038         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2039         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2040
2041         //become admin privacy manager manager
2042         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2043         result = drop_root_privileges(msg.uid, msg.gid);
2044         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2045
2046         // filter by privilege
2047         std::vector<PolicyEntry> policyEntries;
2048         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2049         Api::getPolicy(filter, policyEntries);
2050
2051         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2052         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2053
2054         // filter by other privilege
2055         policyEntries.clear();
2056         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2057         Api::getPolicy(filter2, policyEntries);
2058
2059         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2060         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2061
2062         // filter by appId
2063         policyEntries.clear();
2064         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2065         Api::getPolicy(filter3, policyEntries);
2066
2067         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2068         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2069     }
2070 }
2071
2072 RUNNER_CHILD_TEST(security_manager_10_user_cynara_policy)
2073 {
2074     const char *const MAIN_BUCKET = "MAIN";
2075     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2076     const char *const ADMIN_BUCKET = "ADMIN";
2077     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2078     const std::string username("sm_test_10_user_cynara_policy");
2079     CynaraTestAdmin::Admin admin;
2080     std::string uid_string;
2081     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2082     user.create();
2083     user.getUidString(uid_string);
2084
2085     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2086     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2087     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2088
2089     user.remove();
2090     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2091
2092     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2093     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2094     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2095     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2096 }
2097
2098 RUNNER_CHILD_TEST(security_manager_11_security_manager_cmd_install)
2099 {
2100     int ret;
2101     const int SUCCESS = 0;
2102     const int FAILURE = 256;
2103     const std::string app_id = "security_manager_10_app";
2104     const std::string pkg_id = "security_manager_10_pkg";
2105     const std::string username("sm_test_10_user_name");
2106     std::string uid_string;
2107     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2108     user.create();
2109     user.getUidString(uid_string);
2110     const std::string path1 = "/home/" + username + "/p1";
2111     const std::string path2 = "/home/" + username + "/p2";
2112     const std::string pkgopt = " --pkg=" + pkg_id;
2113     const std::string appopt = " --app=" + app_id;
2114     const std::string uidopt = " --uid=" + uid_string;
2115
2116     mkdir(path1.c_str(), 0);
2117     mkdir(path2.c_str(), 0);
2118
2119     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2120
2121     struct operation {
2122         std::string command;
2123         int expected_result;
2124     };
2125     std::vector<struct operation> operations = {
2126             {"security-manager-cmd", FAILURE},//no option
2127             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2128             {"security-manager-cmd --help", SUCCESS},
2129             {"security-manager-cmd --install", FAILURE},//no params
2130             {"security-manager-cmd -i", FAILURE},//no params
2131             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2132             {installcmd, SUCCESS},
2133             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2134             {installcmd + " --path " + path1 + " private", SUCCESS},
2135             {installcmd + " --path " + path1, FAILURE},//no path type
2136             {installcmd + " --path " + path1 + " private" + " --path " + path2 + " private", SUCCESS},
2137             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " public", FAILURE},//wrong path type
2138             {installcmd + " --path " + path1 + " private" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2139     };
2140
2141     for (auto &op : operations) {
2142         ret = system(op.command.c_str());
2143         RUNNER_ASSERT_MSG(ret == op.expected_result,
2144                 "Unexpected result for command '" << op.command <<"': "
2145                 << ret << " Expected was: "<< op.expected_result);
2146     }
2147 }
2148
2149 RUNNER_CHILD_TEST(security_manager_12_security_manager_cmd_users)
2150 {
2151     int ret;
2152     const int SUCCESS = 0;
2153     const int FAILURE = 256;
2154     const std::string username("sm_test_11_user_name");
2155     std::string uid_string;
2156     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2157     user.create();
2158     user.getUidString(uid_string);
2159     const std::string uidopt = " --uid=" + uid_string;
2160
2161     struct operation {
2162         std::string command;
2163         int expected_result;
2164     };
2165     std::vector<struct operation> operations = {
2166             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2167             {"security-manager-cmd -m", FAILURE},//no params
2168             {"security-manager-cmd -mr", FAILURE},//no uid
2169             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2170             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2171             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2172             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2173             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2174             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2175             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2176             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2177     };
2178
2179     for (auto &op : operations) {
2180         ret = system(op.command.c_str());
2181         RUNNER_ASSERT_MSG(ret == op.expected_result,
2182                 "Unexpected result for command '" << op.command <<"': "
2183                 << ret << " Expected was: "<< op.expected_result);
2184     }
2185 }
2186
2187 RUNNER_MULTIPROCESS_TEST(security_manager_13_security_manager_admin_deny_user_priv)
2188 {
2189     const int BUFFER_SIZE = 128;
2190     struct message {
2191         uid_t uid;
2192         gid_t gid;
2193         char buf[BUFFER_SIZE];
2194     } msg;
2195
2196     privileges_t admin_required_privs = {
2197             "http://tizen.org/privilege/systemsettings.admin",
2198             "http://tizen.org/privilege/systemsettings"};
2199     privileges_t manifest_privs = {
2200             "http://tizen.org/privilege/internet",
2201             "http://tizen.org/privilege/camera"};
2202     privileges_t real_privs_allow = {"http://tizen.org/privilege/camera"};
2203     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2204
2205     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2206     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2207     const std::string app_id = "sm_test_13_SOME_APP";
2208     const std::string pkg_id = "sm_test_13_SOME_PKG";
2209
2210     int pipefd[2];
2211     pid_t pid;
2212     int result = 0;
2213
2214     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2215     pid = fork();
2216     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2217     if (pid != 0)//parent process
2218     {
2219         std::string childuidstr;
2220         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, true);
2221         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, true);
2222
2223         InstallRequest request,request2;
2224         FdUniquePtr pipeptr(pipefd+1);
2225         close(pipefd[0]);
2226
2227         admin.create();
2228         child.create();
2229         child.getUidString(childuidstr);
2230
2231         //install privacy manager for admin
2232         request.setAppId(pirivman_id.c_str());
2233         request.setPkgId(pirivman_pkg_id.c_str());
2234         request.setUid(admin.getUid());
2235         for (auto &priv: admin_required_privs)
2236             request.addPrivilege(priv.c_str());
2237         Api::install(request);
2238
2239         //install app for child that has internet privilege
2240         request2.setAppId(app_id.c_str());
2241         request2.setPkgId(pkg_id.c_str());
2242         request2.setUid(child.getUid());
2243         for (auto &priv: manifest_privs)
2244             request2.addPrivilege(priv.c_str());
2245         Api::install(request2);
2246
2247         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2248                               manifest_privs, SM_NO_PRIVILEGES);
2249
2250         //send info to child
2251         msg.uid = admin.getUid();
2252         msg.gid = admin.getGid();
2253         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2254
2255         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2256         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2257
2258         //wait for child
2259         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2260
2261         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2262                               real_privs_allow, real_privs_deny);
2263     }
2264     if (pid == 0)//child
2265     {
2266         FdUniquePtr pipeptr(pipefd);
2267         close(pipefd[1]);
2268
2269         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2270         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2271
2272         //become admin privacy manager manager
2273         Api::setProcessLabel(pirivman_id.c_str());
2274         result = drop_root_privileges(msg.uid, msg.gid);
2275         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2276         PolicyRequest addPolicyReq;
2277         //change rights
2278         for (auto &denypriv:real_privs_deny) {
2279             /*this entry will deny some privileges for user whose uid (as c string)
2280               was sent in message's buf field.
2281               That user would be denying internet for child in this case*/
2282             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2283             entry.setMaxLevel("Deny");
2284             addPolicyReq.addEntry(entry);
2285         }
2286         Api::sendPolicy(addPolicyReq);
2287         exit(0);
2288     }
2289 }
2290
2291 int main(int argc, char *argv[])
2292 {
2293     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
2294 }