[SM] Turn off tests that does not work because of gumd timeout.
[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 #include <sys/smack.h>
16
17 #include <algorithm>
18 #include <fstream>
19 #include <string>
20 #include <unordered_set>
21
22 #include <grp.h>
23 #include <pwd.h>
24
25 #include <tzplatform_config.h>
26 #include <security-manager.h>
27
28 #include <dpl/log/log.h>
29 #include <dpl/test/test_runner.h>
30 #include <libprivilege-control_test_common.h>
31 #include <tests_common.h>
32 #include <sm_api.h>
33 #include <sm_db.h>
34 #include <sm_request.h>
35 #include <sm_sharing_request.h>
36 #include <sm_user_request.h>
37 #include <app_install_helper.h>
38 #include <temp_test_user.h>
39 #include <cynara_test_client.h>
40 #include <cynara_test_admin.h>
41 #include <service_manager.h>
42 #include <cynara_test_admin.h>
43 #include "memory.h"
44
45 using namespace SecurityManagerTest;
46
47 DEFINE_SMARTPTR(cap_free, _cap_struct, CapsSetsUniquePtr);
48 DEFINE_SMARTPTR(tzplatform_context_destroy, tzplatform_context, TzPlatformContextPtr);
49
50 static const privileges_t SM_ALLOWED_PRIVILEGES = {
51     "http://tizen.org/privilege/location",
52     "http://tizen.org/privilege/camera"
53 };
54
55 static const privileges_t SM_DENIED_PRIVILEGES  = {
56     "http://tizen.org/privilege/bluetooth",
57     "http://tizen.org/privilege/power"
58 };
59
60 static const privileges_t SM_NO_PRIVILEGES  = {
61 };
62
63 static const std::vector<std::string> SM_ALLOWED_GROUPS = {"db_browser", "db_alarm"};
64
65 void changeSecurityContext(const std::string& label, uid_t uid, gid_t gid)
66 {
67     RUNNER_ASSERT_ERRNO_MSG(0 == smack_set_label_for_self(label.c_str()),
68         "Error in smack_set_label_for_self(" << label << ")");
69
70     RUNNER_ASSERT_ERRNO_MSG(0 == setgid(gid), "Error in setgid.");
71     RUNNER_ASSERT_ERRNO_MSG(0 == setuid(uid), "Error in setuid.");
72 }
73
74 std::string genPath(int app_num, const char *postfix) {
75     char buf[16];
76     sprintf(buf, "%02d", app_num);
77     return std::string("/usr/apps/sm_test_") + std::string(buf) + std::string("_pkg_id_full/") + std::string(postfix);
78 }
79 std::string genRWPath(int app_num) {
80     return genPath(app_num, "app_dir");
81 }
82 std::string genROPath(int app_num) {
83     return genPath(app_num, "app_dir_ro");
84 }
85 std::string genPublicROPath(int app_num) {
86     return genPath(app_num, "app_dir_public_ro");
87 }
88 std::string genOwnerRWOthersROPath(int app_num) {
89     return genPath(app_num, "app_dir_rw_others_ro");
90 }
91
92 static const char *const SM_RW_PATH = "/usr/apps/sm_test_02_pkg_id_full/app_dir";
93
94 static const char *const SM_DENIED_PATH = "/usr/apps/non_app_dir";
95 static const char *const SM_TRUSTED_PATH = "/usr/apps/sm_test_02_pkg_id_full/app_dir_trusted";
96
97 static const char *const ANY_USER_REPRESENTATION = "anyuser";/*this may be actually any string*/
98 static const std::string EXEC_FILE("exec");
99 static const std::string NORMAL_FILE("normal");
100 static const std::string LINK_PREFIX("link_to_");
101
102 static const std::string PRIVILEGE_MANAGER_APP = "privilege_manager";
103 static const std::string PRIVILEGE_MANAGER_PKG = "privilege_manager";
104 static const std::string PRIVILEGE_MANAGER_SELF_PRIVILEGE = "http://tizen.org/privilege/systemsettings";
105 static const std::string PRIVILEGE_MANAGER_ADMIN_PRIVILEGE = "http://tizen.org/privilege/systemsettings.admin";
106
107 static const std::vector<std::string> MANY_APPS = {
108     "security_manager_10_app_1",
109     "security_manager_10_app_2",
110     "security_manager_10_app_3",
111     "security_manager_10_app_4",
112     "security_manager_10_app_5"
113 };
114
115 struct app_attributes {
116     std::string package;
117     std::string Tizen_ver;
118 };
119 static const std::map<std::string, struct app_attributes> MANY_APPS_PKGS = {
120     {"security_manager_10_app_1", {"security_manager_10_pkg_1", "2.1"}},
121     {"security_manager_10_app_2", {"security_manager_10_pkg_2", "3.0"}},
122     {"security_manager_10_app_3", {"security_manager_10_pkg_3", "2.1.1"}},
123     {"security_manager_10_app_4", {"security_manager_10_pkg_4", "3.1"}},
124     {"security_manager_10_app_5", {"security_manager_10_pkg_5", "2.2"}},
125     {PRIVILEGE_MANAGER_APP, {PRIVILEGE_MANAGER_PKG, "3.0"}}
126 };
127
128 static const std::vector<privileges_t> MANY_APPS_PRIVILEGES = {
129     {
130         "http://tizen.org/privilege/internet",
131         "http://tizen.org/privilege/location"
132     },
133     {
134         "http://tizen.org/privilege/telephony",
135         "http://tizen.org/privilege/camera"
136     },
137     {
138         "http://tizen.org/privilege/contact.read",
139         "http://tizen.org/privilege/led",
140         "http://tizen.org/privilege/email"
141     },
142     {
143         "http://tizen.org/privilege/led",
144         "http://tizen.org/privilege/email",
145         "http://tizen.org/privilege/telephony",
146         "http://tizen.org/privilege/camera"
147     },
148     {
149         "http://tizen.org/privilege/internet",
150         "http://tizen.org/privilege/location",
151         "http://tizen.org/privilege/led",
152         "http://tizen.org/privilege/email"
153     }
154 };
155
156 /* PRIVILEGE MAPPING TEST CONSTS */
157
158 static const std::string OLD_VERSION = "2.4";
159 static const std::string NEW_VERSION = "3.0";
160
161 static const std::vector<std::string> OLD_PRIVILEGES = {
162         "http://tizen.org/privilege/internet.old",
163         "http://tizen.org/privilege/telephony.old",
164         "http://tizen.org/privilege/contact.old",
165         "http://tizen.org/privilege/led.old",
166         "http://tizen.org/privilege/email.old"
167 };
168
169 static const std::vector<privileges_t> &NEW_PRIVILEGES = MANY_APPS_PRIVILEGES;
170
171 static const privileges_t DEFAULT_PRIVILEGES = {
172         "http://tizen.org/privilege/led",
173         "http://tizen.org/privilege/internet"
174 };
175
176 static std::string generateAppLabel(const std::string &appId)
177 {
178     return "User::App::" + appId;
179 }
180
181 static std::string generatePkgLabelOwnerRWothersRO(const std::string &pkgId)
182 {
183     return "User::Pkg::" + pkgId + "::SharedRO";
184 }
185
186 static std::string generatePkgLabel(const std::string &pkgId)
187 {
188     return "User::Pkg::" + pkgId;
189 }
190
191 static int nftw_check_sm_labels_app_dir(const char *fpath, const struct stat *sb,
192                               const char* correctLabel, bool transmute_test, bool exec_test)
193 {
194     int result;
195     CStringPtr labelPtr;
196     char* label = nullptr;
197
198     /* ACCESS */
199     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
200     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
201     labelPtr.reset(label);
202     RUNNER_ASSERT_MSG(label != nullptr, "ACCESS label on " << fpath << " is not set");
203     result = strcmp(correctLabel, label);
204     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is incorrect"
205             " (should be '" << correctLabel << "' and is '" << label << "')");
206
207
208     /* EXEC */
209     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
210     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
211     labelPtr.reset(label);
212
213     if (S_ISREG(sb->st_mode) && (sb->st_mode & S_IXUSR) && exec_test) {
214         RUNNER_ASSERT_MSG(label != nullptr, "EXEC label on " << fpath << " is not set");
215         result = strcmp(correctLabel, label);
216         RUNNER_ASSERT_MSG(result == 0, "Incorrect EXEC label on executable file " << fpath);
217     } else
218         RUNNER_ASSERT_MSG(label == nullptr, "EXEC label on " << fpath << " is set");
219
220
221     /* TRANSMUTE */
222     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
223     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
224     labelPtr.reset(label);
225
226     if (S_ISDIR(sb->st_mode) && transmute_test == true) {
227         RUNNER_ASSERT_MSG(label != nullptr, "TRANSMUTE label on " << fpath << " is not set at all");
228         RUNNER_ASSERT_MSG(strcmp(label,"TRUE") == 0,
229                 "TRANSMUTE label on " << fpath << " is not set properly: '"<<label<<"'");
230     } else {
231         RUNNER_ASSERT_MSG(label == nullptr, "TRANSMUTE label on " << fpath << " is set");
232     }
233
234     return 0;
235 }
236
237 // nftw doesn't allow passing user data to functions. Work around by using global variable
238 static std::string nftw_expected_label;
239 bool nftw_expected_transmute;
240 bool nftw_expected_exec;
241
242 static int nftw_check_sm_labels(const char *fpath, const struct stat *sb,
243                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
244 {
245     return nftw_check_sm_labels_app_dir(fpath, sb,
246         nftw_expected_label.c_str(), nftw_expected_transmute, nftw_expected_exec);
247 }
248
249 static void prepare_app_path(int app_num, bool others_enabled = false)
250 {
251     std::string SM_RW_PATH = genRWPath(app_num);
252     std::string SM_RO_PATH = genROPath(app_num);
253     std::string SM_PUBLIC_RO_PATH = genPublicROPath(app_num);
254     int result;
255
256     result = nftw(SM_RW_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
257     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RW_PATH);
258
259     result = nftw(SM_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
260     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RO_PATH);
261
262     result = nftw(SM_PUBLIC_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
263     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_PUBLIC_RO_PATH);
264
265     if(others_enabled) {
266         std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(app_num);
267         result = nftw(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
268         RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_OWNER_RW_OTHERS_RO_PATH);
269     }
270
271     result = nftw(SM_DENIED_PATH, &nftw_set_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
272     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_DENIED_PATH);
273 }
274
275 static void prepare_app_env(int app_num, bool others_enabled = false)
276 {
277     prepare_app_path(app_num, others_enabled);
278 }
279
280 static void check_app_path_after_install(int app_num, const char *pkgId, bool others_enabled=false)
281 {
282     std::string SM_RW_PATH = genRWPath(app_num);
283     std::string SM_RO_PATH = genROPath(app_num);
284     std::string SM_PUBLIC_RO_PATH = genPublicROPath(app_num);
285     int result;
286
287     nftw_expected_label = generatePkgLabel(pkgId);
288     nftw_expected_transmute = true;
289     nftw_expected_exec = false;
290
291     result = nftw(SM_RW_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
292     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RW_PATH);
293
294     nftw_expected_label = generatePkgLabel(pkgId) + "::RO";
295     nftw_expected_transmute = false;
296     nftw_expected_exec = false;
297
298     result = nftw(SM_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
299     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RO_PATH);
300
301     nftw_expected_label = "User::Home";
302     nftw_expected_transmute = true;
303     nftw_expected_exec = false;
304
305     result = nftw(SM_PUBLIC_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
306     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_PUBLIC_RO_PATH);
307
308     result = nftw(SM_DENIED_PATH, &nftw_check_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
309     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_DENIED_PATH);
310
311     // owner RW, others RO
312     if(others_enabled) {
313         std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(app_num);
314         nftw_expected_label = generatePkgLabelOwnerRWothersRO(pkgId);
315         nftw_expected_transmute = true;
316         nftw_expected_exec = false;
317
318         result = nftw(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
319         RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_OWNER_RW_OTHERS_RO_PATH);
320     }
321 }
322
323
324 static void check_app_permissions(const char *const app_id, const char *const pkg_id, const char *const user,
325                                   const privileges_t &allowed_privs, const privileges_t &denied_privs)
326 {
327     (void) pkg_id;
328     std::string smackLabel = generateAppLabel(app_id);
329
330     CynaraTestClient::Client ctc;
331
332     for (auto &priv : allowed_privs) {
333         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_ALLOWED);
334     }
335
336     for (auto &priv : denied_privs) {
337         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_DENIED);
338     }
339 }
340
341 static void check_app_gids(const char *const app_id, const std::vector<gid_t> &allowed_gids)
342 {
343     int ret;
344     gid_t main_gid = getgid();
345     std::unordered_set<gid_t> reference_gids(allowed_gids.begin(), allowed_gids.end());
346
347     // Reset supplementary groups
348     ret = setgroups(0, NULL);
349     RUNNER_ASSERT_MSG(ret != -1, "Unable to set supplementary groups");
350
351     Api::setProcessGroups(app_id);
352
353     ret = getgroups(0, nullptr);
354     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
355
356     std::vector<gid_t> actual_gids(ret);
357     ret = getgroups(ret, actual_gids.data());
358     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
359
360     for (const auto &gid : actual_gids) {
361         RUNNER_ASSERT_MSG(gid == main_gid || reference_gids.count(gid) > 0,
362             "Application shouldn't get access to group " << gid);
363         reference_gids.erase(gid);
364     }
365
366     RUNNER_ASSERT_MSG(reference_gids.empty(), "Application didn't get access to some groups");
367 }
368
369 static void check_app_after_install(const char *const app_id, const char *const pkg_id,
370                                     const privileges_t &allowed_privs,
371                                     const privileges_t &denied_privs,
372                                     const std::vector<std::string> &allowed_groups)
373 {
374     TestSecurityManagerDatabase dbtest;
375     dbtest.test_db_after__app_install(app_id, pkg_id, allowed_privs);
376     dbtest.check_privileges_removed(app_id, pkg_id, denied_privs);
377
378     /*Privileges should be granted to all users if root installs app*/
379     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, allowed_privs, denied_privs);
380
381     /* Setup mapping of gids to privileges */
382     /* Do this for each privilege for extra check */
383     for (const auto &privilege : allowed_privs) {
384         dbtest.setup_privilege_groups(privilege, allowed_groups);
385     }
386
387     std::vector<gid_t> allowed_gids;
388
389     for (const auto &groupName : allowed_groups) {
390         errno = 0;
391         struct group* grp = getgrnam(groupName.c_str());
392         RUNNER_ASSERT_ERRNO_MSG(grp, "Group: " << groupName << " not found");
393         allowed_gids.push_back(grp->gr_gid);
394     }
395
396     check_app_gids(app_id, allowed_gids);
397 }
398
399 static void check_app_after_install(const char *const app_id, const char *const pkg_id)
400 {
401     TestSecurityManagerDatabase dbtest;
402     dbtest.test_db_after__app_install(app_id, pkg_id);
403 }
404
405 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
406                                       const privileges_t &privileges, const bool is_pkg_removed)
407 {
408     TestSecurityManagerDatabase dbtest;
409     dbtest.test_db_after__app_uninstall(app_id, pkg_id, privileges, is_pkg_removed);
410
411
412     /*Privileges should not be granted anymore to any user*/
413     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, SM_NO_PRIVILEGES, privileges);
414 }
415
416 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
417                                       const bool is_pkg_removed)
418 {
419     TestSecurityManagerDatabase dbtest;
420     dbtest.test_db_after__app_uninstall(app_id, pkg_id, is_pkg_removed);
421 }
422
423 static void install_app(const char *app_id, const char *pkg_id, uid_t uid = 0)
424 {
425     InstallRequest request;
426     request.setAppId(app_id);
427     request.setPkgId(pkg_id);
428     request.setUid(uid);
429     Api::install(request);
430
431     check_app_after_install(app_id, pkg_id);
432 }
433
434 static void uninstall_app(const char *app_id, const char *pkg_id, bool expect_pkg_removed)
435 {
436     InstallRequest request;
437     request.setAppId(app_id);
438
439     Api::uninstall(request);
440
441     check_app_after_uninstall(app_id, pkg_id, expect_pkg_removed);
442 }
443
444 static inline void register_current_process_as_privilege_manager(uid_t uid, bool forAdmin = false)
445 {
446     InstallRequest request;
447     request.setAppId(PRIVILEGE_MANAGER_APP.c_str());
448     request.setPkgId(PRIVILEGE_MANAGER_PKG.c_str());
449     request.setUid(uid);
450     request.addPrivilege(PRIVILEGE_MANAGER_SELF_PRIVILEGE.c_str());
451     if (forAdmin)
452         request.addPrivilege(PRIVILEGE_MANAGER_ADMIN_PRIVILEGE.c_str());
453     Api::install(request);
454     Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
455 };
456
457 static inline struct passwd *getUserStruct(const std::string &userName) {
458     struct passwd *pw = nullptr;
459     errno = 0;
460
461     while(!(pw = getpwnam(userName.c_str()))) {
462         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
463     };
464
465     return pw;
466 };
467
468 static inline struct passwd *getUserStruct(const uid_t uid) {
469     struct passwd *pw = nullptr;
470     errno = 0;
471
472     while(!(pw = getpwuid(uid))) {
473         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
474     };
475
476     return pw;
477 };
478
479 void check_exact_access(const std::string& subject, const std::string& object, const std::string& access)
480 {
481     // check access
482     if (!access.empty()) {
483         int result = smack_have_access(subject.c_str(), object.c_str(), access.c_str());
484         RUNNER_ASSERT_MSG(result >= 0, "smack_have_access failed");
485         RUNNER_ASSERT_MSG(result == 1,
486           "No smack access: " << subject << " " << object << " " << access);
487     }
488     // check excessive access
489     auto foundInAccess = [&access](std::string::value_type c) {
490         return access.find(c) != std::string::npos; };
491
492     std::string negative = "rwxatl";
493     auto end = std::remove_if(negative.begin(), negative.end(), foundInAccess);
494     negative.erase(end, negative.end());
495
496     for(const auto& c : negative) {
497         int result = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
498         RUNNER_ASSERT_MSG(result >= 0, "smack_have_access failed");
499         RUNNER_ASSERT_MSG(result == 0,
500                           "Unexpected smack access: " << subject << " " << object << " " << c);
501     }
502 }
503
504 std::string access_opposite(std::string &access) {
505     static const std::map<char, int> access_mapping = {{'r', 0}, {'w', 1}, {'x', 2}, {'a', 3},
506                                                        {'t', 4}, {'l', 5}};
507     //May write implies may lock
508     if (access.find('w') != std::string::npos && access.find('l') == std::string::npos) {
509         access.append("l");
510     }
511     std::string access_opposite = "rwxatl";
512     for (char c : access) {
513         access_opposite[access_mapping.at(c)] = '-';
514     }
515     auto it = std::remove_if(access_opposite.begin(), access_opposite.end(), [](char c) {return c == '-';});
516     access_opposite.erase(it, access_opposite.end());
517     return access_opposite;
518 }
519
520 void check_exact_smack_accesses(const std::string &subject, const std::string &object, const std::string &access) {
521     std::string access_str(access);
522     auto no_access = access_opposite(access_str);
523     for (char c : access_str) {
524         int ret = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
525         RUNNER_ASSERT_MSG(ret >= 0, "smack_have_access failed: <" << subject << ">, <" << object << ">, <" << c << "> errno=" << strerror(errno));
526         RUNNER_ASSERT_MSG(ret == 1, "Access " << c << " from " << subject << " to "
527                           << object << " not given");
528     }
529
530     for (char c : no_access) {
531         int ret = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
532         RUNNER_ASSERT_MSG(ret >= 0, "smack_have_access failed: <" << subject << ">, <" << object << ">, <" << c << "> errno=" << strerror(errno));
533         RUNNER_ASSERT_MSG(ret == 0, "Access " << c << " from " << subject << " to "
534                           << object << " unnecessarily given");
535     }
536 }
537
538
539 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER)
540
541
542 RUNNER_TEST(security_manager_01a_app_double_install_double_uninstall)
543 {
544     const char *const sm_app_id = "sm_test_01a_app_id_double";
545     const char *const sm_pkg_id = "sm_test_01a_pkg_id_double";
546
547     InstallRequest requestInst;
548     requestInst.setAppId(sm_app_id);
549     requestInst.setPkgId(sm_pkg_id);
550
551     Api::install(requestInst);
552     Api::install(requestInst);
553
554     // Check records in the security-manager database
555     check_app_after_install(sm_app_id, sm_pkg_id);
556
557     InstallRequest requestUninst;
558     requestUninst.setAppId(sm_app_id);
559
560     Api::uninstall(requestUninst);
561     Api::uninstall(requestUninst);
562
563     // Check records in the security-manager database
564     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
565 }
566
567
568 RUNNER_TEST(security_manager_01b_app_double_install_wrong_pkg_id)
569 {
570     const char *const sm_app_id = "sm_test_01b_app";
571     const char *const sm_pkg_id = "sm_test_01b_pkg";
572     const char *const sm_pkg_id_wrong = "sm_test_01b_pkg_BAD";
573
574     InstallRequest requestInst;
575     requestInst.setAppId(sm_app_id);
576     requestInst.setPkgId(sm_pkg_id);
577
578     Api::install(requestInst);
579
580     InstallRequest requestInst2;
581     requestInst2.setAppId(sm_app_id);
582     requestInst2.setPkgId(sm_pkg_id_wrong);
583
584     Api::install(requestInst2, SECURITY_MANAGER_ERROR_INPUT_PARAM);
585
586
587     /* Check records in the security-manager database */
588     check_app_after_install(sm_app_id, sm_pkg_id);
589
590     InstallRequest requestUninst;
591     requestUninst.setAppId(sm_app_id);
592
593     Api::uninstall(requestUninst);
594
595
596     /* Check records in the security-manager database */
597     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
598
599 }
600
601 RUNNER_TEST(security_manager_01c_app_uninstall_pkg_id_ignored)
602 {
603     const char * const  sm_app_id = "SM_TEST_01c_APPID";
604     const char * const  sm_pkg_id = "SM_TEST_01c_PKGID";
605     const char * const  sm_pkg_id_wrong = "SM_TEST_01c_PKGID_wrong";
606
607     InstallRequest requestInst;
608     requestInst.setAppId(sm_app_id);
609     requestInst.setPkgId(sm_pkg_id);
610
611     Api::install(requestInst);
612
613     /* Check records in the security-manager database */
614     check_app_after_install(sm_app_id, sm_pkg_id);
615
616     InstallRequest requestUninst;
617     requestUninst.setAppId(sm_app_id);
618     requestUninst.setPkgId(sm_pkg_id_wrong);
619
620     Api::uninstall(requestUninst);
621
622     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
623
624 }
625
626 RUNNER_TEST(security_manager_02_app_install_uninstall_full)
627 {
628     std::string SM_RW_PATH = genRWPath(2);
629     std::string SM_RO_PATH = genROPath(2);
630     std::string SM_PUBLIC_RO_PATH = genPublicROPath(2);
631
632     const char *const sm_app_id = "sm_test_02_app_id_full";
633     const char *const sm_pkg_id = "sm_test_02_pkg_id_full";
634
635     prepare_app_env(2);
636
637     InstallRequest requestInst;
638     requestInst.setAppId(sm_app_id);
639     requestInst.setPkgId(sm_pkg_id);
640     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
641     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
642     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
643     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
644     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
645
646     Api::install(requestInst);
647
648     /* Check records in the security-manager database */
649     check_app_after_install(sm_app_id, sm_pkg_id,
650                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
651
652     /* TODO: add parameters to this function */
653     check_app_path_after_install(2, sm_pkg_id, false);
654
655     InstallRequest requestUninst;
656     requestUninst.setAppId(sm_app_id);
657
658     Api::uninstall(requestUninst);
659
660     /* Check records in the security-manager database,
661      * all previously allowed privileges should be removed */
662     check_app_after_uninstall(sm_app_id, sm_pkg_id,
663                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
664 }
665
666 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
667 {
668     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_smack";
669     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_smack";
670     const char *const socketLabel = "not_expected_label";
671     std::string expected_label = generateAppLabel(app_id);
672     char *label = nullptr;
673     CStringPtr labelPtr;
674     int result;
675
676     uninstall_app(app_id, pkg_id, true);
677     install_app(app_id, pkg_id);
678
679     struct sockaddr_un sockaddr = {AF_UNIX, SOCK_PATH};
680     //Clean up before creating socket
681     unlink(SOCK_PATH);
682     int sock = socket(AF_UNIX, SOCK_STREAM, 0);
683     RUNNER_ASSERT_ERRNO_MSG(sock >= 0, "socket failed");
684     SockUniquePtr sockPtr(&sock);
685     //Bind socket to address
686     result = bind(sock, (struct sockaddr*) &sockaddr, sizeof(struct sockaddr_un));
687     RUNNER_ASSERT_ERRNO_MSG(result == 0, "bind failed");
688     //Set socket label to something different than expecedLabel
689     result = smack_set_label_for_file(sock, XATTR_NAME_SMACKIPIN, socketLabel);
690     RUNNER_ASSERT_ERRNO_MSG(result == 0,
691         "Can't set socket label. Result: " << result);
692     result = smack_set_label_for_file(sock, XATTR_NAME_SMACKIPOUT, socketLabel);
693     RUNNER_ASSERT_ERRNO_MSG(result == 0,
694         "Can't set socket label. Result: " << result);
695
696     Api::setProcessLabel(app_id);
697
698     result = smack_new_label_from_file(sock, XATTR_NAME_SMACKIPIN, &label);
699     RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
700     labelPtr.reset(label);
701     result = expected_label.compare(label);
702     RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
703         expected_label << " Actual: " << label);
704
705     result = smack_new_label_from_file(sock, XATTR_NAME_SMACKIPOUT, &label);
706     RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
707     labelPtr.reset(label);
708     result = expected_label.compare(label);
709     RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
710         expected_label << " Actual: " << label);
711
712     result = smack_new_label_from_self(&label);
713     RUNNER_ASSERT_MSG(result >= 0,
714             " Error getting current process label");
715     RUNNER_ASSERT_MSG(label != nullptr,
716             " Process label is not set");
717     labelPtr.reset(label);
718
719     result = expected_label.compare(label);
720     RUNNER_ASSERT_MSG(result == 0,
721             " Process label is incorrect. Expected: \"" << expected_label <<
722             "\" Actual: \"" << label << "\"");
723
724     uninstall_app(app_id, pkg_id, true);
725 }
726
727 RUNNER_CHILD_TEST_NOSMACK(security_manager_03_set_label_from_appid_nosmack)
728 {
729     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_nosmack";
730     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_nosmack";
731
732     uninstall_app(app_id, pkg_id, true);
733     install_app(app_id, pkg_id);
734
735     Api::setProcessLabel(app_id);
736
737     uninstall_app(app_id, pkg_id, true);
738 }
739
740 static void prepare_request(InstallRequest &request,
741               const char *const app_id,
742               const char *const pkg_id,
743               app_install_path_type pathType,
744               const char *const path,
745               uid_t uid)
746 {
747     request.setAppId(app_id);
748     request.setPkgId(pkg_id);
749     request.addPath(path, pathType);
750
751     if (uid != 0)
752         request.setUid(uid);
753 }
754
755 static uid_t getGlobalUserId(void)
756 {
757     return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
758 }
759
760 static const std::string appDirPath(const TemporaryTestUser &user,
761         const std::string &appId, const std::string &pkgId)
762 {
763     struct tzplatform_context *tzCtxPtr = nullptr;
764
765     RUNNER_ASSERT(0 == tzplatform_context_create(&tzCtxPtr));
766     TzPlatformContextPtr tzCtxPtrSmart(tzCtxPtr);
767
768     RUNNER_ASSERT_MSG(0 == tzplatform_context_set_user(tzCtxPtr, user.getUid()),
769                       "Unable to set user <" << user.getUserName() << "> for tzplatform context");
770
771     const char *appDir = tzplatform_context_getenv(tzCtxPtr,
772                                 getGlobalUserId() == user.getUid() ? TZ_SYS_RW_APP : TZ_USER_APP);
773     RUNNER_ASSERT_MSG(nullptr != appDir,
774                       "tzplatform_context_getenv failed"
775                           << "for getting sys rw app of user <" << user.getUserName() << ">");
776
777     return std::string(appDir) + "/" + pkgId + "/" + appId;
778 }
779
780 static const std::string nonAppDirPath(const TemporaryTestUser &user)
781 {
782     return TMP_DIR + "/" + user.getUserName();
783 }
784
785 static const std::string uidToStr(const uid_t uid)
786 {
787     return std::to_string(static_cast<unsigned int>(uid));
788 }
789
790 static void install_and_check(const char *const sm_app_id,
791                               const char *const sm_pkg_id,
792                               const TemporaryTestUser& user,
793                               const std::string &appDir,
794                               bool requestUid)
795 {
796     InstallRequest requestPrivate;
797
798     //install app for non-root user
799     //should fail (users may only register folders inside their home)
800     prepare_request(requestPrivate, sm_app_id, sm_pkg_id,
801                     SECURITY_MANAGER_PATH_RW, SM_RW_PATH,
802                     requestUid ? user.getUid() : 0);
803
804     Api::install(requestPrivate, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
805
806     InstallRequest requestPrivateUser;
807
808     //install app for non-root user
809     //should succeed - this time i register folder inside user's home dir
810     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
811                     SECURITY_MANAGER_PATH_RW, appDir.c_str(),
812                     requestUid ? user.getUid() : 0);
813
814     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
815         requestPrivateUser.addPrivilege(privilege.c_str());
816
817     Api::install(requestPrivateUser);
818
819     check_app_permissions(sm_app_id, sm_pkg_id,
820                           uidToStr(user.getUid()).c_str(),
821                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
822 }
823
824 static void createTestDir(const std::string &dir)
825 {
826     mode_t dirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
827     mode_t execFileMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
828     mode_t normalFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
829
830     mktreeSafe(dir, dirMode);
831     creatSafe(dir + "/" + EXEC_FILE, execFileMode);
832     creatSafe(dir + "/" + NORMAL_FILE, normalFileMode);
833     symlinkSafe(dir + "/" + EXEC_FILE, dir + "/" + LINK_PREFIX + EXEC_FILE);
834     symlinkSafe(dir + "/" + NORMAL_FILE, dir + "/" + LINK_PREFIX + NORMAL_FILE);
835 }
836
837 static void createInnerAppDir(const std::string &dir, const std::string &nonAppDir)
838 {
839     createTestDir(dir);
840
841     symlinkSafe(nonAppDir, dir + "/" + LINK_PREFIX + "non_app_dir");
842     symlinkSafe(nonAppDir + "/" + EXEC_FILE,
843                 dir + "/" + LINK_PREFIX + "non_app_" + EXEC_FILE);
844     symlinkSafe(nonAppDir + "/" + NORMAL_FILE,
845                 dir + "/" + LINK_PREFIX + "non_app_" + NORMAL_FILE);
846 }
847
848 static void generateAppDir(const TemporaryTestUser &user,
849        const std::string &appId, const std::string &pkgId)
850 {
851     const std::string dir = appDirPath(user, appId, pkgId);
852     const std::string nonAppDir = nonAppDirPath(user);
853
854     createInnerAppDir(dir, nonAppDir);
855     createInnerAppDir(dir + "/.inner_dir", nonAppDir);
856     createInnerAppDir(dir + "/inner_dir", nonAppDir);
857 }
858
859 static void generateNonAppDir(const TemporaryTestUser &user)
860 {
861     const std::string dir = nonAppDirPath(user);
862
863     createTestDir(dir);
864     createTestDir(dir + "/.inner_dir");
865     createTestDir(dir + "/inner_dir");
866 }
867
868 static void createTestDirs(const TemporaryTestUser &user,
869        const std::string &appId, const std::string &pkgId)
870 {
871     generateAppDir(user, appId, pkgId);
872     generateNonAppDir(user);
873 }
874
875 static void removeTestDirs(const TemporaryTestUser &user,
876        const std::string &appId, const std::string &pkgId)
877 {
878     removeDir(appDirPath(user, appId, pkgId));
879     removeDir(nonAppDirPath(user));
880 }
881
882 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
883 {
884     int result;
885     const char *const sm_app_id = "sm_test_04a_app_id_uid";
886     const char *const sm_pkg_id = "sm_test_04a_pkg_id_uid";
887     const std::string new_user_name = "sm_test_04a_user_name";
888
889     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
890     testUser.create();
891
892     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
893     createTestDirs(testUser, sm_app_id, sm_pkg_id);
894
895     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
896
897     //switch user to non-root
898     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
899     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
900
901     install_and_check(sm_app_id, sm_pkg_id, testUser, userAppDirPath, false);
902
903     //uninstall app as non-root user
904     InstallRequest request;
905     request.setAppId(sm_app_id);
906
907     Api::uninstall(request);
908
909     check_app_permissions(sm_app_id, sm_pkg_id,
910                           uidToStr(testUser.getUid()).c_str(),
911                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
912 }
913
914 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user)
915 {
916     int result;
917     const char *const sm_app_id = "sm_test_04b_app_id_uid";
918     const char *const sm_pkg_id = "sm_test_04b_pkg_id_uid";
919     const std::string new_user_name = "sm_test_04b_user_name";
920
921     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
922     testUser.create();
923
924     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
925     createTestDirs(testUser, sm_app_id, sm_pkg_id);
926
927     install_and_check(sm_app_id, sm_pkg_id, testUser, appDirPath(testUser, sm_app_id, sm_pkg_id), true);
928
929     //switch user to non-root - root may not uninstall apps for specified users
930     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
931     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
932
933     //uninstall app as non-root user
934     InstallRequest request;
935     request.setAppId(sm_app_id);
936
937     Api::uninstall(request);
938
939     check_app_permissions(sm_app_id, sm_pkg_id,
940                           uidToStr(testUser.getUid()).c_str(),
941                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
942 }
943
944
945 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
946 {
947     int result;
948     CapsSetsUniquePtr caps, caps_empty(cap_init());
949
950     caps.reset(cap_from_text("all=eip"));
951     RUNNER_ASSERT_MSG(caps, "can't convert capabilities from text");
952     result = cap_set_proc(caps.get());
953     RUNNER_ASSERT_MSG(result == 0,
954         "can't set capabilities. Result: " << result);
955
956     Api::dropProcessPrivileges();
957
958     caps.reset(cap_get_proc());
959     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
960
961     result = cap_compare(caps.get(), caps_empty.get());
962     RUNNER_ASSERT_MSG(result == 0,
963         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
964 }
965
966 RUNNER_CHILD_TEST(security_manager_06_install_app_offline)
967 {
968     const char *const app_id = "sm_test_06_app_id_install_app_offline";
969     const char *const pkg_id = "sm_test_06_pkg_id_install_app_offline";
970
971     // Uninstall app on-line, off-line mode doesn't support it
972     uninstall_app(app_id, pkg_id, true);
973
974     ServiceManager("security-manager.service").stopService();
975
976     ServiceManager serviceManager("security-manager.socket");
977     serviceManager.stopService();
978
979     install_app(app_id, pkg_id);
980
981     serviceManager.startService();
982
983     uninstall_app(app_id, pkg_id, true);
984 }
985
986 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
987 {
988     const char *const sm_app_id = "sm_test_07_app_id_user";
989     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
990     const std::string new_user_name = "sm_test_07_user_name";
991     std::string uid_string;
992     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
993     test_user.create();
994     test_user.getUidString(uid_string);
995
996     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
997     createTestDirs(test_user, sm_app_id, sm_pkg_id);
998
999     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
1000
1001     check_app_after_install(sm_app_id, sm_pkg_id);
1002
1003     test_user.remove();
1004
1005     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1006
1007     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
1008 }
1009
1010 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
1011 {
1012     UserRequest addUserRequest;
1013
1014     const char *const sm_app_id = "sm_test_08_app_id_user";
1015     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
1016     const std::string new_user_name = "sm_test_08_user_name";
1017     std::string uid_string;
1018
1019     // gumd user add
1020     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
1021     test_user.create();
1022     test_user.getUidString(uid_string);
1023
1024     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
1025     createTestDirs(test_user, sm_app_id, sm_pkg_id);
1026
1027     addUserRequest.setUid(test_user.getUid());
1028     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
1029
1030     //sm user add
1031     Api::addUser(addUserRequest);
1032
1033     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
1034
1035     check_app_after_install(sm_app_id, sm_pkg_id);
1036
1037     test_user.remove();
1038
1039     UserRequest deleteUserRequest;
1040     deleteUserRequest.setUid(test_user.getUid());
1041
1042     Api::deleteUser(deleteUserRequest);
1043
1044     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1045
1046     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
1047 }
1048
1049 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
1050 {
1051     const char *const app_id = "security_manager_09_add_user_offline_app";
1052     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
1053     const std::string new_user_name("sm_test_09_user_name");
1054
1055     ServiceManager("security-manager.service").stopService();
1056
1057     ServiceManager serviceManager("security-manager.socket");
1058     serviceManager.stopService();
1059
1060     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, true);
1061     test_user.create();
1062
1063     removeTestDirs(test_user, app_id, pkg_id);
1064     createTestDirs(test_user, app_id, pkg_id);
1065
1066     install_app(app_id, pkg_id, test_user.getUid());
1067
1068     check_app_after_install(app_id, pkg_id);
1069
1070     serviceManager.startService();
1071
1072     test_user.remove();
1073
1074     check_app_after_uninstall(app_id, pkg_id, true);
1075 }
1076
1077 RUNNER_MULTIPROCESS_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
1078 {
1079     //TEST DATA
1080     const std::string username("sm_test_10_user_name");
1081     unsigned int privileges_count = 0;
1082
1083     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1084     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1085
1086     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1087         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1088             MANY_APPS.at(i), std::set<std::string>(
1089                 MANY_APPS_PRIVILEGES.at(i).begin(),
1090                 MANY_APPS_PRIVILEGES.at(i).end())));
1091         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1092     };
1093
1094     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1095         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1096     ++privileges_count;
1097     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1098     //TEST DATA END
1099
1100     sem_t *mutex;
1101     errno = 0;
1102     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1103     errno = 0;
1104     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1105     pid_t pid = fork();
1106
1107     if (pid != 0) { //parent process
1108         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
1109         tmpUser.create();
1110
1111         for(const auto &user : users2AppsMap) {
1112
1113             for(const auto &app : user.second) {
1114                 InstallRequest requestInst;
1115                 requestInst.setAppId(app.first.c_str());
1116                 try {
1117                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1118                 } catch (const std::out_of_range &e) {
1119                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1120                 };
1121                 requestInst.setUid(tmpUser.getUid());
1122
1123                 for (const auto &privilege : app.second) {
1124                     requestInst.addPrivilege(privilege.c_str());
1125                 };
1126
1127                 Api::install(requestInst);
1128             };
1129
1130             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1131         };
1132         //Start child process
1133         errno = 0;
1134         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1135
1136         int status;
1137         wait(&status);
1138
1139         tmpUser.remove();
1140     };
1141
1142     if (pid == 0) { //child process
1143         errno = 0;
1144         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
1145         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
1146
1147         struct passwd *pw = getUserStruct(username);
1148         register_current_process_as_privilege_manager(pw->pw_uid);
1149         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1150         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1151
1152         std::vector<PolicyEntry> policyEntries;
1153         PolicyEntry filter;
1154         Api::getPolicy(filter, policyEntries);
1155
1156         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1157         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1158
1159         for (const auto &policyEntry : policyEntries) {
1160             std::string user = policyEntry.getUser();
1161             std::string app = policyEntry.getAppId();
1162             std::string privilege = policyEntry.getPrivilege();
1163
1164             try {
1165                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1166                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1167                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1168                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1169             } catch (const std::out_of_range &e) {
1170                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1171             } catch (const std::invalid_argument& e) {
1172                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1173             };
1174         };
1175         exit(0);
1176     };
1177 }
1178
1179 RUNNER_MULTIPROCESS_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1180 {
1181     //TEST DATA
1182     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1183     unsigned int privileges_count = 0;
1184
1185     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1186     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1187
1188     for (const auto &username : usernames) {
1189         //Only entries for one of the users will be listed
1190         privileges_count = 0;
1191
1192         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1193             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1194                 MANY_APPS.at(i), std::set<std::string>(
1195                     MANY_APPS_PRIVILEGES.at(i).begin(),
1196                     MANY_APPS_PRIVILEGES.at(i).end())));
1197             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1198         };
1199
1200         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1201     };
1202
1203     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1204         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1205
1206     ++privileges_count;
1207     //TEST DATA END
1208
1209     sem_t *mutex;
1210     errno = 0;
1211     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1212     errno = 0;
1213     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1214     pid_t pid = fork();
1215
1216     if (pid != 0) { //parent process
1217         std::vector<TemporaryTestUser> users = {
1218             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1219             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1220             };
1221
1222         users.at(0).create();
1223         users.at(1).create();
1224
1225         //Install apps for both users
1226         for(const auto &user : users) {
1227             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1228                 InstallRequest requestInst;
1229                 requestInst.setAppId(app.first.c_str());
1230                 try {
1231                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1232                 } catch (const std::out_of_range &e) {
1233                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1234                 };
1235                 requestInst.setUid(user.getUid());
1236
1237                 for (const auto &privilege : app.second) {
1238                     requestInst.addPrivilege(privilege.c_str());
1239                 };
1240
1241                 Api::install(requestInst);
1242             };
1243
1244             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1245         };
1246         //Start child
1247         errno = 0;
1248         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1249
1250         int status;
1251         wait(&status);
1252
1253         for(auto &user : users) {
1254             user.remove();
1255         };
1256     };
1257
1258     if (pid == 0) {
1259         errno = 0;
1260         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1261         struct passwd *pw = getUserStruct(usernames.at(0));
1262         register_current_process_as_privilege_manager(pw->pw_uid);
1263
1264         //change uid to normal user
1265         errno = 0;
1266         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1267         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1268
1269         std::vector<PolicyEntry> policyEntries;
1270         PolicyEntry filter;
1271
1272         //this call should only return privileges belonging to the current uid
1273         Api::getPolicy(filter, policyEntries);
1274
1275         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1276         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1277
1278         for (const auto &policyEntry : policyEntries) {
1279             std::string user = policyEntry.getUser();
1280             std::string app = policyEntry.getAppId();
1281             std::string privilege = policyEntry.getPrivilege();
1282
1283             try {
1284                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1285                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1286                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1287                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1288             } catch (const std::out_of_range &e) {
1289                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1290             } catch (const std::invalid_argument& e) {
1291                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1292             };
1293         };
1294         exit(0);
1295     };
1296 }
1297
1298 RUNNER_MULTIPROCESS_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1299 {
1300     //TEST DATA
1301     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1302     unsigned int privileges_count = 0;
1303
1304     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1305     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1306
1307     for (const auto &username : usernames) {
1308
1309         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1310             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1311                 MANY_APPS.at(i), std::set<std::string>(
1312                     MANY_APPS_PRIVILEGES.at(i).begin(),
1313                     MANY_APPS_PRIVILEGES.at(i).end())));
1314             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1315         };
1316
1317         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1318     };
1319
1320     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1321         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1322
1323     privileges_count += 2;
1324     //TEST DATA END
1325
1326     sem_t *mutex;
1327     errno = 0;
1328     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1329     errno = 0;
1330     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1331     pid_t pid = fork();
1332
1333     if (pid != 0) { //parent process
1334         std::vector<TemporaryTestUser> users = {
1335             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1336             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1337             };
1338
1339         users.at(0).create();
1340         users.at(1).create();
1341         //Install apps for both users
1342         for(const auto &user : users) {
1343             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1344                 InstallRequest requestInst;
1345                 requestInst.setAppId(app.first.c_str());
1346                 try {
1347                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1348                 } catch (const std::out_of_range &e) {
1349                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1350                 };
1351                 requestInst.setUid(user.getUid());
1352
1353                 for (const auto &privilege : app.second) {
1354                     requestInst.addPrivilege(privilege.c_str());
1355                 };
1356
1357                 Api::install(requestInst);
1358             };
1359
1360             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1361         };
1362
1363         //Start child
1364         errno = 0;
1365         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1366
1367         //Wait for child to finish
1368         int status;
1369         wait(&status);
1370
1371         for(auto &user : users) {
1372             user.remove();
1373         };
1374     };
1375
1376     if (pid == 0) { //child process
1377         errno = 0;
1378         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child failed, errno: " << errno);
1379
1380         struct passwd *pw = getUserStruct(usernames.at(1));
1381         register_current_process_as_privilege_manager(pw->pw_uid, true);
1382
1383         //change uid to normal user
1384         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1385         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1386
1387         std::vector<PolicyEntry> policyEntries;
1388         PolicyEntry filter;
1389         //this call should succeed as the calling user is privileged
1390         Api::getPolicy(filter, policyEntries);
1391
1392         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1393         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1394
1395         for (const auto &policyEntry : policyEntries) {
1396             std::string user = policyEntry.getUser();
1397             std::string app = policyEntry.getAppId();
1398             std::string privilege = policyEntry.getPrivilege();
1399
1400             try {
1401                 struct passwd *pw_current = getUserStruct(static_cast<uid_t>(std::stoul(user)));
1402                 std::set<std::string>::iterator tmp = users2AppsMap.at(pw_current->pw_name).at(app).find(privilege);
1403                 if (tmp == users2AppsMap.at(pw_current->pw_name).at(app).end())
1404                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1405             } catch (const std::out_of_range &e) {
1406                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected user or app: " << policyEntry << ". Exception: " << e.what());
1407             } catch (const std::invalid_argument& e) {
1408                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1409             };
1410         };
1411
1412         exit(0);
1413     };
1414 }
1415
1416 RUNNER_MULTIPROCESS_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1417 {
1418     //TEST DATA
1419     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1420
1421     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1422     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1423
1424     for (const auto &username : usernames) {
1425
1426         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1427             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1428                 MANY_APPS.at(i), std::set<std::string>(
1429                     MANY_APPS_PRIVILEGES.at(i).begin(),
1430                     MANY_APPS_PRIVILEGES.at(i).end())));
1431         };
1432
1433         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1434     };
1435
1436     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1437         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1438
1439     //TEST DATA END
1440
1441     pid_t pid[2];
1442     sem_t *mutex[2];
1443     errno = 0;
1444     RUNNER_ASSERT_MSG(((mutex[0] = sem_open("mutex_1", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #1, errno: " << errno);
1445     errno = 0;
1446     RUNNER_ASSERT_MSG(((mutex[1] = sem_open("mutex_2", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex #2, errno: " << errno);
1447     errno = 0;
1448     RUNNER_ASSERT_MSG(sem_init(mutex[0], 1, 0) == 0, "failed to setup mutex #1, errno: " << errno);
1449     errno = 0;
1450     RUNNER_ASSERT_MSG(sem_init(mutex[1], 1, 0) == 0, "failed to setup mutex #2, errno: " << errno);
1451     std::vector<PolicyEntry> policyEntries;
1452
1453     pid[0] = fork();
1454
1455     if(pid[0] == 0) { //child #1 process
1456         RUNNER_ASSERT_MSG(sem_wait(mutex[0]) == 0, "sem_wait in child #1 failed, errno: " << errno);
1457         struct passwd *pw = getUserStruct(usernames.at(0));
1458         register_current_process_as_privilege_manager(pw->pw_uid);
1459
1460         //change uid to normal user
1461         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1462         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1463
1464         PolicyEntry filter;
1465         PolicyRequest policyRequest;
1466         //this call should succeed as the calling user is privileged
1467         Api::getPolicyForSelf(filter, policyEntries);
1468
1469         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1470
1471         PolicyEntry policyEntry(
1472                 MANY_APPS[0],
1473                 std::to_string(pw->pw_uid),
1474                 "http://tizen.org/privilege/internet"
1475                 );
1476         policyEntry.setLevel("Deny");
1477
1478         policyRequest.addEntry(policyEntry);
1479         policyEntry = PolicyEntry(
1480                 MANY_APPS[1],
1481                 std::to_string(pw->pw_uid),
1482                 "http://tizen.org/privilege/location"
1483                 );
1484         policyEntry.setLevel("Deny");
1485
1486         policyRequest.addEntry(policyEntry);
1487         Api::sendPolicy(policyRequest);
1488         Api::getPolicyForSelf(filter, policyEntries);
1489
1490         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1491         exit(0);
1492     };
1493
1494     if (pid[0] != 0) {//parent process
1495         pid[1] = fork();
1496
1497         if (pid[1] == 0) { //child #2 process
1498             errno = 0;
1499             RUNNER_ASSERT_MSG(sem_wait(mutex[1]) == 0, "sem_wait in child #2 failed, errno: " << errno);
1500             struct passwd *pw_target = getUserStruct(usernames.at(0));
1501             struct passwd *pw = getUserStruct(usernames.at(1));
1502             register_current_process_as_privilege_manager(pw->pw_uid);
1503
1504             //change uid to normal user
1505             int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1506             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1507
1508             PolicyEntry filter = PolicyEntry(
1509                         SECURITY_MANAGER_ANY,
1510                         std::to_string(pw_target->pw_uid),
1511                         SECURITY_MANAGER_ANY
1512                         );
1513
1514             //U2 requests contents of U1 privacy manager - should fail
1515             Api::getPolicyForSelf(filter, policyEntries);
1516             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1517
1518             filter = PolicyEntry(
1519                         SECURITY_MANAGER_ANY,
1520                         SECURITY_MANAGER_ANY,
1521                         SECURITY_MANAGER_ANY
1522                         );
1523
1524             policyEntries.clear();
1525
1526             //U2 requests contents of ADMIN bucket - should fail
1527             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1528             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1529             exit(0);
1530         };
1531
1532         if (pid[1] != 0) { //parent
1533
1534             std::vector<TemporaryTestUser> users = {
1535                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1536                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1537                 };
1538
1539             users.at(0).create();
1540             users.at(1).create();
1541
1542             //Install apps for both users
1543             for(const auto &user : users2AppsMap) {
1544
1545                 for(const auto &app : user.second) {
1546                     InstallRequest requestInst;
1547                     requestInst.setAppId(app.first.c_str());
1548                     try {
1549                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1550                     } catch (const std::out_of_range &e) {
1551                         RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1552                     };
1553                     requestInst.setUid(users.at(0).getUid());
1554
1555                     for (const auto &privilege : app.second) {
1556                         requestInst.addPrivilege(privilege.c_str());
1557                     };
1558
1559                     Api::install(requestInst);
1560                 };
1561
1562                 //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1563             };
1564
1565             int status;
1566             //Start child #1
1567             errno = 0;
1568             RUNNER_ASSERT_MSG(sem_post(mutex[0]) ==  0, "Error while opening mutex #1, errno: " << errno);
1569
1570             //Wait until child #1 finishes
1571             pid_t ret = wait(&status);
1572             RUNNER_ASSERT_MSG((ret != -1) && WIFEXITED(status), "Updating privileges failed");
1573
1574             //Start child #2
1575             errno = 0;
1576             RUNNER_ASSERT_MSG(sem_post(mutex[1]) ==  0, "Error while opening mutex #2, errno: " << errno);
1577             //Wait until child #2 finishes
1578             ret = wait(&status);
1579             RUNNER_ASSERT_MSG((ret =-1) && WIFEXITED(status), "Listing privileges failed");
1580
1581             for(auto &user : users) {
1582                 user.remove();
1583             };
1584
1585             sem_close(mutex[0]);
1586             sem_close(mutex[1]);
1587         };
1588     };
1589 }
1590
1591 RUNNER_MULTIPROCESS_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1592 {
1593     //TEST DATA
1594     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1595     unsigned int privileges_count = 0;
1596
1597     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1598     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1599
1600     for (const auto &username : usernames) {
1601
1602         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1603             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1604                 MANY_APPS.at(i), std::set<std::string>(
1605                     MANY_APPS_PRIVILEGES.at(i).begin(),
1606                     MANY_APPS_PRIVILEGES.at(i).end())));
1607             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1608         };
1609
1610         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1611     };
1612
1613     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1614         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1615
1616     privileges_count += 2;
1617     //TEST DATA END
1618     sem_t *mutex;
1619     errno = 0;
1620     RUNNER_ASSERT_MSG(((mutex = sem_open("mutex", O_CREAT, 0644, 1)) != SEM_FAILED), "Failure creating mutex, errno: " << errno);
1621     errno = 0;
1622     RUNNER_ASSERT_MSG(sem_init(mutex, 1, 0) == 0, "failed to setup mutex, errno: " << errno);
1623
1624     pid_t pid = fork();
1625     if (pid != 0) {
1626         std::vector<TemporaryTestUser> users = {
1627             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1628             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1629             };
1630
1631         users.at(0).create();
1632         users.at(1).create();
1633
1634         //Install apps for both users
1635         for(const auto &user : users) {
1636
1637             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1638                 InstallRequest requestInst;
1639                 requestInst.setAppId(app.first.c_str());
1640                 try {
1641                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1642                 } catch (const std::out_of_range &e) {
1643                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1644                 };
1645                 requestInst.setUid(user.getUid());
1646
1647                 for (const auto &privilege : app.second) {
1648                     requestInst.addPrivilege(privilege.c_str());
1649                 };
1650
1651                 Api::install(requestInst);
1652             };
1653         };
1654         //Start child process
1655         errno = 0;
1656         RUNNER_ASSERT_MSG(sem_post(mutex) ==  0, "Error while opening mutex, errno: " << errno);
1657         int status;
1658         //Wait for child process to finish
1659         wait(&status);
1660
1661         //switch back to root
1662         for(auto &user : users) {
1663             user.remove();
1664         };
1665
1666         sem_close(mutex);
1667     }
1668
1669     if (pid == 0) { //child process
1670         errno = 0;
1671         RUNNER_ASSERT_MSG(sem_wait(mutex) == 0, "sem_wait in child process failed, errno: " << errno);
1672
1673         struct passwd *pw = getUserStruct(usernames.at(0));
1674         register_current_process_as_privilege_manager(pw->pw_uid, true);
1675
1676         //change uid to normal user
1677         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1678         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1679
1680         PolicyRequest *policyRequest = new PolicyRequest();
1681         PolicyEntry filter;
1682         std::vector<PolicyEntry> policyEntries;
1683         //this call should succeed as the calling user is privileged
1684         Api::getPolicyForSelf(filter, policyEntries);
1685
1686         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty");
1687
1688         PolicyEntry policyEntry(
1689                 SECURITY_MANAGER_ANY,
1690                 SECURITY_MANAGER_ANY,
1691                 "http://tizen.org/privilege/internet"
1692                 );
1693         policyEntry.setMaxLevel("Deny");
1694
1695         policyRequest->addEntry(policyEntry);
1696         policyEntry = PolicyEntry(
1697                 SECURITY_MANAGER_ANY,
1698                 SECURITY_MANAGER_ANY,
1699                 "http://tizen.org/privilege/location"
1700                 );
1701         policyEntry.setMaxLevel("Deny");
1702
1703         policyRequest->addEntry(policyEntry);
1704         Api::sendPolicy(*policyRequest);
1705         Api::getPolicyForAdmin(filter, policyEntries);
1706
1707         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
1708
1709         delete policyRequest;
1710         policyRequest = new PolicyRequest();
1711         policyEntry = PolicyEntry(
1712                 SECURITY_MANAGER_ANY,
1713                 SECURITY_MANAGER_ANY,
1714                 "http://tizen.org/privilege/internet"
1715                 );
1716         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1717         policyRequest->addEntry(policyEntry);
1718
1719         policyEntry = PolicyEntry(
1720                 SECURITY_MANAGER_ANY,
1721                 SECURITY_MANAGER_ANY,
1722                 "http://tizen.org/privilege/location"
1723                 );
1724         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1725
1726         policyRequest->addEntry(policyEntry);
1727         Api::sendPolicy(*policyRequest);
1728
1729         policyEntries.clear();
1730         Api::getPolicyForAdmin(filter, policyEntries);
1731         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1732
1733         delete policyRequest;
1734
1735         exit(0);
1736     };
1737
1738 }
1739
1740 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1741 {
1742     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
1743     const char *const update_app_id = "security_manager_15_update_app_id";
1744     const char *const update_privilege = "http://tizen.org/privilege/led";
1745     const char *const check_start_bucket = "ADMIN";
1746     const std::string username("sm_test_15_username");
1747     PolicyRequest addPolicyRequest;
1748     CynaraTestAdmin::Admin admin;
1749
1750     struct message {
1751         uid_t uid;
1752         gid_t gid;
1753     } msg;
1754
1755     int pipefd[2];
1756     pid_t pid;
1757     int result = 0;
1758
1759     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1760
1761     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1762     user.create();
1763
1764     pid = fork();
1765     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1766     if (pid != 0)//parent process
1767     {
1768         FdUniquePtr pipeptr(pipefd+1);
1769         close(pipefd[0]);
1770
1771         register_current_process_as_privilege_manager(user.getUid(), true);
1772
1773         //send info to child
1774         msg.uid = user.getUid();
1775         msg.gid = user.getGid();
1776
1777         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1778         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1779
1780         //wait for child
1781         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1782
1783         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1784                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1785     }
1786     if(pid == 0)
1787     {
1788         FdUniquePtr pipeptr(pipefd);
1789         close(pipefd[1]);
1790
1791         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1792         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1793
1794         //become admin privacy manager manager
1795         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1796         result = drop_root_privileges(msg.uid, msg.gid);
1797         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1798
1799         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1800         entry.setMaxLevel("Allow");
1801
1802         addPolicyRequest.addEntry(entry);
1803         Api::sendPolicy(addPolicyRequest);
1804         exit(0);
1805     }
1806 }
1807
1808 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1809 {
1810     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
1811     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1812     const char *const update_privilege = "http://tizen.org/privilege/led";
1813     const char *const check_start_bucket = "ADMIN";
1814     const std::string username("sm_test_15_username");
1815     PolicyRequest addPolicyRequest;
1816     CynaraTestAdmin::Admin admin;
1817
1818     struct message {
1819         uid_t uid;
1820         gid_t gid;
1821     } msg;
1822
1823     int pipefd[2];
1824     pid_t pid;
1825     int result = 0;
1826
1827     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1828
1829     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1830     user.create();
1831
1832     pid = fork();
1833     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1834     if (pid != 0)//parent process
1835     {
1836         FdUniquePtr pipeptr(pipefd+1);
1837         close(pipefd[0]);
1838
1839         register_current_process_as_privilege_manager(user.getUid(), true);
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         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_other_app_id).c_str(),
1852                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1853     }
1854     if(pid == 0)
1855     {
1856         FdUniquePtr pipeptr(pipefd);
1857         close(pipefd[1]);
1858
1859         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1860         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1861
1862         //become admin privacy manager manager
1863         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1864         result = drop_root_privileges(msg.uid, msg.gid);
1865         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1866
1867         // use wildcard as appId
1868         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1869         entry.setMaxLevel("Allow");
1870
1871         addPolicyRequest.addEntry(entry);
1872         Api::sendPolicy(addPolicyRequest);
1873         exit(0);
1874     }
1875 }
1876
1877 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1878 {
1879     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
1880     const char *const update_app_id = "security_manager_15_update_app_id";
1881     const char *const update_privilege = "http://tizen.org/privilege/led";
1882     const char *const check_start_bucket = "";
1883     const std::string username("sm_test_15_username");
1884     PolicyRequest addPolicyRequest;
1885     CynaraTestAdmin::Admin admin;
1886
1887     struct message {
1888         uid_t uid;
1889         gid_t gid;
1890     } msg;
1891
1892     int pipefd[2];
1893     pid_t pid;
1894     int result = 0;
1895
1896     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1897
1898     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1899     user.create();
1900
1901     pid = fork();
1902     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1903     if (pid != 0)//parent process
1904     {
1905         FdUniquePtr pipeptr(pipefd+1);
1906         close(pipefd[0]);
1907
1908         register_current_process_as_privilege_manager(user.getUid(), false);
1909
1910         //send info to child
1911         msg.uid = user.getUid();
1912         msg.gid = user.getGid();
1913
1914         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1915         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1916
1917         //wait for child
1918         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1919
1920         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1921                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1922     }
1923     if(pid == 0)
1924     {
1925         FdUniquePtr pipeptr(pipefd);
1926         close(pipefd[1]);
1927
1928         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1929         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1930
1931         //become admin privacy manager manager
1932         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1933         result = drop_root_privileges(msg.uid, msg.gid);
1934         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1935
1936         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1937         entry.setLevel("Allow");
1938
1939         addPolicyRequest.addEntry(entry);
1940         Api::sendPolicy(addPolicyRequest);
1941         exit(0);
1942     }
1943 }
1944
1945 RUNNER_MULTIPROCESS_TEST(security_manager_16_policy_levels_get)
1946 {
1947     const std::string username("sm_test_16_user_cynara_policy");
1948     CynaraTestAdmin::Admin admin;
1949     int pipefd[2];
1950     pid_t pid;
1951     int result = 0;
1952
1953     struct message {
1954         uid_t uid;
1955         gid_t gid;
1956     } msg;
1957
1958     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1959
1960     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1961     user.create();
1962
1963     pid = fork();
1964     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1965     if (pid != 0)//parent process
1966     {
1967         FdUniquePtr pipeptr(pipefd+1);
1968         close(pipefd[0]);
1969
1970         //send info to child
1971         msg.uid = user.getUid();
1972         msg.gid = user.getGid();
1973
1974         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1975         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1976
1977         //wait for child
1978         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1979     }
1980     if(pid == 0)
1981     {
1982         int ret;
1983         char** levels;
1984         std::string allow_policy, deny_policy;
1985         size_t count;
1986         FdUniquePtr pipeptr(pipefd);
1987         close(pipefd[1]);
1988
1989         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1990         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1991
1992         //become admin privacy manager manager
1993         result = drop_root_privileges(msg.uid, msg.gid);
1994         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1995
1996         // without plugins there should only be 2 policies - Allow and Deny
1997         ret = security_manager_policy_levels_get(&levels, &count);
1998
1999         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
2000                 "Invlid return code: " << ret);
2001
2002         RUNNER_ASSERT_MSG(count == 2, "Invalid number of policy levels. Should be 2, instead there is: " << static_cast<int>(count));
2003
2004         deny_policy = std::string(levels[0]);
2005         allow_policy = std::string(levels[count-1]);
2006
2007         // first should always be Deny
2008         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
2009                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
2010
2011         // last should always be Allow
2012         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
2013                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
2014
2015         security_manager_policy_levels_free(levels, count);
2016         exit(0);
2017     }
2018 }
2019
2020 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
2021 {
2022     const char *const update_app_id = "security_manager_17_update_app_id";
2023     const char *const update_privilege = "http://tizen.org/privilege/led";
2024     const char *const check_start_bucket = "";
2025     const std::string username("sm_test_17_username");
2026     PolicyRequest addPolicyRequest;
2027     CynaraTestAdmin::Admin admin;
2028
2029     struct message {
2030         uid_t uid;
2031         gid_t gid;
2032     } msg;
2033
2034     int pipefd[2];
2035     int pipefd2[2];
2036     pid_t pid;
2037     int result = 0;
2038
2039     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2040     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
2041
2042     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2043     user.create();
2044
2045     pid = fork();
2046     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2047     if (pid != 0)//parent process
2048     {
2049         FdUniquePtr pipeptr(pipefd+1);
2050         close(pipefd[0]);
2051
2052         register_current_process_as_privilege_manager(user.getUid(), false);
2053
2054         //send info to child
2055         msg.uid = user.getUid();
2056         msg.gid = user.getGid();
2057
2058         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2059         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2060
2061         //wait for child
2062         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2063
2064         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2065                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
2066
2067         pid = fork();
2068         if (pid != 0)//parent process
2069         {
2070             FdUniquePtr pipeptr(pipefd2+1);
2071             close(pipefd2[0]);
2072
2073             //send info to child
2074             msg.uid = user.getUid();
2075             msg.gid = user.getGid();
2076
2077             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
2078             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2079
2080             //wait for child
2081             RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2082
2083             //wait for child
2084             waitpid(-1, &result, 0);
2085
2086             admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2087                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
2088         }
2089         if(pid == 0)
2090         {
2091             FdUniquePtr pipeptr(pipefd2);
2092             close(pipefd2[1]);
2093
2094             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
2095             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2096
2097             //become admin privacy manager manager
2098             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2099             result = drop_root_privileges(msg.uid, msg.gid);
2100             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2101
2102             // delete this entry
2103             PolicyRequest deletePolicyRequest;
2104             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2105             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
2106
2107             deletePolicyRequest.addEntry(deleteEntry);
2108             Api::sendPolicy(deletePolicyRequest);
2109             exit(0);
2110         }
2111     }
2112     if(pid == 0)
2113     {
2114         FdUniquePtr pipeptr(pipefd);
2115         close(pipefd[1]);
2116
2117         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2118         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2119
2120         //become admin privacy manager manager
2121         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2122         result = drop_root_privileges(msg.uid, msg.gid);
2123         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2124
2125         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2126         entry.setLevel("Allow");
2127
2128         addPolicyRequest.addEntry(entry);
2129         Api::sendPolicy(addPolicyRequest);
2130         exit(0);
2131     }
2132 }
2133
2134 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
2135 {
2136     const std::string username("sm_test_17_user_name");
2137
2138     struct message {
2139         uid_t uid;
2140         gid_t gid;
2141         unsigned int privileges_count;
2142     } msg;
2143
2144     int pipefd[2];
2145     pid_t pid;
2146     int result = 0;
2147
2148     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2149
2150     pid = fork();
2151     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2152     if (pid != 0)//parent process
2153     {
2154         FdUniquePtr pipeptr(pipefd+1);
2155         close(pipefd[0]);
2156
2157         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2158         user.create();
2159
2160         unsigned int privileges_count = 0;
2161
2162         register_current_process_as_privilege_manager(user.getUid(), false);
2163         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2164         ++privileges_count;
2165
2166         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2167             InstallRequest requestInst;
2168             requestInst.setAppId(MANY_APPS[i].c_str());
2169             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).package.c_str());
2170             requestInst.setUid(user.getUid());
2171
2172             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2173                 requestInst.addPrivilege(priv.c_str());
2174             };
2175
2176             Api::install(requestInst);
2177             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2178         };
2179
2180         //send info to child
2181         msg.uid = user.getUid();
2182         msg.gid = user.getGid();
2183         msg.privileges_count = privileges_count;
2184
2185         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2186         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2187
2188         //wait for child
2189         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2190     }
2191     if(pid == 0)
2192     {
2193         FdUniquePtr pipeptr(pipefd);
2194         close(pipefd[1]);
2195
2196         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2197         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2198
2199         //become admin privacy manager manager
2200         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2201         result = drop_root_privileges(msg.uid, msg.gid);
2202         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2203
2204         // filter by privilege
2205         std::vector<PolicyEntry> policyEntries;
2206         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2207         Api::getPolicy(filter, policyEntries);
2208
2209         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2210         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2211
2212         // filter by other privilege
2213         policyEntries.clear();
2214         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2215         Api::getPolicy(filter2, policyEntries);
2216
2217         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2218         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2219
2220         // filter by appId
2221         policyEntries.clear();
2222         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2223         Api::getPolicy(filter3, policyEntries);
2224
2225         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2226         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2227     }
2228 }
2229
2230 RUNNER_CHILD_TEST(security_manager_18_user_cynara_policy)
2231 {
2232     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2233     const char *const MAIN_BUCKET = "MAIN";
2234     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2235     const char *const ADMIN_BUCKET = "ADMIN";
2236     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2237     const std::string username("sm_test_10_user_cynara_policy");
2238     CynaraTestAdmin::Admin admin;
2239     std::string uid_string;
2240     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2241     user.create();
2242     user.getUidString(uid_string);
2243
2244     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2245     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2246     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2247
2248     user.remove();
2249     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2250
2251     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2252     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2253     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2254     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2255 }
2256
2257 RUNNER_CHILD_TEST(security_manager_19_security_manager_cmd_install)
2258 {
2259     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2260     int ret;
2261     const int SUCCESS = 0;
2262     const int FAILURE = 256;
2263     const std::string app_id = "security_manager_10_app";
2264     const std::string pkg_id = "security_manager_10_pkg";
2265     const std::string username("sm_test_10_user_name");
2266     std::string uid_string;
2267     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2268     user.create();
2269     user.getUidString(uid_string);
2270     const std::string path1 = appDirPath(user, app_id, pkg_id) + "/p1";
2271     const std::string path2 = appDirPath(user, app_id, pkg_id) + "/p2";
2272     const std::string pkgopt = " --pkg=" + pkg_id;
2273     const std::string appopt = " --app=" + app_id;
2274     const std::string uidopt = " --uid=" + uid_string;
2275
2276     mktreeSafe(path1.c_str(), 0);
2277     mktreeSafe(path2.c_str(), 0);
2278
2279     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2280
2281     struct operation {
2282         std::string command;
2283         int expected_result;
2284     };
2285     std::vector<struct operation> operations = {
2286             {"security-manager-cmd", FAILURE},//no option
2287             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2288             {"security-manager-cmd --help", SUCCESS},
2289             {"security-manager-cmd --install", FAILURE},//no params
2290             {"security-manager-cmd -i", FAILURE},//no params
2291             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2292             {installcmd, SUCCESS},
2293             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2294             {installcmd + " --path " + path1 + " writable", SUCCESS},
2295             {installcmd + " --path " + path1, FAILURE},//no path type
2296             {installcmd + " --path " + path1 + " writable" + " --path " + path2 + " readable", SUCCESS},
2297             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " readable", FAILURE},//wrong path type
2298             {installcmd + " --path " + path1 + " writable" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2299     };
2300
2301     for (auto &op : operations) {
2302         ret = system(op.command.c_str());
2303         RUNNER_ASSERT_MSG(ret == op.expected_result,
2304                 "Unexpected result for command '" << op.command <<"': "
2305                 << ret << " Expected was: "<< op.expected_result);
2306     }
2307 }
2308
2309 RUNNER_CHILD_TEST(security_manager_20_security_manager_cmd_users)
2310 {
2311     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2312     int ret;
2313     const int SUCCESS = 0;
2314     const int FAILURE = 256;
2315     const std::string username("sm_test_11_user_name");
2316     std::string uid_string;
2317     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2318     user.create();
2319     user.getUidString(uid_string);
2320     const std::string uidopt = " --uid=" + uid_string;
2321
2322     struct operation {
2323         std::string command;
2324         int expected_result;
2325     };
2326     std::vector<struct operation> operations = {
2327             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2328             {"security-manager-cmd -m", FAILURE},//no params
2329             {"security-manager-cmd -mr", FAILURE},//no uid
2330             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2331             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2332             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2333             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2334             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2335             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2336             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2337             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2338     };
2339
2340     for (auto &op : operations) {
2341         ret = system(op.command.c_str());
2342         RUNNER_ASSERT_MSG(ret == op.expected_result,
2343                 "Unexpected result for command '" << op.command <<"': "
2344                 << ret << " Expected was: "<< op.expected_result);
2345     }
2346 }
2347
2348 RUNNER_MULTIPROCESS_TEST(security_manager_21_security_manager_admin_deny_user_priv)
2349 {
2350     const int BUFFER_SIZE = 128;
2351     struct message {
2352         uid_t uid;
2353         gid_t gid;
2354         char buf[BUFFER_SIZE];
2355     } msg;
2356
2357     privileges_t admin_required_privs = {
2358             "http://tizen.org/privilege/systemsettings.admin",
2359             "http://tizen.org/privilege/systemsettings"};
2360     privileges_t manifest_privs = {
2361             "http://tizen.org/privilege/internet",
2362             "http://tizen.org/privilege/camera"};
2363     privileges_t real_privs_allow = {"http://tizen.org/privilege/camera"};
2364     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2365
2366     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2367     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2368     const std::string app_id = "sm_test_13_SOME_APP";
2369     const std::string pkg_id = "sm_test_13_SOME_PKG";
2370
2371     int pipefd[2];
2372     pid_t pid;
2373     int result = 0;
2374
2375     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2376     pid = fork();
2377     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2378     if (pid != 0)//parent process
2379     {
2380         std::string childuidstr;
2381         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, true);
2382         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, true);
2383
2384         InstallRequest request,request2;
2385         FdUniquePtr pipeptr(pipefd+1);
2386         close(pipefd[0]);
2387
2388         admin.create();
2389         child.create();
2390         child.getUidString(childuidstr);
2391
2392         //install privacy manager for admin
2393         request.setAppId(pirivman_id.c_str());
2394         request.setPkgId(pirivman_pkg_id.c_str());
2395         request.setUid(admin.getUid());
2396         for (auto &priv: admin_required_privs)
2397             request.addPrivilege(priv.c_str());
2398         Api::install(request);
2399
2400         //install app for child that has internet privilege
2401         request2.setAppId(app_id.c_str());
2402         request2.setPkgId(pkg_id.c_str());
2403         request2.setUid(child.getUid());
2404         for (auto &priv: manifest_privs)
2405             request2.addPrivilege(priv.c_str());
2406         Api::install(request2);
2407
2408         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2409                               manifest_privs, SM_NO_PRIVILEGES);
2410
2411         //send info to child
2412         msg.uid = admin.getUid();
2413         msg.gid = admin.getGid();
2414         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2415
2416         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2417         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2418
2419         //wait for child
2420         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2421
2422         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2423                               real_privs_allow, real_privs_deny);
2424     }
2425     if (pid == 0)//child
2426     {
2427         FdUniquePtr pipeptr(pipefd);
2428         close(pipefd[1]);
2429
2430         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2431         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2432
2433         //become admin privacy manager manager
2434         Api::setProcessLabel(pirivman_id.c_str());
2435         result = drop_root_privileges(msg.uid, msg.gid);
2436         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2437         PolicyRequest addPolicyReq;
2438         //change rights
2439         for (auto &denypriv:real_privs_deny) {
2440             /*this entry will deny some privileges for user whose uid (as c string)
2441               was sent in message's buf field.
2442               That user would be denying internet for child in this case*/
2443             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2444             entry.setMaxLevel("Deny");
2445             addPolicyReq.addEntry(entry);
2446         }
2447         Api::sendPolicy(addPolicyReq);
2448         exit(0);
2449     }
2450 }
2451
2452 void saveMappingsToDb(const std::string &version_from, const std::string &version_to,
2453                       const privileges_t &privileges, const std::vector<privileges_t> &mappings) {
2454     TestSecurityManagerDatabase db;
2455     RUNNER_ASSERT_MSG(privileges.size() == mappings.size(), "Wrong given privileges and mappings size");
2456     auto privIt = privileges.begin();
2457     auto mappIt = mappings.begin();
2458     for (; privIt != privileges.end() && mappIt != mappings.end(); privIt++, mappIt++) {
2459         for (const auto &mapping : *mappIt) {
2460             db.setup_privilege_mapping(version_from, version_to, *privIt, mapping);
2461         }
2462     }
2463 }
2464
2465 void saveDefaultMappingsToDb(const std::string &version_from, const std::string &version_to,
2466                              const privileges_t &privileges) {
2467     TestSecurityManagerDatabase db;
2468     for (auto &privilege : privileges) {
2469         db.setup_default_version_privilege(version_from, version_to, privilege);
2470     }
2471 }
2472
2473 void concatUnique(privileges_t &to, const privileges_t &from) {
2474     to.reserve(to.size() + from.size());
2475     for (auto &new_priv : from) {
2476         if (std::find(to.begin(), to.end(), new_priv) == to.end())
2477             to.push_back(new_priv);
2478     }
2479 }
2480
2481 RUNNER_TEST(security_manager_22_get_privilege_mappings)
2482 {
2483     saveMappingsToDb(OLD_VERSION, NEW_VERSION, OLD_PRIVILEGES, NEW_PRIVILEGES);
2484     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2485     privileges_t retrievedMapping;
2486     std::string current;
2487     auto expectedIt = NEW_PRIVILEGES.begin();
2488     for (const auto &privilege : OLD_PRIVILEGES) {
2489         retrievedMapping.clear();
2490         std::vector<std::string> privilegeToMap = {privilege};
2491         Api::getPrivilegesMappings(OLD_VERSION.c_str(), NEW_VERSION.c_str(),
2492                                    privilegeToMap, retrievedMapping);
2493         std::vector<std::string> expectedPrivileges = *expectedIt;
2494         concatUnique(expectedPrivileges, DEFAULT_PRIVILEGES);
2495         RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2496                           "Wrong count of mappings returned for " << privilege << "."
2497                           " Got " << retrievedMapping.size()
2498                           << " expected " << expectedPrivileges.size());
2499         RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2500                           "Wrong mapping returned for " << privilege);
2501         ++expectedIt;
2502     }
2503 }
2504
2505 RUNNER_TEST(security_manager_23_get_privileges_mappings)
2506 {
2507     saveMappingsToDb(OLD_VERSION, NEW_VERSION, OLD_PRIVILEGES, NEW_PRIVILEGES);
2508     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2509
2510     std::vector<std::string> retrievedMapping;
2511     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2512     for(auto &expected : NEW_PRIVILEGES) {
2513         concatUnique(expectedPrivileges, expected);
2514     }
2515     const std::vector<std::string> &privilegesToMap = OLD_PRIVILEGES;
2516
2517     Api::getPrivilegesMappings(OLD_VERSION.c_str(), NEW_VERSION.c_str(), privilegesToMap, retrievedMapping);
2518     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2519                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2520                       << " expected " << expectedPrivileges.size());
2521     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2522                       "Wrong mapping returned for privileges set");
2523 }
2524
2525 RUNNER_TEST(security_manager_24_get_privileges_mappings_default_version)
2526 {
2527     saveMappingsToDb(OLD_VERSION, NEW_VERSION, OLD_PRIVILEGES, NEW_PRIVILEGES);
2528     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2529
2530     std::vector<std::string> retrievedMapping;
2531     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2532     for(auto &expected : NEW_PRIVILEGES) {
2533         concatUnique(expectedPrivileges, expected);
2534     }
2535     const std::vector<std::string> &privilegesToMap = OLD_PRIVILEGES;
2536
2537     Api::getPrivilegesMappings(OLD_VERSION.c_str(), nullptr, privilegesToMap, retrievedMapping);
2538     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2539                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2540                       << " expected " << expectedPrivileges.size());
2541     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2542                       "Wrong mapping returned for privileges set");
2543 }
2544
2545 RUNNER_TEST(security_manager_25_get_default_mappings)
2546 {
2547     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2548
2549     std::vector<std::string> retrievedMapping;
2550     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2551
2552     // Empty privilege to map vector will indicate nullptr privilege array in security-manager API
2553     std::vector<std::string> privilegeToMap;
2554
2555     Api::getPrivilegesMappings(OLD_VERSION.c_str(), NEW_VERSION.c_str(), privilegeToMap, retrievedMapping);
2556     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2557                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2558                       << " expected " << expectedPrivileges.size());
2559     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2560                       "Wrong default mapping returned");
2561 }
2562
2563 RUNNER_TEST(security_manager_26_get_default_mappings_default_version)
2564 {
2565     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2566
2567     std::vector<std::string> retrievedMapping;
2568     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2569
2570     // Empty privilege to map vector will indicate nullptr privilege array in security-manager API
2571     std::vector<std::string> privilegeToMap;
2572
2573     Api::getPrivilegesMappings(OLD_VERSION.c_str(), nullptr, privilegeToMap, retrievedMapping);
2574     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2575                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2576                       << " expected " << expectedPrivileges.size());
2577     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2578                       "Wrong default mapping returned");
2579 }
2580
2581 namespace {
2582 const int sm_app_shared_test_id = 27;
2583 const char *const sm_app_shared_id = "sm_test_27_app_id_full";
2584 const char *const sm_app_shared_another_in_package_id = "sm_test_27_app_2_id_full";
2585 const char *const sm_pkg_shared_id = "sm_test_27_pkg_id_full";
2586
2587 void test_success_worker(const std::string &appName, int test_num)
2588 {
2589     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2590
2591     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2592
2593     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1,
2594         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName << " failed " << " to " << SM_OWNER_RW_OTHERS_RO_PATH );
2595 }
2596
2597 void test_fail_worker(const std::string &appName, int test_num)
2598 {
2599     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2600
2601     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2602
2603     RUNNER_ASSERT_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) == -1,
2604         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName
2605         << " surprisingly succeeded, while expecting fail");
2606 }
2607 }
2608
2609 RUNNER_TEST(security_manager_27a_API2X_app_install)
2610 {
2611     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2612     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2613     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2614     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2615     prepare_app_env(sm_app_shared_test_id, true);
2616
2617     // install other apps
2618     for(const auto &app : MANY_APPS_PKGS) {
2619         InstallRequest requestInst;
2620         requestInst.setAppId(app.first.c_str());
2621         requestInst.setPkgId(app.second.package.c_str());
2622         requestInst.setAppTizenVersion(app.second.Tizen_ver.c_str());
2623
2624         Api::install(requestInst);
2625     };
2626
2627     // install
2628     {
2629         InstallRequest requestInst;
2630         requestInst.setAppId(sm_app_shared_id);
2631         requestInst.setPkgId(sm_pkg_shared_id);
2632         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2633         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2634         requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2635         requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2636         requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2637         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2638         requestInst.setAppTizenVersion("2.4");
2639         Api::install(requestInst);
2640     }
2641
2642     // another app in package
2643     {
2644         InstallRequest requestInst;
2645         requestInst.setAppId(sm_app_shared_another_in_package_id);
2646         requestInst.setPkgId(sm_pkg_shared_id);
2647         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2648         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2649         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2650         requestInst.setAppTizenVersion("2.4");
2651         Api::install(requestInst);
2652     }
2653
2654     /* Check records in the security-manager database */
2655     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2656                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2657     /* Check records in the security-manager database */
2658     check_app_after_install(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2659                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2660
2661     /* TODO: add parameters to this function */
2662     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2663
2664     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1, "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") failed");
2665 }
2666
2667 RUNNER_CHILD_TEST(security_manager_27b_owner_1_have_access)
2668 {
2669     test_success_worker(sm_app_shared_id, sm_app_shared_test_id);
2670 }
2671
2672 RUNNER_CHILD_TEST(security_manager_27c_owner_2_have_access)
2673 {
2674     test_success_worker(sm_app_shared_another_in_package_id, sm_app_shared_test_id);
2675 }
2676
2677 RUNNER_CHILD_TEST(security_manager_27d_API2X_apps_have_access_app_1)
2678 {
2679     test_success_worker("security_manager_10_app_1", sm_app_shared_test_id);
2680 }
2681
2682 RUNNER_CHILD_TEST(security_manager_27e_API2X_apps_dont_have_access_app_2)
2683 {
2684     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2685 }
2686
2687 RUNNER_CHILD_TEST(security_manager_27f_API2X_apps_have_access_app_3)
2688 {
2689     test_success_worker("security_manager_10_app_3", sm_app_shared_test_id);
2690 }
2691
2692 RUNNER_CHILD_TEST(security_manager_27g_API2X_apps_dont_have_access_app_4)
2693 {
2694     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2695 }
2696
2697 RUNNER_CHILD_TEST(security_manager_27h_API2X_apps_have_access_app_5)
2698 {
2699     test_success_worker("security_manager_10_app_5", sm_app_shared_test_id);
2700 }
2701
2702
2703 RUNNER_TEST(security_manager_27i_API2X_app_uninstall)
2704 {
2705     {
2706         InstallRequest requestUninst;
2707         requestUninst.setAppId(sm_app_shared_id);
2708         Api::uninstall(requestUninst);
2709     }
2710     {
2711         InstallRequest requestUninst;
2712         requestUninst.setAppId(sm_app_shared_another_in_package_id);
2713         Api::uninstall(requestUninst);
2714     }
2715
2716     /* Check records in the security-manager database,
2717      * all previously allowed privileges should be removed */
2718     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2719                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2720     check_app_after_uninstall(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2721                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2722 }
2723
2724 RUNNER_TEST(security_manager_27j_API30_app_install)
2725 {
2726     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2727     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2728     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2729     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2730     prepare_app_env(sm_app_shared_test_id, true);
2731
2732     // install
2733     InstallRequest requestInst;
2734     requestInst.setAppId(sm_app_shared_id);
2735     requestInst.setPkgId(sm_pkg_shared_id);
2736     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2737     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2738     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2739     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2740     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2741     requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2742     requestInst.setAppTizenVersion("3.0");
2743
2744     Api::install(requestInst);
2745
2746     /* Check records in the security-manager database */
2747     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2748                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2749
2750     /* TODO: add parameters to this function */
2751     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2752
2753     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1, "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") failed");
2754 }
2755
2756 RUNNER_CHILD_TEST(security_manager_27k_API30_apps_dont_have_access_app_1)
2757 {
2758     test_fail_worker("security_manager_10_app_1", sm_app_shared_test_id);
2759 }
2760
2761 RUNNER_CHILD_TEST(security_manager_27l_API30_apps_dont_have_access_app_2)
2762 {
2763     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2764 }
2765
2766 RUNNER_CHILD_TEST(security_manager_27m_API30_apps_dont_have_access_app_3)
2767 {
2768     test_fail_worker("security_manager_10_app_3", sm_app_shared_test_id);
2769 }
2770
2771 RUNNER_CHILD_TEST(security_manager_27n_API30_apps_dont_have_access_app_4)
2772 {
2773     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2774 }
2775
2776 RUNNER_CHILD_TEST(security_manager_27o_API30_apps_dont_have_access_app_5)
2777 {
2778     test_fail_worker("security_manager_10_app_5", sm_app_shared_test_id);
2779 }
2780
2781 RUNNER_TEST(security_manager_27p_API30_app_uninstall)
2782 {
2783     InstallRequest requestUninst;
2784     requestUninst.setAppId(sm_app_shared_id);
2785
2786     Api::uninstall(requestUninst);
2787
2788     /* Check records in the security-manager database,
2789      * all previously allowed privileges should be removed */
2790     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2791                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2792
2793     // install other apps
2794     for(const auto &app : MANY_APPS_PKGS) {
2795         InstallRequest requestUninst;
2796         requestUninst.setAppId(app.first);
2797
2798         Api::uninstall(requestUninst);
2799     };
2800 }
2801
2802 namespace {
2803 const char *const owner_access = "rwxat";
2804 const char *const target_path_access = "rxl";
2805 const char *const target_dir_access = "x";
2806 const char *const no_access = "";
2807
2808 void check_system_access(const std::string pathLabel, bool apply = true) {
2809     check_exact_smack_accesses("User", pathLabel, (apply ? owner_access : no_access));
2810     check_exact_smack_accesses("System", pathLabel, (apply ? owner_access : no_access));
2811 }
2812
2813 void check_owner_access(const std::string &ownerLabel, const std::string &pathLabel, bool apply = true) {
2814     check_exact_smack_accesses(ownerLabel, pathLabel, (apply ? owner_access : no_access));
2815 }
2816
2817 void check_target_access(const std::string &ownerPkgLabel, const std::string &targetLabel,
2818         const std::string &pathLabel, bool pathShared = true, bool anyPathShared = true) {
2819     check_exact_smack_accesses(targetLabel, pathLabel, (pathShared ? target_path_access : no_access));
2820     check_exact_smack_accesses(targetLabel, ownerPkgLabel, (anyPathShared ? target_dir_access : no_access));
2821 }
2822
2823 void check_path_label(const std::string &path, const std::string &expectedLabel) {
2824     char *label = nullptr;
2825     int ret = smack_new_label_from_path(path.c_str(), XATTR_NAME_SMACK, 0, &label);
2826     RUNNER_ASSERT_MSG(ret > 0, "smack_new_label_from_path failed for " << path);
2827     SmackLabelPtr realLabel(label);
2828     RUNNER_ASSERT_MSG(realLabel.get() == expectedLabel, "Fetched label from " << path << " different"
2829             " than expected, is : " << realLabel.get() << " should be " << expectedLabel);
2830 }
2831
2832 void createFile(const std::string &filePath)
2833 {
2834     //create temporary file and set label for it
2835     mode_t systemMask;
2836
2837     unlink(filePath.c_str());
2838     //allow to create file with 777 rights
2839     systemMask = umask(0000);
2840     int fd = open(filePath.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
2841     //restore system mask
2842     umask(systemMask);
2843     RUNNER_ASSERT_ERRNO_MSG(fd > -1, "Unable to create file for tests");
2844
2845     //for descriptor protection
2846     FdUniquePtr fd_ptr(&fd);
2847
2848     //change owner and group to user APP
2849     int ret = chown(filePath.c_str(), APP_UID, APP_GID);
2850     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "Unable to change file owner");
2851 }
2852
2853 }
2854
2855 RUNNER_TEST(security_manager_30a_send_incomplete_req1)
2856 {
2857     SharingRequest request;
2858     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2859     request.setOwnerAppId("someOwner");
2860     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2861     request.setTargetAppId("someTarget");
2862     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2863 }
2864
2865 RUNNER_TEST(security_manager_30b_send_incomplete_req2)
2866 {
2867     SharingRequest request;
2868     request.setTargetAppId("someTarget");
2869     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2870     request.setOwnerAppId("someOwner");
2871     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2872 }
2873
2874 RUNNER_TEST(security_manager_30c_send_incomplete_req3)
2875 {
2876     SharingRequest request;
2877     const char *somePaths[] = {"path1", "path2"};
2878     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2879     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2880     request.setOwnerAppId("someOwner");
2881     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2882 }
2883
2884 RUNNER_TEST(security_manager_30d_unknown_owner)
2885 {
2886     // This test depends on order of checks in security-manager service implementation
2887     SharingRequest request;
2888     request.setOwnerAppId("ImPrettySureIDontExist");
2889     request.setTargetAppId("IDontMatter");
2890     const char *somePaths[] = {"path1", "path2"};
2891     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2892     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2893 }
2894
2895 RUNNER_TEST(security_manager_30e_unknown_target)
2896 {
2897     // This test depends on order of checks in security-manager service implementation
2898     AppInstallHelper owner("installedApp");
2899     owner.revokeRules();
2900     owner.createInstallDir();
2901     InstallRequest ownerInst;
2902     ownerInst.setAppId(owner.getAppId());
2903     ownerInst.setPkgId(owner.getPkgId());
2904     Api::install(ownerInst);
2905
2906     SharingRequest request;
2907     request.setOwnerAppId(owner.getAppId());
2908     request.setTargetAppId("NowImPrettySureIDontExist");
2909     const char *somePaths[] = {"path1", "path2"};
2910     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2911     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2912
2913     Api::uninstall(ownerInst);
2914 }
2915
2916 RUNNER_TEST(security_manager_30f_bad_paths)
2917 {
2918     // This test depends on order of checks in security-manager service implementation
2919     AppInstallHelper owner("installedApp");
2920     owner.revokeRules();
2921     owner.createInstallDir();
2922     InstallRequest ownerInst;
2923     ownerInst.setAppId(owner.getAppId());
2924     ownerInst.setPkgId(owner.getPkgId());
2925     Api::install(ownerInst);
2926
2927     AppInstallHelper target("secondInstalledApp");
2928     target.revokeRules();
2929     target.createInstallDir();
2930     InstallRequest targetInst;
2931     targetInst.setAppId(target.getAppId());
2932     targetInst.setPkgId(target.getPkgId());
2933     Api::install(targetInst);
2934
2935     SharingRequest request;
2936     request.setOwnerAppId(owner.getAppId());
2937     request.setTargetAppId(target.getAppId());
2938
2939     const char *somePath = "/tmp/somePath";
2940     createFile(somePath);
2941     const char *somePaths[] = {somePath};
2942     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2943     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_NOT_PATH_OWNER);
2944
2945     Api::uninstall(ownerInst);
2946 }
2947
2948 RUNNER_TEST(security_manager_31_simple_share)
2949 {
2950     std::vector<AppInstallHelper> helper {{"app30a"}, {"app30b"}};
2951     auto &owner = helper[0];
2952     auto &target = helper[1];
2953
2954     for (auto &e : helper) {
2955         e.revokeRules();
2956         e.createInstallDir();
2957     }
2958
2959     owner.createPrivateDir();
2960     owner.createSharedFile();
2961
2962     InstallRequest ownerReq;
2963     ownerReq.setAppId(owner.getAppId());
2964     ownerReq.setPkgId(owner.getPkgId());
2965     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
2966     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
2967     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
2968     Api::install(ownerReq);
2969
2970     InstallRequest targetReq;
2971     targetReq.setAppId(target.getAppId());
2972     targetReq.setPkgId(target.getAppId());
2973     Api::install(targetReq);
2974
2975     SharingRequest share1;
2976     std::string sharedPath = owner.getSharedPath();
2977     share1.setOwnerAppId(owner.getAppId());
2978     share1.setTargetAppId(target.getAppId());
2979     const char *path[] = {sharedPath.c_str()};
2980     share1.addPaths(path, 1);
2981     Api::applySharing(share1);
2982
2983     TestSecurityManagerDatabase db;
2984     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
2985     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
2986
2987     check_system_access(pathLabel1);
2988     check_owner_access(owner.generateAppLabel(), pathLabel1);
2989     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
2990     check_path_label(sharedPath, pathLabel1);
2991
2992     Api::dropSharing(share1);
2993     check_system_access(pathLabel1, false);
2994     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
2995     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
2996     check_path_label(sharedPath, owner.generatePkgLabel());
2997
2998     Api::uninstall(ownerReq);
2999     Api::uninstall(targetReq);
3000 }
3001
3002 RUNNER_TEST(security_manager_32_double_share)
3003 {
3004     std::vector<AppInstallHelper> helper {{"app31a"}, {"app31b"}};
3005     auto &owner = helper[0];
3006     auto &target = helper[1];
3007
3008     // cleanup
3009     for (auto &e : helper) {
3010         e.revokeRules();
3011         e.createInstallDir();
3012     }
3013     owner.createPrivateDir();
3014     owner.createSharedFile();
3015
3016     InstallRequest ownerReq;
3017     ownerReq.setAppId(owner.getAppId());
3018     ownerReq.setPkgId(owner.getPkgId());
3019     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
3020
3021     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3022     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3023     Api::install(ownerReq);
3024
3025     InstallRequest targetReq;
3026     targetReq.setAppId(target.getAppId());
3027     targetReq.setPkgId(target.getAppId());
3028     Api::install(targetReq);
3029
3030     SharingRequest share1;
3031     std::string sharedPath = owner.getSharedPath(0);
3032     share1.setOwnerAppId(owner.getAppId());
3033     share1.setTargetAppId(target.getAppId());
3034     const char *path[] = {sharedPath.c_str()};
3035     share1.addPaths(path, 1);
3036     Api::applySharing(share1);
3037
3038     TestSecurityManagerDatabase db;
3039     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3040     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3041
3042     check_system_access(pathLabel);
3043     check_owner_access(owner.generateAppLabel(), pathLabel);
3044     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3045     check_path_label(sharedPath, pathLabel);
3046
3047     Api::applySharing(share1);
3048     check_system_access(pathLabel);
3049     check_owner_access(owner.generateAppLabel(), pathLabel);
3050     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3051     check_path_label(sharedPath, pathLabel);
3052
3053     Api::dropSharing(share1);
3054     check_system_access(pathLabel);
3055     check_owner_access(owner.generateAppLabel(), pathLabel);
3056     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3057     check_path_label(sharedPath, pathLabel);
3058
3059     Api::dropSharing(share1);
3060     check_system_access(pathLabel, false);
3061     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3062     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel, false, false);
3063     check_path_label(sharedPath, owner.generatePkgLabel());
3064
3065     Api::uninstall(ownerReq);
3066     Api::uninstall(targetReq);
3067 }
3068 RUNNER_TEST(security_manager_33_share_two_with_one)
3069 {
3070     std::vector<AppInstallHelper> helper {{"app32a"}, {"app32b"}};
3071     auto &owner = helper[0];
3072     auto &target = helper[1];
3073
3074     // cleanup
3075     for (auto &e : helper) {
3076         e.revokeRules();
3077         e.createInstallDir();
3078     }
3079     owner.createPrivateDir();
3080     owner.createSharedFile(0);
3081     owner.createSharedFile(1);
3082
3083     InstallRequest ownerReq;
3084     ownerReq.setAppId(owner.getAppId());
3085     ownerReq.setPkgId(owner.getPkgId());
3086     ownerReq.addPath(owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW);
3087     ownerReq.addPath(owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW);
3088
3089     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3090     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3091     Api::install(ownerReq);
3092
3093     InstallRequest targetReq;
3094     targetReq.setAppId(target.getAppId());
3095     targetReq.setPkgId(target.getAppId());
3096     Api::install(targetReq);
3097
3098     SharingRequest share1, share2;
3099     std::string sharedPath1 = owner.getSharedPath(0);
3100     std::string sharedPath2 = owner.getSharedPath(1);
3101     share1.setOwnerAppId(owner.getAppId());
3102     share2.setOwnerAppId(owner.getAppId());
3103     share1.setTargetAppId(target.getAppId());
3104     share2.setTargetAppId(target.getAppId());
3105     const char *path1[] = {sharedPath1.c_str()};
3106     const char *path2[] = {sharedPath2.c_str()};
3107     share1.addPaths(path1, 1);
3108     share2.addPaths(path2, 1);
3109
3110     Api::applySharing(share1);
3111     TestSecurityManagerDatabase db;
3112     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3113     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3114
3115     check_system_access(pathLabel1);
3116     check_owner_access(owner.generateAppLabel(), pathLabel1);
3117     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3118     check_path_label(sharedPath1, pathLabel1);
3119
3120     Api::applySharing(share2);
3121     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3122     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3123     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for private shared paths should be unique!");
3124
3125     check_system_access(pathLabel1);
3126     check_system_access(pathLabel2);
3127     check_owner_access(owner.generateAppLabel(), pathLabel1);
3128     check_owner_access(owner.generateAppLabel(), pathLabel2);
3129     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3130     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3131     check_path_label(sharedPath1, pathLabel1);
3132     check_path_label(sharedPath2, pathLabel2);
3133
3134     Api::dropSharing(share1);
3135     check_system_access(pathLabel1, false);
3136     check_system_access(pathLabel2);
3137     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3138     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false);
3139     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3140     check_path_label(sharedPath1, owner.generatePkgLabel());
3141     check_path_label(sharedPath2, pathLabel2);
3142
3143     Api::dropSharing(share2);
3144     check_system_access(pathLabel1, false);
3145     check_system_access(pathLabel2, false);
3146     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3147     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3148     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3149     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2, false, false);
3150     check_path_label(sharedPath1, owner.generatePkgLabel());
3151     check_path_label(sharedPath2, owner.generatePkgLabel());
3152
3153     Api::uninstall(ownerReq);
3154     Api::uninstall(targetReq);
3155 }
3156
3157 RUNNER_TEST(security_manager_34_share_one_with_two)
3158 {
3159     std::vector<AppInstallHelper> helper {{"app33a"}, {"app33b"}, {"app33c"}};
3160     auto &owner = helper[0];
3161     auto &target1 = helper[1];
3162     auto &target2 = helper[2];
3163
3164     // cleanup
3165     for (auto &e : helper) {
3166         e.revokeRules();
3167         e.createInstallDir();
3168     }
3169     owner.createPrivateDir();
3170     owner.createSharedFile();
3171
3172     InstallRequest ownerReq;
3173     ownerReq.setAppId(owner.getAppId());
3174     ownerReq.setPkgId(owner.getPkgId());
3175     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
3176     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3177     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3178     Api::install(ownerReq);
3179
3180     for (size_t i = 1; i < helper.size(); i++) {
3181         InstallRequest targetReq;
3182         targetReq.setAppId(helper[i].getAppId());
3183         targetReq.setPkgId(helper[i].getAppId());
3184         Api::install(targetReq);
3185     }
3186
3187     SharingRequest share1, share2;
3188     std::string sharedPath = owner.getSharedPath(0).c_str();
3189     share1.setOwnerAppId(owner.getAppId());
3190     share2.setOwnerAppId(owner.getAppId());
3191     share1.setTargetAppId(target1.getAppId());
3192     share2.setTargetAppId(target2.getAppId());
3193
3194     const char *path[] = {sharedPath.c_str()};
3195     share1.addPaths(path, 1);
3196     share2.addPaths(path, 1);
3197
3198     Api::applySharing(share1);
3199     TestSecurityManagerDatabase db;
3200     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3201     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3202
3203     check_system_access(pathLabel);
3204     check_owner_access(owner.generateAppLabel(), pathLabel);
3205     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3206     check_path_label(sharedPath, pathLabel);
3207
3208     Api::applySharing(share2);
3209     check_system_access(pathLabel);
3210     check_owner_access(owner.generateAppLabel(), pathLabel);
3211     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3212     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3213     check_path_label(sharedPath, pathLabel);
3214
3215     Api::dropSharing(share1);
3216     check_system_access(pathLabel);
3217     check_owner_access(owner.generateAppLabel(), pathLabel);
3218     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3219     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3220     check_path_label(sharedPath, pathLabel);
3221
3222     Api::dropSharing(share2);
3223     check_system_access(pathLabel, false);
3224     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3225     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3226     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel, false, false);
3227     check_path_label(sharedPath, owner.generatePkgLabel());
3228
3229     Api::uninstall(ownerReq);
3230     for (size_t i = 1; i < helper.size(); i++) {
3231         InstallRequest targetReq;
3232         targetReq.setAppId(helper[i].getAppId());
3233         targetReq.setPkgId(helper[i].getAppId());
3234         Api::uninstall(targetReq);
3235     }
3236 }
3237
3238 RUNNER_TEST(security_manager_35_share_two_with_two)
3239 {
3240     std::vector<AppInstallHelper> helper {{"app34a"}, {"app34b"}, {"app34c"}};
3241     auto &owner = helper[0];
3242     auto &target1 = helper[1];
3243     auto &target2 = helper[2];
3244
3245     // cleanup
3246     for (auto &e : helper) {
3247         e.revokeRules();
3248         e.createInstallDir();
3249     }
3250     owner.createPrivateDir();
3251     owner.createSharedFile(0);
3252     owner.createSharedFile(1);
3253
3254     InstallRequest ownerReq;
3255     ownerReq.setAppId(owner.getAppId());
3256     ownerReq.setPkgId(owner.getPkgId());
3257     ownerReq.addPath(owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW);
3258     ownerReq.addPath(owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW);
3259
3260     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3261     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3262     Api::install(ownerReq);
3263
3264     for (size_t i = 1; i < helper.size(); i++) {
3265         InstallRequest targetReq;
3266         targetReq.setAppId(helper[i].getAppId());
3267         targetReq.setPkgId(helper[i].getAppId());
3268         Api::install(targetReq);
3269     }
3270
3271     SharingRequest share1, share2;
3272     std::string sharedPath1 = owner.getSharedPath(0).c_str();
3273     std::string sharedPath2 = owner.getSharedPath(1).c_str();
3274     share1.setOwnerAppId(owner.getAppId());
3275     share2.setOwnerAppId(owner.getAppId());
3276     share1.setTargetAppId(target1.getAppId());
3277     share2.setTargetAppId(target2.getAppId());
3278
3279     const char *path1[] = {sharedPath1.c_str()};
3280     const char *path2[] = {sharedPath2.c_str()};
3281     share1.addPaths(path1, 1);
3282     share2.addPaths(path2, 1);
3283
3284     Api::applySharing(share1);
3285     TestSecurityManagerDatabase db;
3286     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3287     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3288
3289     check_system_access(pathLabel1);
3290     check_owner_access(owner.generateAppLabel(), pathLabel1);
3291     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3292     check_path_label(sharedPath1, pathLabel1);
3293
3294     Api::applySharing(share2);
3295     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3296     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3297     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for shared files should be unique!");
3298
3299     check_system_access(pathLabel1);
3300     check_system_access(pathLabel2);
3301     check_owner_access(owner.generateAppLabel(), pathLabel1);
3302     check_owner_access(owner.generateAppLabel(), pathLabel2);
3303     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3304     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2);
3305     check_path_label(sharedPath1, pathLabel1);
3306     check_path_label(sharedPath2, pathLabel2);
3307
3308     Api::dropSharing(share2);
3309     check_system_access(pathLabel1);
3310     check_system_access(pathLabel2, false);
3311     check_owner_access(owner.generateAppLabel(), pathLabel1);
3312     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3313     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3314     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3315     check_path_label(sharedPath1, pathLabel1);
3316     check_path_label(sharedPath2, owner.generatePkgLabel());
3317
3318     Api::dropSharing(share1);
3319     check_system_access(pathLabel1, false);
3320     check_system_access(pathLabel2, false);
3321     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3322     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3323     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1, false, false);
3324     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3325     check_path_label(sharedPath1, owner.generatePkgLabel());
3326     check_path_label(sharedPath2, owner.generatePkgLabel());
3327     Api::uninstall(ownerReq);
3328     for (size_t i = 1; i < helper.size(); i++) {
3329         InstallRequest targetReq;
3330         targetReq.setAppId(helper[i].getAppId());
3331         targetReq.setPkgId(helper[i].getAppId());
3332         Api::uninstall(targetReq);
3333     }
3334 }
3335
3336 RUNNER_TEST(security_manager_40_set_wrong_author_id)
3337 {
3338     InstallRequest requestInst;
3339
3340     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3341         security_manager_app_inst_req_set_author_id(requestInst.get(), NULL));
3342
3343     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3344         security_manager_app_inst_req_set_author_id(requestInst.get(), ""));
3345 }
3346
3347 RUNNER_TEST(security_manager_41_set_author_id_multiple_times)
3348 {
3349     for(unsigned int i=0; i<10; ++i) {
3350         std::string authorId = "some-author-id" + std::to_string(i);
3351
3352         InstallRequest requestInst;
3353         requestInst.setAuthorId(authorId);
3354     }
3355 }
3356
3357 RUNNER_TEST(security_manager_43_app_install_with_trusted_path)
3358 {
3359     std::vector<AppInstallHelper> helper {{"app43a"}, {"app43b"}, {"app43c"}};
3360     auto &provider  = helper[0];
3361     auto &user      = helper[1];
3362     auto &untrusted = helper[2];
3363
3364     TestSecurityManagerDatabase dbtest;
3365     const char *author_id = "custom_author_id_test 41";
3366
3367     const char *const trusted_access = "rwxatl";
3368     const char *const system_access = "rwxatl";
3369
3370     int result;
3371
3372     // cleanup
3373     for (auto &e : helper) {
3374         e.revokeRules();
3375         e.createInstallDir();
3376         e.createTrustedDir();
3377     }
3378
3379     result = nftw(provider.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3380     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_TRUSTED_PATH);
3381
3382     // install app with shared/trusted dir
3383     InstallRequest trustingApp;
3384     trustingApp.setAppId(provider.getAppId());
3385     trustingApp.setPkgId(provider.getPkgId());
3386     trustingApp.setAuthorId("author id to be overwritten");
3387     trustingApp.setAuthorId(author_id);
3388     trustingApp.addPath(provider.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3389     Api::install(trustingApp);
3390
3391     int64_t authorDb = dbtest.get_author_id(author_id);
3392     const std::string trusted_label = std::string("User::Author::") + std::to_string(authorDb);
3393
3394     // check trusted path label
3395     nftw_expected_label = trusted_label;
3396     nftw_expected_transmute = true;
3397     nftw_expected_exec = false;
3398
3399     // check labels
3400     result = nftw(provider.getTrustedDir().c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
3401     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_TRUSTED_PATH);
3402
3403     // check rules
3404     check_exact_access("System", trusted_label, system_access);
3405     check_exact_access("User", trusted_label, system_access);
3406     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, trusted_access);
3407     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3408
3409     // install trusted app
3410     InstallRequest trustedApp;
3411     trustedApp.setAppId(user.getAppId());
3412     trustedApp.setPkgId(user.getPkgId());
3413     trustedApp.setAuthorId(author_id);
3414     Api::install(trustedApp);
3415
3416     // check rules
3417     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3418     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3419
3420     // install untrusted app
3421     InstallRequest untrustedApp;
3422     untrustedApp.setAppId(untrusted.getAppId());
3423     untrustedApp.setPkgId(untrusted.getPkgId());
3424     Api::install(untrustedApp);
3425
3426     // check rules
3427     check_exact_access(generateAppLabel(untrusted.getAppId()), trusted_label, "");
3428     check_exact_access(generatePkgLabel(untrusted.getPkgId()), trusted_label, "");
3429
3430     // uninstall trusting app
3431     Api::uninstall(trustingApp);
3432
3433     // there's still one app with author id, rules should be kept
3434     check_exact_access("System", trusted_label, system_access);
3435     check_exact_access("User", trusted_label, system_access);
3436     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, "");
3437     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3438     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3439     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3440
3441     Api::uninstall(trustedApp);
3442
3443     // no more apps with author id
3444     check_exact_access("System", trusted_label, "");
3445     check_exact_access("User", trusted_label, "");
3446     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, "");
3447     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3448
3449     Api::uninstall(untrustedApp);
3450 }
3451
3452
3453 RUNNER_TEST(security_manager_44_app_install_with_trusted_path_no_author_id)
3454 {
3455     AppInstallHelper help("app44");
3456     help.createInstallDir();
3457     help.createTrustedDir();
3458
3459     // install app with shared/trusted dir but without authors id
3460     InstallRequest app;
3461     app.setAppId(help.getAppId());
3462     app.setPkgId(help.getPkgId());
3463     app.addPath(help.getTrustedDir(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3464     Api::install(app, SECURITY_MANAGER_ERROR_INPUT_PARAM);
3465 }
3466
3467 int main(int argc, char *argv[])
3468 {
3469     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
3470 }