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