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