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