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