34fa989ef3c61b82ef6b92b70dbdbb08fc13ed15
[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     const char *const update_app_id = "security_manager_15_update_app_id";
1743     const char *const update_privilege = "http://tizen.org/privilege/led";
1744     const char *const check_start_bucket = "ADMIN";
1745     const std::string username("sm_test_15_username");
1746     PolicyRequest addPolicyRequest;
1747     CynaraTestAdmin::Admin admin;
1748
1749     struct message {
1750         uid_t uid;
1751         gid_t gid;
1752     } msg;
1753
1754     int pipefd[2];
1755     pid_t pid;
1756     int result = 0;
1757
1758     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1759
1760     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1761     user.create();
1762
1763     pid = fork();
1764     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1765     if (pid != 0)//parent process
1766     {
1767         FdUniquePtr pipeptr(pipefd+1);
1768         close(pipefd[0]);
1769
1770         register_current_process_as_privilege_manager(user.getUid(), true);
1771
1772         //send info to child
1773         msg.uid = user.getUid();
1774         msg.gid = user.getGid();
1775
1776         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1777         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1778
1779         //wait for child
1780         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1781
1782         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1783                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1784     }
1785     if(pid == 0)
1786     {
1787         FdUniquePtr pipeptr(pipefd);
1788         close(pipefd[1]);
1789
1790         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1791         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1792
1793         //become admin privacy manager manager
1794         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1795         result = drop_root_privileges(msg.uid, msg.gid);
1796         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1797
1798         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1799         entry.setMaxLevel("Allow");
1800
1801         addPolicyRequest.addEntry(entry);
1802         Api::sendPolicy(addPolicyRequest);
1803         exit(0);
1804     }
1805 }
1806
1807 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1808 {
1809     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1810     const char *const update_privilege = "http://tizen.org/privilege/led";
1811     const char *const check_start_bucket = "ADMIN";
1812     const std::string username("sm_test_15_username");
1813     PolicyRequest addPolicyRequest;
1814     CynaraTestAdmin::Admin admin;
1815
1816     struct message {
1817         uid_t uid;
1818         gid_t gid;
1819     } msg;
1820
1821     int pipefd[2];
1822     pid_t pid;
1823     int result = 0;
1824
1825     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1826
1827     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1828     user.create();
1829
1830     pid = fork();
1831     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1832     if (pid != 0)//parent process
1833     {
1834         FdUniquePtr pipeptr(pipefd+1);
1835         close(pipefd[0]);
1836
1837         register_current_process_as_privilege_manager(user.getUid(), true);
1838
1839         //send info to child
1840         msg.uid = user.getUid();
1841         msg.gid = user.getGid();
1842
1843         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1844         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1845
1846         //wait for child
1847         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1848
1849         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_other_app_id).c_str(),
1850                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1851     }
1852     if(pid == 0)
1853     {
1854         FdUniquePtr pipeptr(pipefd);
1855         close(pipefd[1]);
1856
1857         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1858         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1859
1860         //become admin privacy manager manager
1861         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1862         result = drop_root_privileges(msg.uid, msg.gid);
1863         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1864
1865         // use wildcard as appId
1866         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1867         entry.setMaxLevel("Allow");
1868
1869         addPolicyRequest.addEntry(entry);
1870         Api::sendPolicy(addPolicyRequest);
1871         exit(0);
1872     }
1873 }
1874
1875 RUNNER_MULTIPROCESS_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1876 {
1877     const char *const update_app_id = "security_manager_15_update_app_id";
1878     const char *const update_privilege = "http://tizen.org/privilege/led";
1879     const char *const check_start_bucket = "";
1880     const std::string username("sm_test_15_username");
1881     PolicyRequest addPolicyRequest;
1882     CynaraTestAdmin::Admin admin;
1883
1884     struct message {
1885         uid_t uid;
1886         gid_t gid;
1887     } msg;
1888
1889     int pipefd[2];
1890     pid_t pid;
1891     int result = 0;
1892
1893     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1894
1895     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1896     user.create();
1897
1898     pid = fork();
1899     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1900     if (pid != 0)//parent process
1901     {
1902         FdUniquePtr pipeptr(pipefd+1);
1903         close(pipefd[0]);
1904
1905         register_current_process_as_privilege_manager(user.getUid(), false);
1906
1907         //send info to child
1908         msg.uid = user.getUid();
1909         msg.gid = user.getGid();
1910
1911         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1912         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1913
1914         //wait for child
1915         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1916
1917         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1918                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1919     }
1920     if(pid == 0)
1921     {
1922         FdUniquePtr pipeptr(pipefd);
1923         close(pipefd[1]);
1924
1925         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1926         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1927
1928         //become admin privacy manager manager
1929         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1930         result = drop_root_privileges(msg.uid, msg.gid);
1931         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1932
1933         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1934         entry.setLevel("Allow");
1935
1936         addPolicyRequest.addEntry(entry);
1937         Api::sendPolicy(addPolicyRequest);
1938         exit(0);
1939     }
1940 }
1941
1942 RUNNER_MULTIPROCESS_TEST(security_manager_16_policy_levels_get)
1943 {
1944     const std::string username("sm_test_16_user_cynara_policy");
1945     CynaraTestAdmin::Admin admin;
1946     int pipefd[2];
1947     pid_t pid;
1948     int result = 0;
1949
1950     struct message {
1951         uid_t uid;
1952         gid_t gid;
1953     } msg;
1954
1955     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1956
1957     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1958     user.create();
1959
1960     pid = fork();
1961     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1962     if (pid != 0)//parent process
1963     {
1964         FdUniquePtr pipeptr(pipefd+1);
1965         close(pipefd[0]);
1966
1967         //send info to child
1968         msg.uid = user.getUid();
1969         msg.gid = user.getGid();
1970
1971         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1972         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1973
1974         //wait for child
1975         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
1976     }
1977     if(pid == 0)
1978     {
1979         int ret;
1980         char** levels;
1981         std::string allow_policy, deny_policy;
1982         size_t count;
1983         FdUniquePtr pipeptr(pipefd);
1984         close(pipefd[1]);
1985
1986         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1987         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1988
1989         //become admin privacy manager manager
1990         result = drop_root_privileges(msg.uid, msg.gid);
1991         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1992
1993         // without plugins there should only be 2 policies - Allow and Deny
1994         ret = security_manager_policy_levels_get(&levels, &count);
1995
1996         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
1997                 "Invlid return code: " << ret);
1998
1999         RUNNER_ASSERT_MSG(count == 2, "Invalid number of policy levels. Should be 2, instead there is: " << static_cast<int>(count));
2000
2001         deny_policy = std::string(levels[0]);
2002         allow_policy = std::string(levels[count-1]);
2003
2004         // first should always be Deny
2005         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
2006                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
2007
2008         // last should always be Allow
2009         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
2010                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
2011
2012         security_manager_policy_levels_free(levels, count);
2013         exit(0);
2014     }
2015 }
2016
2017 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
2018 {
2019     const char *const update_app_id = "security_manager_17_update_app_id";
2020     const char *const update_privilege = "http://tizen.org/privilege/led";
2021     const char *const check_start_bucket = "";
2022     const std::string username("sm_test_17_username");
2023     PolicyRequest addPolicyRequest;
2024     CynaraTestAdmin::Admin admin;
2025
2026     struct message {
2027         uid_t uid;
2028         gid_t gid;
2029     } msg;
2030
2031     int pipefd[2];
2032     int pipefd2[2];
2033     pid_t pid;
2034     int result = 0;
2035
2036     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2037     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
2038
2039     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2040     user.create();
2041
2042     pid = fork();
2043     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2044     if (pid != 0)//parent process
2045     {
2046         FdUniquePtr pipeptr(pipefd+1);
2047         close(pipefd[0]);
2048
2049         register_current_process_as_privilege_manager(user.getUid(), false);
2050
2051         //send info to child
2052         msg.uid = user.getUid();
2053         msg.gid = user.getGid();
2054
2055         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2056         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2057
2058         //wait for child
2059         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2060
2061         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2062                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
2063
2064         pid = fork();
2065         if (pid != 0)//parent process
2066         {
2067             FdUniquePtr pipeptr(pipefd2+1);
2068             close(pipefd2[0]);
2069
2070             //send info to child
2071             msg.uid = user.getUid();
2072             msg.gid = user.getGid();
2073
2074             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
2075             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2076
2077             //wait for child
2078             RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2079
2080             //wait for child
2081             waitpid(-1, &result, 0);
2082
2083             admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2084                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
2085         }
2086         if(pid == 0)
2087         {
2088             FdUniquePtr pipeptr(pipefd2);
2089             close(pipefd2[1]);
2090
2091             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
2092             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2093
2094             //become admin privacy manager manager
2095             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2096             result = drop_root_privileges(msg.uid, msg.gid);
2097             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2098
2099             // delete this entry
2100             PolicyRequest deletePolicyRequest;
2101             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2102             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
2103
2104             deletePolicyRequest.addEntry(deleteEntry);
2105             Api::sendPolicy(deletePolicyRequest);
2106             exit(0);
2107         }
2108     }
2109     if(pid == 0)
2110     {
2111         FdUniquePtr pipeptr(pipefd);
2112         close(pipefd[1]);
2113
2114         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2115         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2116
2117         //become admin privacy manager manager
2118         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2119         result = drop_root_privileges(msg.uid, msg.gid);
2120         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2121
2122         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2123         entry.setLevel("Allow");
2124
2125         addPolicyRequest.addEntry(entry);
2126         Api::sendPolicy(addPolicyRequest);
2127         exit(0);
2128     }
2129 }
2130
2131 RUNNER_MULTIPROCESS_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
2132 {
2133     const std::string username("sm_test_17_user_name");
2134
2135     struct message {
2136         uid_t uid;
2137         gid_t gid;
2138         unsigned int privileges_count;
2139     } msg;
2140
2141     int pipefd[2];
2142     pid_t pid;
2143     int result = 0;
2144
2145     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2146
2147     pid = fork();
2148     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2149     if (pid != 0)//parent process
2150     {
2151         FdUniquePtr pipeptr(pipefd+1);
2152         close(pipefd[0]);
2153
2154         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2155         user.create();
2156
2157         unsigned int privileges_count = 0;
2158
2159         register_current_process_as_privilege_manager(user.getUid(), false);
2160         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2161         ++privileges_count;
2162
2163         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2164             InstallRequest requestInst;
2165             requestInst.setAppId(MANY_APPS[i].c_str());
2166             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).package.c_str());
2167             requestInst.setUid(user.getUid());
2168
2169             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2170                 requestInst.addPrivilege(priv.c_str());
2171             };
2172
2173             Api::install(requestInst);
2174             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2175         };
2176
2177         //send info to child
2178         msg.uid = user.getUid();
2179         msg.gid = user.getGid();
2180         msg.privileges_count = privileges_count;
2181
2182         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2183         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2184
2185         //wait for child
2186         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2187     }
2188     if(pid == 0)
2189     {
2190         FdUniquePtr pipeptr(pipefd);
2191         close(pipefd[1]);
2192
2193         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2194         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2195
2196         //become admin privacy manager manager
2197         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2198         result = drop_root_privileges(msg.uid, msg.gid);
2199         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2200
2201         // filter by privilege
2202         std::vector<PolicyEntry> policyEntries;
2203         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2204         Api::getPolicy(filter, policyEntries);
2205
2206         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2207         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2208
2209         // filter by other privilege
2210         policyEntries.clear();
2211         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2212         Api::getPolicy(filter2, policyEntries);
2213
2214         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2215         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2216
2217         // filter by appId
2218         policyEntries.clear();
2219         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2220         Api::getPolicy(filter3, policyEntries);
2221
2222         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2223         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2224     }
2225 }
2226
2227 RUNNER_CHILD_TEST(security_manager_18_user_cynara_policy)
2228 {
2229     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2230     const char *const MAIN_BUCKET = "MAIN";
2231     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2232     const char *const ADMIN_BUCKET = "ADMIN";
2233     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2234     const std::string username("sm_test_10_user_cynara_policy");
2235     CynaraTestAdmin::Admin admin;
2236     std::string uid_string;
2237     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2238     user.create();
2239     user.getUidString(uid_string);
2240
2241     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2242     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2243     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2244
2245     user.remove();
2246     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2247
2248     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2249     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2250     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2251     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2252 }
2253
2254 RUNNER_CHILD_TEST(security_manager_19_security_manager_cmd_install)
2255 {
2256     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2257     int ret;
2258     const int SUCCESS = 0;
2259     const int FAILURE = 256;
2260     const std::string app_id = "security_manager_10_app";
2261     const std::string pkg_id = "security_manager_10_pkg";
2262     const std::string username("sm_test_10_user_name");
2263     std::string uid_string;
2264     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2265     user.create();
2266     user.getUidString(uid_string);
2267     const std::string path1 = appDirPath(user, app_id, pkg_id) + "/p1";
2268     const std::string path2 = appDirPath(user, app_id, pkg_id) + "/p2";
2269     const std::string pkgopt = " --pkg=" + pkg_id;
2270     const std::string appopt = " --app=" + app_id;
2271     const std::string uidopt = " --uid=" + uid_string;
2272
2273     mktreeSafe(path1.c_str(), 0);
2274     mktreeSafe(path2.c_str(), 0);
2275
2276     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2277
2278     struct operation {
2279         std::string command;
2280         int expected_result;
2281     };
2282     std::vector<struct operation> operations = {
2283             {"security-manager-cmd", FAILURE},//no option
2284             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2285             {"security-manager-cmd --help", SUCCESS},
2286             {"security-manager-cmd --install", FAILURE},//no params
2287             {"security-manager-cmd -i", FAILURE},//no params
2288             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2289             {installcmd, SUCCESS},
2290             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2291             {installcmd + " --path " + path1 + " writable", SUCCESS},
2292             {installcmd + " --path " + path1, FAILURE},//no path type
2293             {installcmd + " --path " + path1 + " writable" + " --path " + path2 + " readable", SUCCESS},
2294             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " readable", FAILURE},//wrong path type
2295             {installcmd + " --path " + path1 + " writable" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2296     };
2297
2298     for (auto &op : operations) {
2299         ret = system(op.command.c_str());
2300         RUNNER_ASSERT_MSG(ret == op.expected_result,
2301                 "Unexpected result for command '" << op.command <<"': "
2302                 << ret << " Expected was: "<< op.expected_result);
2303     }
2304 }
2305
2306 RUNNER_CHILD_TEST(security_manager_20_security_manager_cmd_users)
2307 {
2308     RUNNER_IGNORED_MSG("temporarily disabled due to gumd timeouts");
2309     int ret;
2310     const int SUCCESS = 0;
2311     const int FAILURE = 256;
2312     const std::string username("sm_test_11_user_name");
2313     std::string uid_string;
2314     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, true);
2315     user.create();
2316     user.getUidString(uid_string);
2317     const std::string uidopt = " --uid=" + uid_string;
2318
2319     struct operation {
2320         std::string command;
2321         int expected_result;
2322     };
2323     std::vector<struct operation> operations = {
2324             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2325             {"security-manager-cmd -m", FAILURE},//no params
2326             {"security-manager-cmd -mr", FAILURE},//no uid
2327             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2328             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2329             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2330             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2331             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2332             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2333             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2334             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2335     };
2336
2337     for (auto &op : operations) {
2338         ret = system(op.command.c_str());
2339         RUNNER_ASSERT_MSG(ret == op.expected_result,
2340                 "Unexpected result for command '" << op.command <<"': "
2341                 << ret << " Expected was: "<< op.expected_result);
2342     }
2343 }
2344
2345 RUNNER_MULTIPROCESS_TEST(security_manager_21_security_manager_admin_deny_user_priv)
2346 {
2347     const int BUFFER_SIZE = 128;
2348     struct message {
2349         uid_t uid;
2350         gid_t gid;
2351         char buf[BUFFER_SIZE];
2352     } msg;
2353
2354     privileges_t admin_required_privs = {
2355             "http://tizen.org/privilege/systemsettings.admin",
2356             "http://tizen.org/privilege/systemsettings"};
2357     privileges_t manifest_privs = {
2358             "http://tizen.org/privilege/internet",
2359             "http://tizen.org/privilege/camera"};
2360     privileges_t real_privs_allow = {"http://tizen.org/privilege/camera"};
2361     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2362
2363     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2364     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2365     const std::string app_id = "sm_test_13_SOME_APP";
2366     const std::string pkg_id = "sm_test_13_SOME_PKG";
2367
2368     int pipefd[2];
2369     pid_t pid;
2370     int result = 0;
2371
2372     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2373     pid = fork();
2374     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2375     if (pid != 0)//parent process
2376     {
2377         std::string childuidstr;
2378         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, true);
2379         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, true);
2380
2381         InstallRequest request,request2;
2382         FdUniquePtr pipeptr(pipefd+1);
2383         close(pipefd[0]);
2384
2385         admin.create();
2386         child.create();
2387         child.getUidString(childuidstr);
2388
2389         //install privacy manager for admin
2390         request.setAppId(pirivman_id.c_str());
2391         request.setPkgId(pirivman_pkg_id.c_str());
2392         request.setUid(admin.getUid());
2393         for (auto &priv: admin_required_privs)
2394             request.addPrivilege(priv.c_str());
2395         Api::install(request);
2396
2397         //install app for child that has internet privilege
2398         request2.setAppId(app_id.c_str());
2399         request2.setPkgId(pkg_id.c_str());
2400         request2.setUid(child.getUid());
2401         for (auto &priv: manifest_privs)
2402             request2.addPrivilege(priv.c_str());
2403         Api::install(request2);
2404
2405         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2406                               manifest_privs, SM_NO_PRIVILEGES);
2407
2408         //send info to child
2409         msg.uid = admin.getUid();
2410         msg.gid = admin.getGid();
2411         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2412
2413         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2414         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2415
2416         //wait for child
2417         RUNNER_ASSERT_MSG(wait(&result) == pid, "wait failed");
2418
2419         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2420                               real_privs_allow, real_privs_deny);
2421     }
2422     if (pid == 0)//child
2423     {
2424         FdUniquePtr pipeptr(pipefd);
2425         close(pipefd[1]);
2426
2427         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2428         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2429
2430         //become admin privacy manager manager
2431         Api::setProcessLabel(pirivman_id.c_str());
2432         result = drop_root_privileges(msg.uid, msg.gid);
2433         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2434         PolicyRequest addPolicyReq;
2435         //change rights
2436         for (auto &denypriv:real_privs_deny) {
2437             /*this entry will deny some privileges for user whose uid (as c string)
2438               was sent in message's buf field.
2439               That user would be denying internet for child in this case*/
2440             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2441             entry.setMaxLevel("Deny");
2442             addPolicyReq.addEntry(entry);
2443         }
2444         Api::sendPolicy(addPolicyReq);
2445         exit(0);
2446     }
2447 }
2448
2449 void saveMappingsToDb(const std::string &version_from, const std::string &version_to,
2450                       const privileges_t &privileges, const std::vector<privileges_t> &mappings) {
2451     TestSecurityManagerDatabase db;
2452     RUNNER_ASSERT_MSG(privileges.size() == mappings.size(), "Wrong given privileges and mappings size");
2453     auto privIt = privileges.begin();
2454     auto mappIt = mappings.begin();
2455     for (; privIt != privileges.end() && mappIt != mappings.end(); privIt++, mappIt++) {
2456         for (const auto &mapping : *mappIt) {
2457             db.setup_privilege_mapping(version_from, version_to, *privIt, mapping);
2458         }
2459     }
2460 }
2461
2462 void saveDefaultMappingsToDb(const std::string &version_from, const std::string &version_to,
2463                              const privileges_t &privileges) {
2464     TestSecurityManagerDatabase db;
2465     for (auto &privilege : privileges) {
2466         db.setup_default_version_privilege(version_from, version_to, privilege);
2467     }
2468 }
2469
2470 void concatUnique(privileges_t &to, const privileges_t &from) {
2471     to.reserve(to.size() + from.size());
2472     for (auto &new_priv : from) {
2473         if (std::find(to.begin(), to.end(), new_priv) == to.end())
2474             to.push_back(new_priv);
2475     }
2476 }
2477
2478 RUNNER_TEST(security_manager_22_get_privilege_mappings)
2479 {
2480     saveMappingsToDb(OLD_VERSION, NEW_VERSION, OLD_PRIVILEGES, NEW_PRIVILEGES);
2481     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2482     privileges_t retrievedMapping;
2483     std::string current;
2484     auto expectedIt = NEW_PRIVILEGES.begin();
2485     for (const auto &privilege : OLD_PRIVILEGES) {
2486         retrievedMapping.clear();
2487         std::vector<std::string> privilegeToMap = {privilege};
2488         Api::getPrivilegesMappings(OLD_VERSION.c_str(), NEW_VERSION.c_str(),
2489                                    privilegeToMap, retrievedMapping);
2490         std::vector<std::string> expectedPrivileges = *expectedIt;
2491         concatUnique(expectedPrivileges, DEFAULT_PRIVILEGES);
2492         RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2493                           "Wrong count of mappings returned for " << privilege << "."
2494                           " Got " << retrievedMapping.size()
2495                           << " expected " << expectedPrivileges.size());
2496         RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2497                           "Wrong mapping returned for " << privilege);
2498         ++expectedIt;
2499     }
2500 }
2501
2502 RUNNER_TEST(security_manager_23_get_privileges_mappings)
2503 {
2504     saveMappingsToDb(OLD_VERSION, NEW_VERSION, OLD_PRIVILEGES, NEW_PRIVILEGES);
2505     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2506
2507     std::vector<std::string> retrievedMapping;
2508     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2509     for(auto &expected : NEW_PRIVILEGES) {
2510         concatUnique(expectedPrivileges, expected);
2511     }
2512     const std::vector<std::string> &privilegesToMap = OLD_PRIVILEGES;
2513
2514     Api::getPrivilegesMappings(OLD_VERSION.c_str(), NEW_VERSION.c_str(), privilegesToMap, retrievedMapping);
2515     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2516                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2517                       << " expected " << expectedPrivileges.size());
2518     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2519                       "Wrong mapping returned for privileges set");
2520 }
2521
2522 RUNNER_TEST(security_manager_24_get_privileges_mappings_default_version)
2523 {
2524     saveMappingsToDb(OLD_VERSION, NEW_VERSION, OLD_PRIVILEGES, NEW_PRIVILEGES);
2525     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2526
2527     std::vector<std::string> retrievedMapping;
2528     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2529     for(auto &expected : NEW_PRIVILEGES) {
2530         concatUnique(expectedPrivileges, expected);
2531     }
2532     const std::vector<std::string> &privilegesToMap = OLD_PRIVILEGES;
2533
2534     Api::getPrivilegesMappings(OLD_VERSION.c_str(), nullptr, privilegesToMap, retrievedMapping);
2535     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2536                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2537                       << " expected " << expectedPrivileges.size());
2538     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2539                       "Wrong mapping returned for privileges set");
2540 }
2541
2542 RUNNER_TEST(security_manager_25_get_default_mappings)
2543 {
2544     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2545
2546     std::vector<std::string> retrievedMapping;
2547     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2548
2549     // Empty privilege to map vector will indicate nullptr privilege array in security-manager API
2550     std::vector<std::string> privilegeToMap;
2551
2552     Api::getPrivilegesMappings(OLD_VERSION.c_str(), NEW_VERSION.c_str(), privilegeToMap, retrievedMapping);
2553     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2554                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2555                       << " expected " << expectedPrivileges.size());
2556     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2557                       "Wrong default mapping returned");
2558 }
2559
2560 RUNNER_TEST(security_manager_26_get_default_mappings_default_version)
2561 {
2562     saveDefaultMappingsToDb(OLD_VERSION, NEW_VERSION, DEFAULT_PRIVILEGES);
2563
2564     std::vector<std::string> retrievedMapping;
2565     std::vector<std::string> expectedPrivileges = DEFAULT_PRIVILEGES;
2566
2567     // Empty privilege to map vector will indicate nullptr privilege array in security-manager API
2568     std::vector<std::string> privilegeToMap;
2569
2570     Api::getPrivilegesMappings(OLD_VERSION.c_str(), nullptr, privilegeToMap, retrievedMapping);
2571     RUNNER_ASSERT_MSG(retrievedMapping.size() == expectedPrivileges.size(),
2572                       "Wrong count of mappings returned. Got " << retrievedMapping.size()
2573                       << " expected " << expectedPrivileges.size());
2574     RUNNER_ASSERT_MSG(std::is_permutation(retrievedMapping.begin(), retrievedMapping.end(), expectedPrivileges.begin()),
2575                       "Wrong default mapping returned");
2576 }
2577
2578 namespace {
2579 const int sm_app_shared_test_id = 27;
2580 const char *const sm_app_shared_id = "sm_test_27_app_id_full";
2581 const char *const sm_app_shared_another_in_package_id = "sm_test_27_app_2_id_full";
2582 const char *const sm_pkg_shared_id = "sm_test_27_pkg_id_full";
2583
2584 void test_success_worker(const std::string &appName, int test_num)
2585 {
2586     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2587
2588     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2589
2590     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1,
2591         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName << " failed " << " to " << SM_OWNER_RW_OTHERS_RO_PATH );
2592 }
2593
2594 void test_fail_worker(const std::string &appName, int test_num)
2595 {
2596     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2597
2598     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2599
2600     RUNNER_ASSERT_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) == -1,
2601         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName
2602         << " surprisingly succeeded, while expecting fail");
2603 }
2604 }
2605
2606 RUNNER_TEST(security_manager_27a_API2X_app_install)
2607 {
2608     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2609     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2610     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2611     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2612     prepare_app_env(sm_app_shared_test_id, true);
2613
2614     // install other apps
2615     for(const auto &app : MANY_APPS_PKGS) {
2616         InstallRequest requestInst;
2617         requestInst.setAppId(app.first.c_str());
2618         requestInst.setPkgId(app.second.package.c_str());
2619         requestInst.setAppTizenVersion(app.second.Tizen_ver.c_str());
2620
2621         Api::install(requestInst);
2622     };
2623
2624     // install
2625     {
2626         InstallRequest requestInst;
2627         requestInst.setAppId(sm_app_shared_id);
2628         requestInst.setPkgId(sm_pkg_shared_id);
2629         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2630         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2631         requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2632         requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2633         requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2634         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2635         requestInst.setAppTizenVersion("2.4");
2636         Api::install(requestInst);
2637     }
2638
2639     // another app in package
2640     {
2641         InstallRequest requestInst;
2642         requestInst.setAppId(sm_app_shared_another_in_package_id);
2643         requestInst.setPkgId(sm_pkg_shared_id);
2644         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2645         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2646         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2647         requestInst.setAppTizenVersion("2.4");
2648         Api::install(requestInst);
2649     }
2650
2651     /* Check records in the security-manager database */
2652     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2653                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2654     /* Check records in the security-manager database */
2655     check_app_after_install(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2656                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2657
2658     /* TODO: add parameters to this function */
2659     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2660
2661     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");
2662 }
2663
2664 RUNNER_CHILD_TEST(security_manager_27b_owner_1_have_access)
2665 {
2666     test_success_worker(sm_app_shared_id, sm_app_shared_test_id);
2667 }
2668
2669 RUNNER_CHILD_TEST(security_manager_27c_owner_2_have_access)
2670 {
2671     test_success_worker(sm_app_shared_another_in_package_id, sm_app_shared_test_id);
2672 }
2673
2674 RUNNER_CHILD_TEST(security_manager_27d_API2X_apps_have_access_app_1)
2675 {
2676     test_success_worker("security_manager_10_app_1", sm_app_shared_test_id);
2677 }
2678
2679 RUNNER_CHILD_TEST(security_manager_27e_API2X_apps_dont_have_access_app_2)
2680 {
2681     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2682 }
2683
2684 RUNNER_CHILD_TEST(security_manager_27f_API2X_apps_have_access_app_3)
2685 {
2686     test_success_worker("security_manager_10_app_3", sm_app_shared_test_id);
2687 }
2688
2689 RUNNER_CHILD_TEST(security_manager_27g_API2X_apps_dont_have_access_app_4)
2690 {
2691     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2692 }
2693
2694 RUNNER_CHILD_TEST(security_manager_27h_API2X_apps_have_access_app_5)
2695 {
2696     test_success_worker("security_manager_10_app_5", sm_app_shared_test_id);
2697 }
2698
2699
2700 RUNNER_TEST(security_manager_27i_API2X_app_uninstall)
2701 {
2702     {
2703         InstallRequest requestUninst;
2704         requestUninst.setAppId(sm_app_shared_id);
2705         Api::uninstall(requestUninst);
2706     }
2707     {
2708         InstallRequest requestUninst;
2709         requestUninst.setAppId(sm_app_shared_another_in_package_id);
2710         Api::uninstall(requestUninst);
2711     }
2712
2713     /* Check records in the security-manager database,
2714      * all previously allowed privileges should be removed */
2715     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2716                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2717     check_app_after_uninstall(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2718                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2719 }
2720
2721 RUNNER_TEST(security_manager_27j_API30_app_install)
2722 {
2723     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2724     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2725     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2726     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2727     prepare_app_env(sm_app_shared_test_id, true);
2728
2729     // install
2730     InstallRequest requestInst;
2731     requestInst.setAppId(sm_app_shared_id);
2732     requestInst.setPkgId(sm_pkg_shared_id);
2733     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2734     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2735     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2736     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2737     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2738     requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2739     requestInst.setAppTizenVersion("3.0");
2740
2741     Api::install(requestInst);
2742
2743     /* Check records in the security-manager database */
2744     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2745                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2746
2747     /* TODO: add parameters to this function */
2748     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2749
2750     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");
2751 }
2752
2753 RUNNER_CHILD_TEST(security_manager_27k_API30_apps_dont_have_access_app_1)
2754 {
2755     test_fail_worker("security_manager_10_app_1", sm_app_shared_test_id);
2756 }
2757
2758 RUNNER_CHILD_TEST(security_manager_27l_API30_apps_dont_have_access_app_2)
2759 {
2760     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2761 }
2762
2763 RUNNER_CHILD_TEST(security_manager_27m_API30_apps_dont_have_access_app_3)
2764 {
2765     test_fail_worker("security_manager_10_app_3", sm_app_shared_test_id);
2766 }
2767
2768 RUNNER_CHILD_TEST(security_manager_27n_API30_apps_dont_have_access_app_4)
2769 {
2770     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2771 }
2772
2773 RUNNER_CHILD_TEST(security_manager_27o_API30_apps_dont_have_access_app_5)
2774 {
2775     test_fail_worker("security_manager_10_app_5", sm_app_shared_test_id);
2776 }
2777
2778 RUNNER_TEST(security_manager_27p_API30_app_uninstall)
2779 {
2780     InstallRequest requestUninst;
2781     requestUninst.setAppId(sm_app_shared_id);
2782
2783     Api::uninstall(requestUninst);
2784
2785     /* Check records in the security-manager database,
2786      * all previously allowed privileges should be removed */
2787     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2788                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2789
2790     // install other apps
2791     for(const auto &app : MANY_APPS_PKGS) {
2792         InstallRequest requestUninst;
2793         requestUninst.setAppId(app.first);
2794
2795         Api::uninstall(requestUninst);
2796     };
2797 }
2798
2799 namespace {
2800 const char *const owner_access = "rwxat";
2801 const char *const target_path_access = "rxl";
2802 const char *const target_dir_access = "x";
2803 const char *const no_access = "";
2804
2805 void check_system_access(const std::string pathLabel, bool apply = true) {
2806     check_exact_smack_accesses("User", pathLabel, (apply ? owner_access : no_access));
2807     check_exact_smack_accesses("System", pathLabel, (apply ? owner_access : no_access));
2808 }
2809
2810 void check_owner_access(const std::string &ownerLabel, const std::string &pathLabel, bool apply = true) {
2811     check_exact_smack_accesses(ownerLabel, pathLabel, (apply ? owner_access : no_access));
2812 }
2813
2814 void check_target_access(const std::string &ownerPkgLabel, const std::string &targetLabel,
2815         const std::string &pathLabel, bool pathShared = true, bool anyPathShared = true) {
2816     check_exact_smack_accesses(targetLabel, pathLabel, (pathShared ? target_path_access : no_access));
2817     check_exact_smack_accesses(targetLabel, ownerPkgLabel, (anyPathShared ? target_dir_access : no_access));
2818 }
2819
2820 void check_path_label(const std::string &path, const std::string &expectedLabel) {
2821     char *label = nullptr;
2822     int ret = smack_new_label_from_path(path.c_str(), XATTR_NAME_SMACK, 0, &label);
2823     RUNNER_ASSERT_MSG(ret > 0, "smack_new_label_from_path failed for " << path);
2824     SmackLabelPtr realLabel(label);
2825     RUNNER_ASSERT_MSG(realLabel.get() == expectedLabel, "Fetched label from " << path << " different"
2826             " than expected, is : " << realLabel.get() << " should be " << expectedLabel);
2827 }
2828
2829 void createFile(const std::string &filePath)
2830 {
2831     //create temporary file and set label for it
2832     mode_t systemMask;
2833
2834     unlink(filePath.c_str());
2835     //allow to create file with 777 rights
2836     systemMask = umask(0000);
2837     int fd = open(filePath.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
2838     //restore system mask
2839     umask(systemMask);
2840     RUNNER_ASSERT_ERRNO_MSG(fd > -1, "Unable to create file for tests");
2841
2842     //for descriptor protection
2843     FdUniquePtr fd_ptr(&fd);
2844
2845     //change owner and group to user APP
2846     int ret = chown(filePath.c_str(), APP_UID, APP_GID);
2847     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "Unable to change file owner");
2848 }
2849
2850 }
2851
2852 RUNNER_TEST(security_manager_30a_send_incomplete_req1)
2853 {
2854     SharingRequest request;
2855     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2856     request.setOwnerAppId("someOwner");
2857     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2858     request.setTargetAppId("someTarget");
2859     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2860 }
2861
2862 RUNNER_TEST(security_manager_30b_send_incomplete_req2)
2863 {
2864     SharingRequest request;
2865     request.setTargetAppId("someTarget");
2866     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2867     request.setOwnerAppId("someOwner");
2868     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2869 }
2870
2871 RUNNER_TEST(security_manager_30c_send_incomplete_req3)
2872 {
2873     SharingRequest request;
2874     const char *somePaths[] = {"path1", "path2"};
2875     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2876     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2877     request.setOwnerAppId("someOwner");
2878     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2879 }
2880
2881 RUNNER_TEST(security_manager_30d_unknown_owner)
2882 {
2883     // This test depends on order of checks in security-manager service implementation
2884     SharingRequest request;
2885     request.setOwnerAppId("ImPrettySureIDontExist");
2886     request.setTargetAppId("IDontMatter");
2887     const char *somePaths[] = {"path1", "path2"};
2888     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2889     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2890 }
2891
2892 RUNNER_TEST(security_manager_30e_unknown_target)
2893 {
2894     // This test depends on order of checks in security-manager service implementation
2895     AppInstallHelper owner("installedApp");
2896     owner.revokeRules();
2897     owner.createInstallDir();
2898     InstallRequest ownerInst;
2899     ownerInst.setAppId(owner.getAppId());
2900     ownerInst.setPkgId(owner.getPkgId());
2901     Api::install(ownerInst);
2902
2903     SharingRequest request;
2904     request.setOwnerAppId(owner.getAppId());
2905     request.setTargetAppId("NowImPrettySureIDontExist");
2906     const char *somePaths[] = {"path1", "path2"};
2907     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2908     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2909
2910     Api::uninstall(ownerInst);
2911 }
2912
2913 RUNNER_TEST(security_manager_30f_bad_paths)
2914 {
2915     // This test depends on order of checks in security-manager service implementation
2916     AppInstallHelper owner("installedApp");
2917     owner.revokeRules();
2918     owner.createInstallDir();
2919     InstallRequest ownerInst;
2920     ownerInst.setAppId(owner.getAppId());
2921     ownerInst.setPkgId(owner.getPkgId());
2922     Api::install(ownerInst);
2923
2924     AppInstallHelper target("secondInstalledApp");
2925     target.revokeRules();
2926     target.createInstallDir();
2927     InstallRequest targetInst;
2928     targetInst.setAppId(target.getAppId());
2929     targetInst.setPkgId(target.getPkgId());
2930     Api::install(targetInst);
2931
2932     SharingRequest request;
2933     request.setOwnerAppId(owner.getAppId());
2934     request.setTargetAppId(target.getAppId());
2935
2936     const char *somePath = "/tmp/somePath";
2937     createFile(somePath);
2938     const char *somePaths[] = {somePath};
2939     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2940     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_NOT_PATH_OWNER);
2941
2942     Api::uninstall(ownerInst);
2943 }
2944
2945 RUNNER_TEST(security_manager_31_simple_share)
2946 {
2947     std::vector<AppInstallHelper> helper {{"app30a"}, {"app30b"}};
2948     auto &owner = helper[0];
2949     auto &target = helper[1];
2950
2951     for (auto &e : helper) {
2952         e.revokeRules();
2953         e.createInstallDir();
2954     }
2955
2956     owner.createPrivateDir();
2957     owner.createSharedFile();
2958
2959     InstallRequest ownerReq;
2960     ownerReq.setAppId(owner.getAppId());
2961     ownerReq.setPkgId(owner.getPkgId());
2962     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
2963     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
2964     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
2965     Api::install(ownerReq);
2966
2967     InstallRequest targetReq;
2968     targetReq.setAppId(target.getAppId());
2969     targetReq.setPkgId(target.getAppId());
2970     Api::install(targetReq);
2971
2972     SharingRequest share1;
2973     std::string sharedPath = owner.getSharedPath();
2974     share1.setOwnerAppId(owner.getAppId());
2975     share1.setTargetAppId(target.getAppId());
2976     const char *path[] = {sharedPath.c_str()};
2977     share1.addPaths(path, 1);
2978     Api::applySharing(share1);
2979
2980     TestSecurityManagerDatabase db;
2981     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
2982     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
2983
2984     check_system_access(pathLabel1);
2985     check_owner_access(owner.generateAppLabel(), pathLabel1);
2986     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
2987     check_path_label(sharedPath, pathLabel1);
2988
2989     Api::dropSharing(share1);
2990     check_system_access(pathLabel1, false);
2991     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
2992     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
2993     check_path_label(sharedPath, owner.generatePkgLabel());
2994
2995     Api::uninstall(ownerReq);
2996     Api::uninstall(targetReq);
2997 }
2998
2999 RUNNER_TEST(security_manager_32_double_share)
3000 {
3001     std::vector<AppInstallHelper> helper {{"app31a"}, {"app31b"}};
3002     auto &owner = helper[0];
3003     auto &target = helper[1];
3004
3005     // cleanup
3006     for (auto &e : helper) {
3007         e.revokeRules();
3008         e.createInstallDir();
3009     }
3010     owner.createPrivateDir();
3011     owner.createSharedFile();
3012
3013     InstallRequest ownerReq;
3014     ownerReq.setAppId(owner.getAppId());
3015     ownerReq.setPkgId(owner.getPkgId());
3016     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
3017
3018     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3019     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3020     Api::install(ownerReq);
3021
3022     InstallRequest targetReq;
3023     targetReq.setAppId(target.getAppId());
3024     targetReq.setPkgId(target.getAppId());
3025     Api::install(targetReq);
3026
3027     SharingRequest share1;
3028     std::string sharedPath = owner.getSharedPath(0);
3029     share1.setOwnerAppId(owner.getAppId());
3030     share1.setTargetAppId(target.getAppId());
3031     const char *path[] = {sharedPath.c_str()};
3032     share1.addPaths(path, 1);
3033     Api::applySharing(share1);
3034
3035     TestSecurityManagerDatabase db;
3036     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3037     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3038
3039     check_system_access(pathLabel);
3040     check_owner_access(owner.generateAppLabel(), pathLabel);
3041     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3042     check_path_label(sharedPath, pathLabel);
3043
3044     Api::applySharing(share1);
3045     check_system_access(pathLabel);
3046     check_owner_access(owner.generateAppLabel(), pathLabel);
3047     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3048     check_path_label(sharedPath, pathLabel);
3049
3050     Api::dropSharing(share1);
3051     check_system_access(pathLabel);
3052     check_owner_access(owner.generateAppLabel(), pathLabel);
3053     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3054     check_path_label(sharedPath, pathLabel);
3055
3056     Api::dropSharing(share1);
3057     check_system_access(pathLabel, false);
3058     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3059     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel, false, false);
3060     check_path_label(sharedPath, owner.generatePkgLabel());
3061
3062     Api::uninstall(ownerReq);
3063     Api::uninstall(targetReq);
3064 }
3065 RUNNER_TEST(security_manager_33_share_two_with_one)
3066 {
3067     std::vector<AppInstallHelper> helper {{"app32a"}, {"app32b"}};
3068     auto &owner = helper[0];
3069     auto &target = helper[1];
3070
3071     // cleanup
3072     for (auto &e : helper) {
3073         e.revokeRules();
3074         e.createInstallDir();
3075     }
3076     owner.createPrivateDir();
3077     owner.createSharedFile(0);
3078     owner.createSharedFile(1);
3079
3080     InstallRequest ownerReq;
3081     ownerReq.setAppId(owner.getAppId());
3082     ownerReq.setPkgId(owner.getPkgId());
3083     ownerReq.addPath(owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW);
3084     ownerReq.addPath(owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW);
3085
3086     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3087     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3088     Api::install(ownerReq);
3089
3090     InstallRequest targetReq;
3091     targetReq.setAppId(target.getAppId());
3092     targetReq.setPkgId(target.getAppId());
3093     Api::install(targetReq);
3094
3095     SharingRequest share1, share2;
3096     std::string sharedPath1 = owner.getSharedPath(0);
3097     std::string sharedPath2 = owner.getSharedPath(1);
3098     share1.setOwnerAppId(owner.getAppId());
3099     share2.setOwnerAppId(owner.getAppId());
3100     share1.setTargetAppId(target.getAppId());
3101     share2.setTargetAppId(target.getAppId());
3102     const char *path1[] = {sharedPath1.c_str()};
3103     const char *path2[] = {sharedPath2.c_str()};
3104     share1.addPaths(path1, 1);
3105     share2.addPaths(path2, 1);
3106
3107     Api::applySharing(share1);
3108     TestSecurityManagerDatabase db;
3109     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3110     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3111
3112     check_system_access(pathLabel1);
3113     check_owner_access(owner.generateAppLabel(), pathLabel1);
3114     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3115     check_path_label(sharedPath1, pathLabel1);
3116
3117     Api::applySharing(share2);
3118     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3119     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3120     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for private shared paths should be unique!");
3121
3122     check_system_access(pathLabel1);
3123     check_system_access(pathLabel2);
3124     check_owner_access(owner.generateAppLabel(), pathLabel1);
3125     check_owner_access(owner.generateAppLabel(), pathLabel2);
3126     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3127     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3128     check_path_label(sharedPath1, pathLabel1);
3129     check_path_label(sharedPath2, pathLabel2);
3130
3131     Api::dropSharing(share1);
3132     check_system_access(pathLabel1, false);
3133     check_system_access(pathLabel2);
3134     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3135     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false);
3136     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3137     check_path_label(sharedPath1, owner.generatePkgLabel());
3138     check_path_label(sharedPath2, pathLabel2);
3139
3140     Api::dropSharing(share2);
3141     check_system_access(pathLabel1, false);
3142     check_system_access(pathLabel2, false);
3143     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3144     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3145     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3146     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2, false, false);
3147     check_path_label(sharedPath1, owner.generatePkgLabel());
3148     check_path_label(sharedPath2, owner.generatePkgLabel());
3149
3150     Api::uninstall(ownerReq);
3151     Api::uninstall(targetReq);
3152 }
3153
3154 RUNNER_TEST(security_manager_34_share_one_with_two)
3155 {
3156     std::vector<AppInstallHelper> helper {{"app33a"}, {"app33b"}, {"app33c"}};
3157     auto &owner = helper[0];
3158     auto &target1 = helper[1];
3159     auto &target2 = helper[2];
3160
3161     // cleanup
3162     for (auto &e : helper) {
3163         e.revokeRules();
3164         e.createInstallDir();
3165     }
3166     owner.createPrivateDir();
3167     owner.createSharedFile();
3168
3169     InstallRequest ownerReq;
3170     ownerReq.setAppId(owner.getAppId());
3171     ownerReq.setPkgId(owner.getPkgId());
3172     ownerReq.addPath(owner.getSharedPath(), SECURITY_MANAGER_PATH_RW);
3173     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3174     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3175     Api::install(ownerReq);
3176
3177     for (size_t i = 1; i < helper.size(); i++) {
3178         InstallRequest targetReq;
3179         targetReq.setAppId(helper[i].getAppId());
3180         targetReq.setPkgId(helper[i].getAppId());
3181         Api::install(targetReq);
3182     }
3183
3184     SharingRequest share1, share2;
3185     std::string sharedPath = owner.getSharedPath(0).c_str();
3186     share1.setOwnerAppId(owner.getAppId());
3187     share2.setOwnerAppId(owner.getAppId());
3188     share1.setTargetAppId(target1.getAppId());
3189     share2.setTargetAppId(target2.getAppId());
3190
3191     const char *path[] = {sharedPath.c_str()};
3192     share1.addPaths(path, 1);
3193     share2.addPaths(path, 1);
3194
3195     Api::applySharing(share1);
3196     TestSecurityManagerDatabase db;
3197     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3198     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3199
3200     check_system_access(pathLabel);
3201     check_owner_access(owner.generateAppLabel(), pathLabel);
3202     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3203     check_path_label(sharedPath, pathLabel);
3204
3205     Api::applySharing(share2);
3206     check_system_access(pathLabel);
3207     check_owner_access(owner.generateAppLabel(), pathLabel);
3208     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3209     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3210     check_path_label(sharedPath, pathLabel);
3211
3212     Api::dropSharing(share1);
3213     check_system_access(pathLabel);
3214     check_owner_access(owner.generateAppLabel(), pathLabel);
3215     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3216     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3217     check_path_label(sharedPath, pathLabel);
3218
3219     Api::dropSharing(share2);
3220     check_system_access(pathLabel, false);
3221     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3222     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3223     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel, false, false);
3224     check_path_label(sharedPath, owner.generatePkgLabel());
3225
3226     Api::uninstall(ownerReq);
3227     for (size_t i = 1; i < helper.size(); i++) {
3228         InstallRequest targetReq;
3229         targetReq.setAppId(helper[i].getAppId());
3230         targetReq.setPkgId(helper[i].getAppId());
3231         Api::uninstall(targetReq);
3232     }
3233 }
3234
3235 RUNNER_TEST(security_manager_35_share_two_with_two)
3236 {
3237     std::vector<AppInstallHelper> helper {{"app34a"}, {"app34b"}, {"app34c"}};
3238     auto &owner = helper[0];
3239     auto &target1 = helper[1];
3240     auto &target2 = helper[2];
3241
3242     // cleanup
3243     for (auto &e : helper) {
3244         e.revokeRules();
3245         e.createInstallDir();
3246     }
3247     owner.createPrivateDir();
3248     owner.createSharedFile(0);
3249     owner.createSharedFile(1);
3250
3251     InstallRequest ownerReq;
3252     ownerReq.setAppId(owner.getAppId());
3253     ownerReq.setPkgId(owner.getPkgId());
3254     ownerReq.addPath(owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW);
3255     ownerReq.addPath(owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW);
3256
3257     int result = nftw(owner.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3258     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << owner.getInstallDir());
3259     Api::install(ownerReq);
3260
3261     for (size_t i = 1; i < helper.size(); i++) {
3262         InstallRequest targetReq;
3263         targetReq.setAppId(helper[i].getAppId());
3264         targetReq.setPkgId(helper[i].getAppId());
3265         Api::install(targetReq);
3266     }
3267
3268     SharingRequest share1, share2;
3269     std::string sharedPath1 = owner.getSharedPath(0).c_str();
3270     std::string sharedPath2 = owner.getSharedPath(1).c_str();
3271     share1.setOwnerAppId(owner.getAppId());
3272     share2.setOwnerAppId(owner.getAppId());
3273     share1.setTargetAppId(target1.getAppId());
3274     share2.setTargetAppId(target2.getAppId());
3275
3276     const char *path1[] = {sharedPath1.c_str()};
3277     const char *path2[] = {sharedPath2.c_str()};
3278     share1.addPaths(path1, 1);
3279     share2.addPaths(path2, 1);
3280
3281     Api::applySharing(share1);
3282     TestSecurityManagerDatabase db;
3283     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3284     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3285
3286     check_system_access(pathLabel1);
3287     check_owner_access(owner.generateAppLabel(), pathLabel1);
3288     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3289     check_path_label(sharedPath1, pathLabel1);
3290
3291     Api::applySharing(share2);
3292     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3293     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3294     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for shared files should be unique!");
3295
3296     check_system_access(pathLabel1);
3297     check_system_access(pathLabel2);
3298     check_owner_access(owner.generateAppLabel(), pathLabel1);
3299     check_owner_access(owner.generateAppLabel(), pathLabel2);
3300     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3301     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2);
3302     check_path_label(sharedPath1, pathLabel1);
3303     check_path_label(sharedPath2, pathLabel2);
3304
3305     Api::dropSharing(share2);
3306     check_system_access(pathLabel1);
3307     check_system_access(pathLabel2, false);
3308     check_owner_access(owner.generateAppLabel(), pathLabel1);
3309     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3310     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3311     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3312     check_path_label(sharedPath1, pathLabel1);
3313     check_path_label(sharedPath2, owner.generatePkgLabel());
3314
3315     Api::dropSharing(share1);
3316     check_system_access(pathLabel1, false);
3317     check_system_access(pathLabel2, false);
3318     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3319     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3320     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1, false, false);
3321     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3322     check_path_label(sharedPath1, owner.generatePkgLabel());
3323     check_path_label(sharedPath2, owner.generatePkgLabel());
3324     Api::uninstall(ownerReq);
3325     for (size_t i = 1; i < helper.size(); i++) {
3326         InstallRequest targetReq;
3327         targetReq.setAppId(helper[i].getAppId());
3328         targetReq.setPkgId(helper[i].getAppId());
3329         Api::uninstall(targetReq);
3330     }
3331 }
3332
3333 RUNNER_TEST(security_manager_40_set_wrong_author_id)
3334 {
3335     InstallRequest requestInst;
3336
3337     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3338         security_manager_app_inst_req_set_author_id(requestInst.get(), NULL));
3339
3340     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3341         security_manager_app_inst_req_set_author_id(requestInst.get(), ""));
3342 }
3343
3344 RUNNER_TEST(security_manager_41_set_author_id_multiple_times)
3345 {
3346     for(unsigned int i=0; i<10; ++i) {
3347         std::string authorId = "some-author-id" + std::to_string(i);
3348
3349         InstallRequest requestInst;
3350         requestInst.setAuthorId(authorId);
3351     }
3352 }
3353
3354 RUNNER_TEST(security_manager_43_app_install_with_trusted_path)
3355 {
3356     std::vector<AppInstallHelper> helper {{"app43a"}, {"app43b"}, {"app43c"}};
3357     auto &provider  = helper[0];
3358     auto &user      = helper[1];
3359     auto &untrusted = helper[2];
3360
3361     TestSecurityManagerDatabase dbtest;
3362     const char *author_id = "custom_author_id_test 41";
3363
3364     const char *const trusted_access = "rwxatl";
3365     const char *const system_access = "rwxatl";
3366
3367     int result;
3368
3369     // cleanup
3370     for (auto &e : helper) {
3371         e.revokeRules();
3372         e.createInstallDir();
3373         e.createTrustedDir();
3374     }
3375
3376     result = nftw(provider.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3377     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_TRUSTED_PATH);
3378
3379     // install app with shared/trusted dir
3380     InstallRequest trustingApp;
3381     trustingApp.setAppId(provider.getAppId());
3382     trustingApp.setPkgId(provider.getPkgId());
3383     trustingApp.setAuthorId("author id to be overwritten");
3384     trustingApp.setAuthorId(author_id);
3385     trustingApp.addPath(provider.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3386     Api::install(trustingApp);
3387
3388     int64_t authorDb = dbtest.get_author_id(author_id);
3389     const std::string trusted_label = std::string("User::Author::") + std::to_string(authorDb);
3390
3391     // check trusted path label
3392     nftw_expected_label = trusted_label;
3393     nftw_expected_transmute = true;
3394     nftw_expected_exec = false;
3395
3396     // check labels
3397     result = nftw(provider.getTrustedDir().c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
3398     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_TRUSTED_PATH);
3399
3400     // check rules
3401     check_exact_access("System", trusted_label, system_access);
3402     check_exact_access("User", trusted_label, system_access);
3403     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, trusted_access);
3404     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3405
3406     // install trusted app
3407     InstallRequest trustedApp;
3408     trustedApp.setAppId(user.getAppId());
3409     trustedApp.setPkgId(user.getPkgId());
3410     trustedApp.setAuthorId(author_id);
3411     Api::install(trustedApp);
3412
3413     // check rules
3414     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3415     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3416
3417     // install untrusted app
3418     InstallRequest untrustedApp;
3419     untrustedApp.setAppId(untrusted.getAppId());
3420     untrustedApp.setPkgId(untrusted.getPkgId());
3421     Api::install(untrustedApp);
3422
3423     // check rules
3424     check_exact_access(generateAppLabel(untrusted.getAppId()), trusted_label, "");
3425     check_exact_access(generatePkgLabel(untrusted.getPkgId()), trusted_label, "");
3426
3427     // uninstall trusting app
3428     Api::uninstall(trustingApp);
3429
3430     // there's still one app with author id, rules should be kept
3431     check_exact_access("System", trusted_label, system_access);
3432     check_exact_access("User", trusted_label, system_access);
3433     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, "");
3434     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3435     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3436     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3437
3438     Api::uninstall(trustedApp);
3439
3440     // no more apps with author id
3441     check_exact_access("System", trusted_label, "");
3442     check_exact_access("User", trusted_label, "");
3443     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, "");
3444     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3445
3446     Api::uninstall(untrustedApp);
3447 }
3448
3449
3450 RUNNER_TEST(security_manager_44_app_install_with_trusted_path_no_author_id)
3451 {
3452     AppInstallHelper help("app44");
3453     help.createInstallDir();
3454     help.createTrustedDir();
3455
3456     // install app with shared/trusted dir but without authors id
3457     InstallRequest app;
3458     app.setAppId(help.getAppId());
3459     app.setPkgId(help.getPkgId());
3460     app.addPath(help.getTrustedDir(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3461     Api::install(app, SECURITY_MANAGER_ERROR_INPUT_PARAM);
3462 }
3463
3464 int main(int argc, char *argv[])
3465 {
3466     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
3467 }