Add SM tests for app installation constraints
[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 <regex>
19 #include <string>
20 #include <unordered_set>
21
22 #include <ftw.h>
23 #include <grp.h>
24 #include <pwd.h>
25
26 #include <tzplatform_config.h>
27 #include <security-manager.h>
28
29 #include <access_provider.h>
30 #include <dpl/log/log.h>
31 #include <dpl/test/test_runner.h>
32 #include <passwd_access.h>
33 #include <tests_common.h>
34 #include <sm_api.h>
35 #include <sm_db.h>
36 #include <sm_request.h>
37 #include <sm_sharing_request.h>
38 #include <sm_user_request.h>
39 #include <app_install_helper.h>
40 #include <synchronization_pipe.h>
41 #include <temp_test_user.h>
42 #include <uds.h>
43 #include <cynara_test_client.h>
44 #include <cynara_test_admin.h>
45 #include <service_manager.h>
46 #include <cynara_test_admin.h>
47 #include "memory.h"
48
49 using namespace SecurityManagerTest;
50
51 DEFINE_SMARTPTR(cap_free, _cap_struct, CapsSetsUniquePtr);
52 DEFINE_SMARTPTR(tzplatform_context_destroy, tzplatform_context, TzPlatformContextPtr);
53
54 static const privileges_t SM_ALLOWED_PRIVILEGES = {
55     "http://tizen.org/privilege/display",
56     "http://tizen.org/privilege/nfc"
57 };
58
59 static const privileges_t SM_DENIED_PRIVILEGES  = {
60     "http://tizen.org/privilege/bluetooth",
61     "http://tizen.org/privilege/power"
62 };
63
64 static const privileges_t SM_NO_PRIVILEGES  = {
65 };
66
67 static const std::vector<std::string> SM_ALLOWED_GROUPS = {"db_browser", "db_alarm"};
68
69 void changeSecurityContext(const std::string& label, uid_t uid, gid_t gid)
70 {
71     RUNNER_ASSERT_ERRNO_MSG(0 == smack_set_label_for_self(label.c_str()),
72         "Error in smack_set_label_for_self(" << label << ")");
73
74     RUNNER_ASSERT_ERRNO_MSG(0 == setgid(gid), "Error in setgid.");
75     RUNNER_ASSERT_ERRNO_MSG(0 == setuid(uid), "Error in setuid.");
76 }
77
78 std::string genPath(int app_num, const char *postfix) {
79     char buf[16];
80     sprintf(buf, "%02d", app_num);
81     return std::string("/opt/usr/apps/sm_test_") + std::string(buf) + std::string("_pkg_id_full/") + std::string(postfix);
82 }
83 std::string genRWPath(int app_num) {
84     return genPath(app_num, "app_dir");
85 }
86 std::string genROPath(int app_num) {
87     return genPath(app_num, "app_dir_ro");
88 }
89 std::string genPublicROPath(int app_num) {
90     return genPath(app_num, "app_dir_public_ro");
91 }
92 std::string genOwnerRWOthersROPath(int app_num) {
93     return genPath(app_num, "app_dir_rw_others_ro");
94 }
95
96 static const char *const SM_RW_PATH = "/opt/usr/apps/sm_test_02_pkg_id_full/app_dir";
97
98 static const char *const SM_DENIED_PATH = "/opt/usr/apps/non_app_dir";
99 static const char *const SM_TRUSTED_PATH = "/opt/usr/apps/sm_test_02_pkg_id_full/app_dir_trusted";
100
101 static const char *const ANY_USER_REPRESENTATION = "anyuser";/*this may be actually any string*/
102 static const std::string EXEC_FILE("exec");
103 static const std::string NORMAL_FILE("normal");
104 static const std::string LINK_PREFIX("link_to_");
105
106 static const std::string PRIVILEGE_MANAGER_APP = "privilege_manager";
107 static const std::string PRIVILEGE_MANAGER_PKG = "privilege_manager";
108 static const std::string PRIVILEGE_MANAGER_SELF_PRIVILEGE = "http://tizen.org/privilege/notexist";
109 static const std::string PRIVILEGE_MANAGER_ADMIN_PRIVILEGE = "http://tizen.org/privilege/internal/usermanagement";
110
111 static const std::vector<std::string> MANY_APPS = {
112     "security_manager_10_app_1",
113     "security_manager_10_app_2",
114     "security_manager_10_app_3",
115     "security_manager_10_app_4",
116     "security_manager_10_app_5"
117 };
118
119 struct app_attributes {
120     std::string package;
121     std::string Tizen_ver;
122 };
123 static const std::map<std::string, struct app_attributes> MANY_APPS_PKGS = {
124     {"security_manager_10_app_1", {"security_manager_10_pkg_1", "2.1"}},
125     {"security_manager_10_app_2", {"security_manager_10_pkg_2", "3.0"}},
126     {"security_manager_10_app_3", {"security_manager_10_pkg_3", "2.1.1"}},
127     {"security_manager_10_app_4", {"security_manager_10_pkg_4", "3.1"}},
128     {"security_manager_10_app_5", {"security_manager_10_pkg_5", "2.2"}},
129     {PRIVILEGE_MANAGER_APP, {PRIVILEGE_MANAGER_PKG, "3.0"}}
130 };
131
132 static const std::vector<privileges_t> MANY_APPS_PRIVILEGES = {
133     {
134         "http://tizen.org/privilege/internet",
135         "http://tizen.org/privilege/display"
136     },
137     {
138         "http://tizen.org/privilege/telephony",
139         "http://tizen.org/privilege/datasharing"
140     },
141     {
142         "http://tizen.org/privilege/content.write",
143         "http://tizen.org/privilege/led",
144         "http://tizen.org/privilege/email"
145     },
146     {
147         "http://tizen.org/privilege/led",
148         "http://tizen.org/privilege/email",
149         "http://tizen.org/privilege/telephony",
150         "http://tizen.org/privilege/datasharing"
151     },
152     {
153         "http://tizen.org/privilege/internet",
154         "http://tizen.org/privilege/display",
155         "http://tizen.org/privilege/led",
156         "http://tizen.org/privilege/email"
157     }
158 };
159
160 class ScopedProcessLabel {
161 public:
162     ScopedProcessLabel() {
163         smack_new_label_from_self(&label);
164     }
165
166     ~ScopedProcessLabel() {
167         smack_set_label_for_self(label);
168         free(label);
169     }
170
171 private:
172     char *label;
173 };
174
175 static std::string generateAppLabel(const std::string &appId)
176 {
177     return "User::App::" + appId;
178 }
179
180 static std::string generatePkgLabelOwnerRWothersRO(const std::string &pkgId)
181 {
182     return "User::Pkg::" + pkgId + "::SharedRO";
183 }
184
185 static std::string generatePkgLabel(const std::string &pkgId)
186 {
187     return "User::Pkg::" + pkgId;
188 }
189
190 #define FTW_MAX_FDS 16
191
192 static int nftw_remove_labels(const char *fpath, const struct stat* /*sb*/,
193                        int /*typeflag*/, struct FTW* /*ftwbuf*/)
194 {
195     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_ACCESS);
196     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_EXEC);
197     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_TRANSMUTE);
198
199     return 0;
200 }
201
202 static int nftw_set_labels_non_app_dir(const char *fpath, const struct stat* /*sb*/,
203                                 int /*typeflag*/, struct FTW* /*ftwbuf*/)
204 {
205     smack_lsetlabel(fpath, "canary_label", SMACK_LABEL_ACCESS);
206     smack_lsetlabel(fpath, "canary_label", SMACK_LABEL_EXEC);
207     smack_lsetlabel(fpath, nullptr, SMACK_LABEL_TRANSMUTE);
208
209     return 0;
210 }
211
212 static int nftw_check_labels_non_app_dir(const char *fpath, const struct stat* /*sb*/,
213                                   int /*typeflag*/, struct FTW* /*ftwbuf*/)
214 {
215     int result;
216     CStringPtr labelPtr;
217     char* label = nullptr;
218
219     /* ACCESS */
220     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
221     labelPtr.reset(label);
222     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
223     result = strcmp("canary_label", labelPtr.get());
224     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is overwritten");
225
226     /* EXEC */
227     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
228     labelPtr.reset(label);
229     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
230     result = strcmp("canary_label", labelPtr.get());
231     RUNNER_ASSERT_MSG(result == 0, "EXEC label on " << fpath << " is overwritten");
232
233     /* TRANSMUTE */
234     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
235     labelPtr.reset(label);
236     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
237     RUNNER_ASSERT_MSG(labelPtr.get() == nullptr, "TRANSMUTE label on " << fpath << " is set");
238
239     return 0;
240 }
241
242 static int nftw_check_sm_labels_app_dir(const char *fpath, const struct stat *sb,
243                               const char* correctLabel, bool transmute_test, bool exec_test)
244 {
245     int result;
246     CStringPtr labelPtr;
247     char* label = nullptr;
248
249     /* ACCESS */
250     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_ACCESS);
251     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
252     labelPtr.reset(label);
253     RUNNER_ASSERT_MSG(label != nullptr, "ACCESS label on " << fpath << " is not set");
254     result = strcmp(correctLabel, label);
255     RUNNER_ASSERT_MSG(result == 0, "ACCESS label on " << fpath << " is incorrect"
256             " (should be '" << correctLabel << "' and is '" << label << "')");
257
258
259     /* EXEC */
260     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_EXEC);
261     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
262     labelPtr.reset(label);
263
264     if (S_ISREG(sb->st_mode) && (sb->st_mode & S_IXUSR) && exec_test) {
265         RUNNER_ASSERT_MSG(label != nullptr, "EXEC label on " << fpath << " is not set");
266         result = strcmp(correctLabel, label);
267         RUNNER_ASSERT_MSG(result == 0, "Incorrect EXEC label on executable file " << fpath);
268     } else
269         RUNNER_ASSERT_MSG(label == nullptr, "EXEC label on " << fpath << " is set");
270
271
272     /* TRANSMUTE */
273     result = smack_lgetlabel(fpath, &label, SMACK_LABEL_TRANSMUTE);
274     RUNNER_ASSERT_MSG(result == 0, "Could not get label for the path");
275     labelPtr.reset(label);
276
277     if (S_ISDIR(sb->st_mode) && transmute_test == true) {
278         RUNNER_ASSERT_MSG(label != nullptr, "TRANSMUTE label on " << fpath << " is not set at all");
279         RUNNER_ASSERT_MSG(strcmp(label,"TRUE") == 0,
280                 "TRANSMUTE label on " << fpath << " is not set properly: '"<<label<<"'");
281     } else {
282         RUNNER_ASSERT_MSG(label == nullptr, "TRANSMUTE label on " << fpath << " is set");
283     }
284
285     return 0;
286 }
287
288 // nftw doesn't allow passing user data to functions. Work around by using global variable
289 static std::string nftw_expected_label;
290 bool nftw_expected_transmute;
291 bool nftw_expected_exec;
292
293 static int nftw_check_sm_labels(const char *fpath, const struct stat *sb,
294                                int /*typeflag*/, struct FTW* /*ftwbuf*/)
295 {
296     return nftw_check_sm_labels_app_dir(fpath, sb,
297         nftw_expected_label.c_str(), nftw_expected_transmute, nftw_expected_exec);
298 }
299
300 static void prepare_app_path(int app_num, bool others_enabled = false)
301 {
302     std::string SM_RW_PATH = genRWPath(app_num);
303     std::string SM_RO_PATH = genROPath(app_num);
304     std::string SM_PUBLIC_RO_PATH = genPublicROPath(app_num);
305     int result;
306
307     result = nftw(SM_RW_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
308     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RW_PATH);
309
310     result = nftw(SM_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
311     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_RO_PATH);
312
313     result = nftw(SM_PUBLIC_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
314     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_PUBLIC_RO_PATH);
315
316     if(others_enabled) {
317         std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(app_num);
318         result = nftw(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
319         RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << SM_OWNER_RW_OTHERS_RO_PATH);
320     }
321
322     result = nftw(SM_DENIED_PATH, &nftw_set_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
323     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_DENIED_PATH);
324 }
325
326 static void prepare_app_env(int app_num, bool others_enabled = false)
327 {
328     prepare_app_path(app_num, others_enabled);
329 }
330
331 static void check_app_path_after_install(int app_num, const char *pkgId, bool others_enabled=false)
332 {
333     std::string SM_RW_PATH = genRWPath(app_num);
334     std::string SM_RO_PATH = genROPath(app_num);
335     std::string SM_PUBLIC_RO_PATH = genPublicROPath(app_num);
336     int result;
337
338     nftw_expected_label = generatePkgLabel(pkgId);
339     nftw_expected_transmute = true;
340     nftw_expected_exec = false;
341
342     result = nftw(SM_RW_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
343     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RW_PATH);
344
345     nftw_expected_label = generatePkgLabel(pkgId) + "::RO";
346     nftw_expected_transmute = false;
347     nftw_expected_exec = false;
348
349     result = nftw(SM_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
350     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_RO_PATH);
351
352     nftw_expected_label = "User::Home";
353     nftw_expected_transmute = true;
354     nftw_expected_exec = false;
355
356     result = nftw(SM_PUBLIC_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
357     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_PUBLIC_RO_PATH);
358
359     result = nftw(SM_DENIED_PATH, &nftw_check_labels_non_app_dir, FTW_MAX_FDS, FTW_PHYS);
360     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_DENIED_PATH);
361
362     // owner RW, others RO
363     if(others_enabled) {
364         std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(app_num);
365         nftw_expected_label = generatePkgLabelOwnerRWothersRO(pkgId);
366         nftw_expected_transmute = true;
367         nftw_expected_exec = false;
368
369         result = nftw(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
370         RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_OWNER_RW_OTHERS_RO_PATH);
371     }
372 }
373
374
375 static void check_app_permissions(const char *const app_id, const char *const pkg_id, const char *const user,
376                                   const privileges_t &allowed_privs, const privileges_t &denied_privs)
377 {
378     (void) pkg_id;
379     std::string smackLabel = generateAppLabel(app_id);
380
381     CynaraTestClient::Client ctc;
382
383     for (auto &priv : allowed_privs) {
384         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_ALLOWED);
385     }
386
387     for (auto &priv : denied_privs) {
388         ctc.check(smackLabel.c_str(), "", user, priv.c_str(), CYNARA_API_ACCESS_DENIED);
389     }
390 }
391
392 static void check_app_gids(const char *const app_id, const std::vector<gid_t> &allowed_gids)
393 {
394     int ret;
395     gid_t main_gid = getgid();
396     std::unordered_set<gid_t> reference_gids(allowed_gids.begin(), allowed_gids.end());
397
398     // Reset supplementary groups
399     ret = setgroups(0, NULL);
400     RUNNER_ASSERT_MSG(ret != -1, "Unable to set supplementary groups");
401
402     Api::setProcessGroups(app_id);
403
404     ret = getgroups(0, nullptr);
405     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
406
407     std::vector<gid_t> actual_gids(ret);
408     ret = getgroups(ret, actual_gids.data());
409     RUNNER_ASSERT_MSG(ret != -1, "Unable to get supplementary groups");
410
411     for (const auto &gid : actual_gids) {
412         RUNNER_ASSERT_MSG(gid == main_gid || reference_gids.count(gid) > 0,
413             "Application shouldn't get access to group " << gid);
414         reference_gids.erase(gid);
415     }
416
417     RUNNER_ASSERT_MSG(reference_gids.empty(), "Application didn't get access to some groups");
418 }
419
420 static void check_app_after_install(const char *const app_id, const char *const pkg_id,
421                                     const privileges_t &allowed_privs,
422                                     const privileges_t &denied_privs,
423                                     const std::vector<std::string> &allowed_groups)
424 {
425     TestSecurityManagerDatabase dbtest;
426     dbtest.test_db_after__app_install(app_id, pkg_id);
427
428     /*Privileges should be granted to all users if root installs app*/
429     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, allowed_privs, denied_privs);
430
431     /* Setup mapping of gids to privileges */
432     /* Do this for each privilege for extra check */
433     for (const auto &privilege : allowed_privs) {
434         dbtest.setup_privilege_groups(privilege, allowed_groups);
435     }
436
437     std::vector<gid_t> allowed_gids;
438
439     for (const auto &groupName : allowed_groups) {
440         errno = 0;
441         struct group* grp = getgrnam(groupName.c_str());
442         RUNNER_ASSERT_ERRNO_MSG(grp, "Group: " << groupName << " not found");
443         allowed_gids.push_back(grp->gr_gid);
444     }
445
446     check_app_gids(app_id, allowed_gids);
447 }
448
449 static void check_app_after_install(const char *const app_id, const char *const pkg_id)
450 {
451     TestSecurityManagerDatabase dbtest;
452     dbtest.test_db_after__app_install(app_id, pkg_id);
453 }
454
455 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
456                                       const privileges_t &privileges, const bool is_pkg_removed)
457 {
458     TestSecurityManagerDatabase dbtest;
459     dbtest.test_db_after__app_uninstall(app_id, pkg_id, is_pkg_removed);
460
461
462     /*Privileges should not be granted anymore to any user*/
463     check_app_permissions(app_id, pkg_id, ANY_USER_REPRESENTATION, SM_NO_PRIVILEGES, privileges);
464 }
465
466 static void check_app_after_uninstall(const char *const app_id, const char *const pkg_id,
467                                       const bool is_pkg_removed)
468 {
469     TestSecurityManagerDatabase dbtest;
470     dbtest.test_db_after__app_uninstall(app_id, pkg_id, is_pkg_removed);
471 }
472
473 static void install_app(const char *app_id, const char *pkg_id, uid_t uid = 0)
474 {
475     InstallRequest request;
476     request.setAppId(app_id);
477     request.setPkgId(pkg_id);
478     request.setUid(uid);
479     Api::install(request);
480
481     check_app_after_install(app_id, pkg_id);
482 }
483
484 static void uninstall_app(const char *app_id, const char *pkg_id, bool expect_pkg_removed)
485 {
486     InstallRequest request;
487     request.setAppId(app_id);
488
489     Api::uninstall(request);
490
491     check_app_after_uninstall(app_id, pkg_id, expect_pkg_removed);
492 }
493
494 static inline void register_current_process_as_privilege_manager(uid_t uid, bool forAdmin = false)
495 {
496     InstallRequest request;
497     request.setAppId(PRIVILEGE_MANAGER_APP.c_str());
498     request.setPkgId(PRIVILEGE_MANAGER_PKG.c_str());
499     request.setUid(uid);
500     request.addPrivilege(PRIVILEGE_MANAGER_SELF_PRIVILEGE.c_str());
501     if (forAdmin)
502         request.addPrivilege(PRIVILEGE_MANAGER_ADMIN_PRIVILEGE.c_str());
503     Api::install(request);
504     Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
505 };
506
507 static inline struct passwd *getUserStruct(const std::string &userName) {
508     struct passwd *pw = nullptr;
509     errno = 0;
510
511     while(!(pw = getpwnam(userName.c_str()))) {
512         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
513     };
514
515     return pw;
516 };
517
518 static inline struct passwd *getUserStruct(const uid_t uid) {
519     struct passwd *pw = nullptr;
520     errno = 0;
521
522     while(!(pw = getpwuid(uid))) {
523         RUNNER_ASSERT_ERRNO_MSG(errno == EINTR, "getpwnam() failed");
524     };
525
526     return pw;
527 };
528
529 void check_exact_access(const std::string& subject, const std::string& object, const std::string& access)
530 {
531     // check access
532     if (!access.empty()) {
533         int result = smack_have_access(subject.c_str(), object.c_str(), access.c_str());
534         RUNNER_ASSERT_MSG(result >= 0, "smack_have_access failed");
535         RUNNER_ASSERT_MSG(result == 1,
536           "No smack access: " << subject << " " << object << " " << access);
537     }
538     // check excessive access
539     auto foundInAccess = [&access](std::string::value_type c) {
540         return access.find(c) != std::string::npos; };
541
542     std::string negative = "rwxatl";
543     auto end = std::remove_if(negative.begin(), negative.end(), foundInAccess);
544     negative.erase(end, negative.end());
545
546     for(const auto& c : negative) {
547         int result = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
548         RUNNER_ASSERT_MSG(result >= 0, "smack_have_access failed");
549         RUNNER_ASSERT_MSG(result == 0, "Unexpected access for" << 
550             " subject:" << subject <<
551             " object:" << object <<
552             " right:" << std::string(1,c) <<
553             " result:" << result <<
554             " expected:0");
555     }
556 }
557
558 std::string access_opposite(std::string &access) {
559     static const std::map<char, int> access_mapping = {{'r', 0}, {'w', 1}, {'x', 2}, {'a', 3},
560                                                        {'t', 4}, {'l', 5}};
561     //May write implies may lock
562     if (access.find('w') != std::string::npos && access.find('l') == std::string::npos) {
563         access.append("l");
564     }
565     std::string access_opposite = "rwxatl";
566     for (char c : access) {
567         access_opposite[access_mapping.at(c)] = '-';
568     }
569     auto it = std::remove_if(access_opposite.begin(), access_opposite.end(), [](char c) {return c == '-';});
570     access_opposite.erase(it, access_opposite.end());
571     return access_opposite;
572 }
573
574 void check_exact_smack_accesses(const std::string &subject, const std::string &object, const std::string &access) {
575     std::string access_str(access);
576     auto no_access = access_opposite(access_str);
577     for (char c : access_str) {
578         int ret = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
579         RUNNER_ASSERT_MSG(ret >= 0, "smack_have_access failed: <" << subject << ">, <" << object << ">, <" << c << "> errno=" << strerror(errno));
580         RUNNER_ASSERT_MSG(ret == 1, "Access " << c << " from " << subject << " to "
581                           << object << " not given");
582     }
583
584     for (char c : no_access) {
585         int ret = smack_have_access(subject.c_str(), object.c_str(), std::string(1, c).c_str());
586         RUNNER_ASSERT_MSG(ret >= 0, "smack_have_access failed: <" << subject << ">, <" << object << ">, <" << c << "> errno=" << strerror(errno));
587         RUNNER_ASSERT_MSG(ret == 0, "Access " << c << " from " << subject << " to "
588                           << object << " unnecessarily given");
589     }
590 }
591
592
593 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER)
594
595 RUNNER_TEST(security_manager_01a_app_double_install_double_uninstall)
596 {
597     const char *const sm_app_id = "sm_test_01a_app_id_double";
598     const char *const sm_pkg_id = "sm_test_01a_pkg_id_double";
599
600     InstallRequest requestInst;
601     requestInst.setAppId(sm_app_id);
602     requestInst.setPkgId(sm_pkg_id);
603
604     Api::install(requestInst);
605     Api::install(requestInst);
606
607     // Check records in the security-manager database
608     check_app_after_install(sm_app_id, sm_pkg_id);
609
610     InstallRequest requestUninst;
611     requestUninst.setAppId(sm_app_id);
612
613     Api::uninstall(requestUninst);
614     Api::uninstall(requestUninst);
615
616     // Check records in the security-manager database
617     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
618 }
619
620
621 RUNNER_TEST(security_manager_01b_app_double_install_wrong_pkg_id)
622 {
623     const char *const sm_app_id = "sm_test_01b_app";
624     const char *const sm_pkg_id = "sm_test_01b_pkg";
625     const char *const sm_pkg_id_wrong = "sm_test_01b_pkg_BAD";
626
627     InstallRequest requestInst;
628     requestInst.setAppId(sm_app_id);
629     requestInst.setPkgId(sm_pkg_id);
630
631     Api::install(requestInst);
632
633     InstallRequest requestInst2;
634     requestInst2.setAppId(sm_app_id);
635     requestInst2.setPkgId(sm_pkg_id_wrong);
636
637     Api::install(requestInst2, SECURITY_MANAGER_ERROR_INPUT_PARAM);
638
639
640     /* Check records in the security-manager database */
641     check_app_after_install(sm_app_id, sm_pkg_id);
642
643     InstallRequest requestUninst;
644     requestUninst.setAppId(sm_app_id);
645
646     Api::uninstall(requestUninst);
647
648
649     /* Check records in the security-manager database */
650     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
651
652 }
653
654 RUNNER_TEST(security_manager_01c_app_uninstall_pkg_id_ignored)
655 {
656     const char * const  sm_app_id = "SM_TEST_01c_APPID";
657     const char * const  sm_pkg_id = "SM_TEST_01c_PKGID";
658     const char * const  sm_pkg_id_wrong = "SM_TEST_01c_PKGID_wrong";
659
660     InstallRequest requestInst;
661     requestInst.setAppId(sm_app_id);
662     requestInst.setPkgId(sm_pkg_id);
663
664     Api::install(requestInst);
665
666     /* Check records in the security-manager database */
667     check_app_after_install(sm_app_id, sm_pkg_id);
668
669     InstallRequest requestUninst;
670     requestUninst.setAppId(sm_app_id);
671     requestUninst.setPkgId(sm_pkg_id_wrong);
672
673     Api::uninstall(requestUninst);
674
675     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
676
677 }
678
679 RUNNER_TEST(security_manager_02_app_install_uninstall_full)
680 {
681     std::string SM_RW_PATH = genRWPath(2);
682     std::string SM_RO_PATH = genROPath(2);
683     std::string SM_PUBLIC_RO_PATH = genPublicROPath(2);
684
685     const char *const sm_app_id = "sm_test_02_app_id_full";
686     const char *const sm_pkg_id = "sm_test_02_pkg_id_full";
687
688     prepare_app_env(2);
689
690     InstallRequest requestInst;
691     requestInst.setAppId(sm_app_id);
692     requestInst.setPkgId(sm_pkg_id);
693     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
694     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
695     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
696     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
697     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
698
699     Api::install(requestInst);
700
701     /* Check records in the security-manager database */
702     check_app_after_install(sm_app_id, sm_pkg_id,
703                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
704
705     /* TODO: add parameters to this function */
706     check_app_path_after_install(2, sm_pkg_id, false);
707
708     InstallRequest requestUninst;
709     requestUninst.setAppId(sm_app_id);
710
711     Api::uninstall(requestUninst);
712
713     /* Check records in the security-manager database,
714      * all previously allowed privileges should be removed */
715     check_app_after_uninstall(sm_app_id, sm_pkg_id,
716                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
717 }
718
719 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
720 {
721     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_smack";
722     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_smack";
723     const char *const socketLabel = "not_expected_label";
724     std::string expected_label = generateAppLabel(app_id);
725     std::string expected_socket_label = socketLabel;
726     char *label = nullptr;
727     CStringPtr labelPtr;
728     int result;
729
730     uninstall_app(app_id, pkg_id, true);
731     install_app(app_id, pkg_id);
732
733     const auto sockaddr = UDSHelpers::makeAbstractAddress("sm_test_03.socket");
734     int sock = UDSHelpers::createServer(&sockaddr);
735     SockUniquePtr sockPtr(&sock);
736
737     //Set socket label to something different than expecedLabel
738     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPIN, socketLabel);
739     RUNNER_ASSERT_ERRNO_MSG(result == 0,
740         "Can't set socket label. Result: " << result);
741     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPOUT, socketLabel);
742     RUNNER_ASSERT_ERRNO_MSG(result == 0,
743         "Can't set socket label. Result: " << result);
744
745     {
746         ScopedProcessLabel keepLabel;
747         Api::setProcessLabel(app_id);
748
749         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPIN, &label);
750         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
751         labelPtr.reset(label);
752         result = expected_socket_label.compare(label);
753         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
754             expected_label << " Actual: " << label);
755
756         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPOUT, &label);
757         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
758         labelPtr.reset(label);
759         result = expected_socket_label.compare(label);
760         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
761             expected_label << " Actual: " << label);
762
763         result = smack_new_label_from_self(&label);
764         RUNNER_ASSERT_MSG(result >= 0,
765                 " Error getting current process label");
766         RUNNER_ASSERT_MSG(label != nullptr,
767                 " Process label is not set");
768         labelPtr.reset(label);
769
770         result = expected_label.compare(label);
771         RUNNER_ASSERT_MSG(result == 0,
772                 " Process label is incorrect. Expected: \"" << expected_label <<
773                 "\" Actual: \"" << label << "\"");
774     }
775
776     uninstall_app(app_id, pkg_id, true);
777 }
778
779 RUNNER_CHILD_TEST_NOSMACK(security_manager_03_set_label_from_appid_nosmack)
780 {
781     const char *const app_id = "sm_test_03_app_id_set_label_from_appid_nosmack";
782     const char *const pkg_id = "sm_test_03_pkg_id_set_label_from_appid_nosmack";
783
784     uninstall_app(app_id, pkg_id, true);
785     install_app(app_id, pkg_id);
786
787     {
788         ScopedProcessLabel keepLabel;
789         Api::setProcessLabel(app_id);
790     }
791
792     uninstall_app(app_id, pkg_id, true);
793 }
794
795 static void prepare_request(InstallRequest &request,
796               const char *const app_id,
797               const char *const pkg_id,
798               app_install_path_type pathType,
799               const char *const path,
800               uid_t uid)
801 {
802     request.setAppId(app_id);
803     request.setPkgId(pkg_id);
804     request.addPath(path, pathType);
805
806     if (uid != 0)
807         request.setUid(uid);
808 }
809
810 static uid_t getGlobalUserId(void)
811 {
812     return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
813 }
814
815 static uid_t getGlobalGroupId(void)
816 {
817     gid_t global_uid = tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
818     errno = 0;
819     passwd* pw = getpwuid(global_uid);
820     RUNNER_ASSERT_ERRNO_MSG(pw, "getpwuid() failed.");
821     return pw->pw_gid;
822
823 }
824
825 static const std::string appDirPath(const TemporaryTestUser &user,
826         const std::string &appId, const std::string &pkgId)
827 {
828     struct tzplatform_context *tzCtxPtr = nullptr;
829
830     RUNNER_ASSERT(0 == tzplatform_context_create(&tzCtxPtr));
831     TzPlatformContextPtr tzCtxPtrSmart(tzCtxPtr);
832
833     RUNNER_ASSERT_MSG(0 == tzplatform_context_set_user(tzCtxPtr, user.getUid()),
834                       "Unable to set user <" << user.getUserName() << "> for tzplatform context");
835
836     const char *appDir = tzplatform_context_getenv(tzCtxPtr,
837                                 getGlobalUserId() == user.getUid() ? TZ_SYS_RW_APP : TZ_USER_APP);
838     RUNNER_ASSERT_MSG(nullptr != appDir,
839                       "tzplatform_context_getenv failed"
840                           << "for getting sys rw app of user <" << user.getUserName() << ">");
841
842     return std::string(appDir) + "/" + pkgId + "/" + appId;
843 }
844
845 static const std::string nonAppDirPath(const TemporaryTestUser &user)
846 {
847     return TMP_DIR + "/" + user.getUserName();
848 }
849
850 static const std::string uidToStr(const uid_t uid)
851 {
852     return std::to_string(static_cast<unsigned int>(uid));
853 }
854
855 static void install_and_check(const char *const sm_app_id,
856                               const char *const sm_pkg_id,
857                               const TemporaryTestUser& user,
858                               const std::string &appDir,
859                               bool requestUid)
860 {
861     InstallRequest requestPrivate;
862
863     //install app for non-root user
864     //should fail (users may only register folders inside their home)
865     prepare_request(requestPrivate, sm_app_id, sm_pkg_id,
866                     SECURITY_MANAGER_PATH_RW, SM_RW_PATH,
867                     requestUid ? user.getUid() : 0);
868
869     Api::install(requestPrivate, SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
870
871     InstallRequest requestPrivateUser;
872
873     //install app for non-root user
874     //should succeed - this time i register folder inside user's home dir
875     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
876                     SECURITY_MANAGER_PATH_RW, appDir.c_str(),
877                     requestUid ? user.getUid() : 0);
878
879     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
880         requestPrivateUser.addPrivilege(privilege.c_str());
881
882     Api::install(requestPrivateUser);
883
884     check_app_permissions(sm_app_id, sm_pkg_id,
885                           uidToStr(user.getUid()).c_str(),
886                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
887 }
888
889 static void createTestDir(const std::string &dir)
890 {
891     mode_t dirMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
892     mode_t execFileMode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
893     mode_t normalFileMode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH;
894
895     mktreeSafe(dir, dirMode);
896     creatSafe(dir + "/" + EXEC_FILE, execFileMode);
897     creatSafe(dir + "/" + NORMAL_FILE, normalFileMode);
898     symlinkSafe(dir + "/" + EXEC_FILE, dir + "/" + LINK_PREFIX + EXEC_FILE);
899     symlinkSafe(dir + "/" + NORMAL_FILE, dir + "/" + LINK_PREFIX + NORMAL_FILE);
900 }
901
902 static void createInnerAppDir(const std::string &dir, const std::string &nonAppDir)
903 {
904     createTestDir(dir);
905
906     symlinkSafe(nonAppDir, dir + "/" + LINK_PREFIX + "non_app_dir");
907     symlinkSafe(nonAppDir + "/" + EXEC_FILE,
908                 dir + "/" + LINK_PREFIX + "non_app_" + EXEC_FILE);
909     symlinkSafe(nonAppDir + "/" + NORMAL_FILE,
910                 dir + "/" + LINK_PREFIX + "non_app_" + NORMAL_FILE);
911 }
912
913 static void generateAppDir(const TemporaryTestUser &user,
914        const std::string &appId, const std::string &pkgId)
915 {
916     const std::string dir = appDirPath(user, appId, pkgId);
917     const std::string nonAppDir = nonAppDirPath(user);
918
919     createInnerAppDir(dir, nonAppDir);
920     createInnerAppDir(dir + "/.inner_dir", nonAppDir);
921     createInnerAppDir(dir + "/inner_dir", nonAppDir);
922 }
923
924 static void generateNonAppDir(const TemporaryTestUser &user)
925 {
926     const std::string dir = nonAppDirPath(user);
927
928     createTestDir(dir);
929     createTestDir(dir + "/.inner_dir");
930     createTestDir(dir + "/inner_dir");
931 }
932
933 static void createTestDirs(const TemporaryTestUser &user,
934        const std::string &appId, const std::string &pkgId)
935 {
936     generateAppDir(user, appId, pkgId);
937     generateNonAppDir(user);
938 }
939
940 static void removeTestDirs(const TemporaryTestUser &user,
941        const std::string &appId, const std::string &pkgId)
942 {
943     removeDir(appDirPath(user, appId, pkgId));
944     removeDir(nonAppDirPath(user));
945 }
946
947
948
949 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
950 {
951     int result;
952     const char *const sm_app_id = "sm_test_04a_app_id_uid";
953     const char *const sm_pkg_id = "sm_test_04a_pkg_id_uid";
954     const std::string new_user_name = "sm_test_04a_user_name";
955
956     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
957     testUser.create();
958
959     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
960     createTestDirs(testUser, sm_app_id, sm_pkg_id);
961
962     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
963
964     //switch user to non-root
965     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
966     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
967
968     install_and_check(sm_app_id, sm_pkg_id, testUser, userAppDirPath, false);
969
970     //uninstall app as non-root user
971     InstallRequest request;
972     request.setAppId(sm_app_id);
973
974     Api::uninstall(request);
975
976     check_app_permissions(sm_app_id, sm_pkg_id,
977                           uidToStr(testUser.getUid()).c_str(),
978                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
979 }
980
981 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user)
982 {
983     int result;
984     const char *const sm_app_id = "sm_test_04b_app_id_uid";
985     const char *const sm_pkg_id = "sm_test_04b_pkg_id_uid";
986     const std::string new_user_name = "sm_test_04b_user_name";
987
988     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
989     testUser.create();
990
991     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
992     createTestDirs(testUser, sm_app_id, sm_pkg_id);
993
994     install_and_check(sm_app_id, sm_pkg_id, testUser, appDirPath(testUser, sm_app_id, sm_pkg_id), true);
995
996     //switch user to non-root - root may not uninstall apps for specified users
997     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
998     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
999
1000     //uninstall app as non-root user
1001     InstallRequest request;
1002     request.setAppId(sm_app_id);
1003
1004     Api::uninstall(request);
1005
1006     check_app_permissions(sm_app_id, sm_pkg_id,
1007                           uidToStr(testUser.getUid()).c_str(),
1008                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1009 }
1010
1011
1012 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
1013 {
1014     int result;
1015     CapsSetsUniquePtr caps, caps_empty(cap_init());
1016
1017     caps.reset(cap_from_text("all=eip"));
1018     RUNNER_ASSERT_MSG(caps, "can't convert capabilities from text");
1019     result = cap_set_proc(caps.get());
1020     RUNNER_ASSERT_MSG(result == 0,
1021         "can't set capabilities. Result: " << result);
1022
1023     Api::dropProcessPrivileges();
1024
1025     caps.reset(cap_get_proc());
1026     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
1027
1028     result = cap_compare(caps.get(), caps_empty.get());
1029     RUNNER_ASSERT_MSG(result == 0,
1030         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
1031 }
1032
1033 RUNNER_CHILD_TEST(security_manager_06_install_app_offline)
1034 {
1035     const char *const app_id = "sm_test_06_app_id_install_app_offline";
1036     const char *const pkg_id = "sm_test_06_pkg_id_install_app_offline";
1037
1038     // Uninstall app on-line, off-line mode doesn't support it
1039     uninstall_app(app_id, pkg_id, true);
1040
1041     ServiceManager("security-manager.service").stopService();
1042
1043     ServiceManager serviceManager("security-manager.socket");
1044     serviceManager.stopService();
1045
1046     install_app(app_id, pkg_id);
1047
1048     serviceManager.startService();
1049
1050     uninstall_app(app_id, pkg_id, true);
1051 }
1052
1053 RUNNER_CHILD_TEST(security_manager_07_user_add_app_install)
1054 {
1055     const char *const sm_app_id = "sm_test_07_app_id_user";
1056     const char *const sm_pkg_id = "sm_test_07_pkg_id_user";
1057     const std::string new_user_name = "sm_test_07_user_name";
1058     std::string uid_string;
1059     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
1060     test_user.create();
1061     test_user.getUidString(uid_string);
1062
1063     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
1064     createTestDirs(test_user, sm_app_id, sm_pkg_id);
1065
1066     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
1067
1068     check_app_after_install(sm_app_id, sm_pkg_id);
1069
1070     test_user.remove();
1071
1072     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1073
1074     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
1075 }
1076
1077 RUNNER_CHILD_TEST(security_manager_08_user_double_add_double_remove)
1078 {
1079     UserRequest addUserRequest;
1080
1081     const char *const sm_app_id = "sm_test_08_app_id_user";
1082     const char *const sm_pkg_id = "sm_test_08_pkg_id_user";
1083     const std::string new_user_name = "sm_test_08_user_name";
1084     std::string uid_string;
1085
1086     // gumd user add
1087     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, false);
1088     test_user.create();
1089     test_user.getUidString(uid_string);
1090
1091     removeTestDirs(test_user, sm_app_id, sm_pkg_id);
1092     createTestDirs(test_user, sm_app_id, sm_pkg_id);
1093
1094     addUserRequest.setUid(test_user.getUid());
1095     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
1096
1097     //sm user add
1098     Api::addUser(addUserRequest);
1099
1100     install_app(sm_app_id, sm_pkg_id, test_user.getUid());
1101
1102     check_app_after_install(sm_app_id, sm_pkg_id);
1103
1104     test_user.remove();
1105
1106     UserRequest deleteUserRequest;
1107     deleteUserRequest.setUid(test_user.getUid());
1108
1109     Api::deleteUser(deleteUserRequest);
1110
1111     check_app_permissions(sm_app_id, sm_pkg_id, uid_string.c_str(), SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
1112
1113     check_app_after_uninstall(sm_app_id, sm_pkg_id, true);
1114 }
1115
1116 RUNNER_CHILD_TEST(security_manager_09_add_user_offline)
1117 {
1118     const char *const app_id = "security_manager_09_add_user_offline_app";
1119     const char *const pkg_id = "security_manager_09_add_user_offline_pkg";
1120     const std::string new_user_name("sm_test_09_user_name");
1121
1122     ServiceManager("security-manager.service").stopService();
1123
1124     ServiceManager serviceManager("security-manager.socket");
1125     serviceManager.stopService();
1126
1127     TemporaryTestUser test_user(new_user_name, GUM_USERTYPE_NORMAL, true);
1128     test_user.create();
1129
1130     removeTestDirs(test_user, app_id, pkg_id);
1131     createTestDirs(test_user, app_id, pkg_id);
1132
1133     install_app(app_id, pkg_id, test_user.getUid());
1134
1135     check_app_after_install(app_id, pkg_id);
1136
1137     serviceManager.startService();
1138
1139     test_user.remove();
1140
1141     check_app_after_uninstall(app_id, pkg_id, true);
1142 }
1143
1144 RUNNER_CHILD_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
1145 {
1146     //TEST DATA
1147     const std::string username("sm_test_10_user_name");
1148     unsigned int privileges_count = 0;
1149
1150     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1151     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1152
1153     for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1154         apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1155             MANY_APPS.at(i), std::set<std::string>(
1156                 MANY_APPS_PRIVILEGES.at(i).begin(),
1157                 MANY_APPS_PRIVILEGES.at(i).end())));
1158         privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1159     };
1160
1161     apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1162         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1163     ++privileges_count;
1164     users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1165     //TEST DATA END
1166
1167     SynchronizationPipe pipe;
1168     pid_t pid = fork();
1169
1170     if (pid != 0) { //parent process
1171         pipe.claimParentEp();
1172         TemporaryTestUser tmpUser(username, GUM_USERTYPE_NORMAL, false);
1173         tmpUser.create();
1174
1175         for(const auto &user : users2AppsMap) {
1176
1177             for(const auto &app : user.second) {
1178                 InstallRequest requestInst;
1179                 requestInst.setAppId(app.first.c_str());
1180                 try {
1181                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1182                 } catch (const std::out_of_range &e) {
1183                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1184                 };
1185                 requestInst.setUid(tmpUser.getUid());
1186
1187                 for (const auto &privilege : app.second) {
1188                     requestInst.addPrivilege(privilege.c_str());
1189                 };
1190
1191                 Api::install(requestInst);
1192             };
1193
1194             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1195         };
1196
1197         //Start child process
1198         pipe.post();
1199         waitPid(pid);
1200
1201         tmpUser.remove();
1202     } else { //child process
1203         pipe.claimChildEp();
1204         pipe.wait();
1205
1206         struct passwd *pw = getUserStruct(username);
1207         std::string uidStr = std::to_string(pw->pw_uid);
1208         register_current_process_as_privilege_manager(pw->pw_uid);
1209         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1210         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1211
1212         std::vector<PolicyEntry> policyEntries;
1213         PolicyEntry filter;
1214         Api::getPolicy(filter, policyEntries);
1215
1216         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1217         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1218
1219         for (const auto &policyEntry : policyEntries) {
1220             std::string user = policyEntry.getUser();
1221             std::string app = policyEntry.getAppId();
1222             std::string privilege = policyEntry.getPrivilege();
1223
1224             RUNNER_ASSERT_MSG(user == uidStr, "Unexpected user: " << user);
1225
1226             try {
1227                 std::set<std::string>::iterator tmp = users2AppsMap.at(username).at(app).find(privilege);
1228                 if (tmp == users2AppsMap.at(username).at(app).end())
1229                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1230             } catch (const std::out_of_range &e) {
1231                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected app: " << policyEntry << ". Exception: " << e.what());
1232             };
1233         };
1234         exit(0);
1235     };
1236 }
1237
1238 RUNNER_CHILD_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
1239 {
1240     //TEST DATA
1241     const std::vector<std::string> usernames = {"sm_test_11_user_name_1", "sm_test_11_user_name_2"};
1242     unsigned int privileges_count = 0;
1243
1244     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1245     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1246
1247     for (const auto &username : usernames) {
1248         //Only entries for one of the users will be listed
1249         privileges_count = 0;
1250
1251         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1252             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1253                 MANY_APPS.at(i), std::set<std::string>(
1254                     MANY_APPS_PRIVILEGES.at(i).begin(),
1255                     MANY_APPS_PRIVILEGES.at(i).end())));
1256             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1257         };
1258
1259         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1260     };
1261
1262     users2AppsMap.at(usernames.at(0)).insert(std::pair<std::string, std::set<std::string>>(
1263         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1264
1265     ++privileges_count;
1266     //TEST DATA END
1267
1268     SynchronizationPipe pipe;
1269     pid_t pid = fork();
1270
1271     if (pid != 0) { //parent process
1272         pipe.claimParentEp();
1273         std::vector<TemporaryTestUser> users = {
1274             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1275             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1276             };
1277
1278         users.at(0).create();
1279         users.at(1).create();
1280
1281         //Install apps for both users
1282         for(const auto &user : users) {
1283             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1284                 InstallRequest requestInst;
1285                 requestInst.setAppId(app.first.c_str());
1286                 try {
1287                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1288                 } catch (const std::out_of_range &e) {
1289                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1290                 };
1291                 requestInst.setUid(user.getUid());
1292
1293                 for (const auto &privilege : app.second) {
1294                     requestInst.addPrivilege(privilege.c_str());
1295                 };
1296
1297                 Api::install(requestInst);
1298             };
1299
1300             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1301         };
1302
1303         //Start child
1304         pipe.post();
1305         waitPid(pid);
1306
1307         for (auto &user : users)
1308             user.remove();
1309
1310     } else { //child process
1311         pipe.claimChildEp();
1312         pipe.wait();
1313
1314         struct passwd *pw = getUserStruct(usernames.at(0));
1315         std::string uidStr = std::to_string(pw->pw_uid);
1316         register_current_process_as_privilege_manager(pw->pw_uid);
1317
1318         //change uid to normal user
1319         errno = 0;
1320         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1321         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1322
1323         std::vector<PolicyEntry> policyEntries;
1324         PolicyEntry filter;
1325
1326         //this call should only return privileges belonging to the current uid
1327         Api::getPolicy(filter, policyEntries);
1328
1329         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1330         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1331
1332         for (const auto &policyEntry : policyEntries) {
1333             std::string user = policyEntry.getUser();
1334             std::string app = policyEntry.getAppId();
1335             std::string privilege = policyEntry.getPrivilege();
1336
1337             RUNNER_ASSERT_MSG(uidStr == user, "Unexpected user: " << user);
1338
1339             try {
1340                 std::set<std::string>::iterator tmp = users2AppsMap.at(usernames.at(0)).at(app).find(privilege);
1341                 if (tmp == users2AppsMap.at(usernames.at(0)).at(app).end())
1342                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1343             } catch (const std::out_of_range &e) {
1344                 RUNNER_FAIL_MSG("Unexpected policy entry: app: " << policyEntry << ". Exception: " << e.what());
1345             };
1346         };
1347         exit(0);
1348     };
1349 }
1350
1351 RUNNER_CHILD_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
1352 {
1353     std::vector<PolicyEntry> oldPolicyVec;
1354     Api::getPolicy(PolicyEntry(), oldPolicyVec);
1355     std::unordered_set<PolicyEntry> oldPolicySet(oldPolicyVec.begin(), oldPolicyVec.end());
1356
1357     //TEST DATA
1358     const std::vector<std::string> usernames = {"sm_test_12_user_name_1", "sm_test_12_user_name_2"};
1359     unsigned int privileges_count = oldPolicyVec.size();
1360
1361     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1362     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1363
1364     for (const auto &username : usernames) {
1365         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1366             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1367                 MANY_APPS.at(i), std::set<std::string>(
1368                     MANY_APPS_PRIVILEGES.at(i).begin(),
1369                     MANY_APPS_PRIVILEGES.at(i).end())));
1370             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1371         };
1372
1373         users2AppsMap.insert(std::make_pair(username, apps2PrivsMap));
1374     };
1375
1376     users2AppsMap.at(usernames.at(1)).insert(std::make_pair(PRIVILEGE_MANAGER_APP,
1377         std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE, PRIVILEGE_MANAGER_ADMIN_PRIVILEGE}));
1378
1379     privileges_count += 2;
1380     //TEST DATA END
1381
1382     SynchronizationPipe pipe;
1383     pid_t pid = fork();
1384
1385     if (pid != 0) { //parent process
1386         pipe.claimParentEp();
1387         std::vector<TemporaryTestUser> users = {
1388             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1389             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1390             };
1391
1392         users.at(0).create();
1393         users.at(1).create();
1394         //Install apps for both users
1395         for(const auto &user : users) {
1396             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1397                 InstallRequest requestInst;
1398                 requestInst.setAppId(app.first.c_str());
1399                 try {
1400                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1401                 } catch (const std::out_of_range &e) {
1402                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1403                 };
1404                 requestInst.setUid(user.getUid());
1405
1406                 for (const auto &privilege : app.second) {
1407                     requestInst.addPrivilege(privilege.c_str());
1408                 };
1409
1410                 Api::install(requestInst);
1411             };
1412
1413             //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1414         };
1415
1416         //Start child process
1417         pipe.post();
1418         waitPid(pid);
1419
1420         for (auto &user : users)
1421             user.remove();
1422
1423     } else { //child process
1424         pipe.claimChildEp();
1425         pipe.wait();
1426
1427         struct passwd *pw = getUserStruct(usernames.at(1));
1428         uid_t myUid = pw->pw_uid;
1429         gid_t myGid = pw->pw_gid;
1430         std::string uidStr1 = std::to_string(myUid);
1431         pw = getUserStruct(usernames.at(0));
1432         std::string uidStr0 = std::to_string(pw->pw_uid);
1433         register_current_process_as_privilege_manager(myUid, true);
1434
1435         //change uid to normal user
1436         int result = drop_root_privileges(myUid, myGid);
1437         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1438
1439
1440         std::vector<PolicyEntry> policyEntries;
1441         //this call should succeed as the calling user is privileged
1442         Api::getPolicy(PolicyEntry(), policyEntries);
1443
1444         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
1445         RUNNER_ASSERT_MSG(policyEntries.size() == privileges_count, "Number of policies doesn't match - should be: " << privileges_count << " and is " << policyEntries.size());
1446
1447         for (const auto &policyEntry : policyEntries) {
1448             if (oldPolicySet.count(policyEntry))
1449                 continue;
1450
1451             std::string user = policyEntry.getUser();
1452             std::string app = policyEntry.getAppId();
1453             std::string privilege = policyEntry.getPrivilege();
1454
1455             RUNNER_ASSERT_MSG(user == uidStr0 || user == uidStr1, "Unexpected user: " << user);
1456
1457             std::string uidStrToLook = user == uidStr0 ? usernames.at(0) : usernames.at(1);
1458
1459             try {
1460                 std::set<std::string>::iterator tmp = users2AppsMap.at(uidStrToLook).at(app).find(privilege);
1461                 if (tmp == users2AppsMap.at(uidStrToLook).at(app).end())
1462                     RUNNER_FAIL_MSG("Unexpected policy entry: unexpected privilege: " << policyEntry);
1463             } catch (const std::out_of_range &e) {
1464                 RUNNER_FAIL_MSG("Unexpected policy entry: unexpected app: " << policyEntry << ". Exception: " << e.what());
1465             } catch (const std::invalid_argument& e) {
1466                 RUNNER_FAIL_MSG("Incorrect UID: " << user << ". Exception: " << e.what());
1467             };
1468         };
1469
1470         exit(0);
1471     };
1472 }
1473
1474 RUNNER_CHILD_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
1475 {
1476     //TEST DATA
1477     const std::vector<std::string> usernames = {"sm_test_13_user_name_1", "sm_test_13_user_name_2"};
1478
1479     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1480     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1481
1482     for (const auto &username : usernames) {
1483
1484         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1485             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1486                 MANY_APPS.at(i), std::set<std::string>(
1487                     MANY_APPS_PRIVILEGES.at(i).begin(),
1488                     MANY_APPS_PRIVILEGES.at(i).end())));
1489         };
1490
1491         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1492     };
1493
1494     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1495         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1496
1497     //TEST DATA END
1498
1499     pid_t pid[2];
1500     SynchronizationPipe sync[2];
1501     std::vector<PolicyEntry> policyEntries;
1502
1503     pid[0] = fork();
1504
1505     if (pid[0] == 0) { //child #1 process
1506         sync[0].claimChildEp();
1507         sync[0].wait();
1508
1509         struct passwd *pw = getUserStruct(usernames.at(0));
1510         register_current_process_as_privilege_manager(pw->pw_uid);
1511
1512         //change uid to normal user
1513         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1514         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1515
1516         PolicyEntry filter;
1517         PolicyRequest policyRequest;
1518
1519         PolicyEntry policyEntry(
1520                 MANY_APPS[0],
1521                 std::to_string(pw->pw_uid),
1522                 "http://tizen.org/privilege/internet"
1523                 );
1524         policyEntry.setLevel("Deny");
1525
1526         policyRequest.addEntry(policyEntry);
1527         policyEntry = PolicyEntry(
1528                 MANY_APPS[1],
1529                 std::to_string(pw->pw_uid),
1530                 "http://tizen.org/privilege/display"
1531                 );
1532         policyEntry.setLevel("Deny");
1533
1534         policyRequest.addEntry(policyEntry);
1535         Api::sendPolicy(policyRequest);
1536
1537         exit(0);
1538     } else { //parent process
1539         sync[0].claimParentEp();
1540         pid[1] = fork();
1541
1542         if (pid[1] == 0) { //child #2 process
1543             sync[1].claimChildEp();
1544             sync[1].wait();
1545
1546             struct passwd *pw = getUserStruct(usernames.at(0));
1547             uid_t target_uid = pw->pw_uid;
1548             pw = getUserStruct(usernames.at(1));
1549             uid_t my_uid = pw->pw_uid;
1550             gid_t my_gid = pw->pw_gid;
1551
1552             register_current_process_as_privilege_manager(my_uid);
1553
1554             //change uid to normal user
1555             int result = drop_root_privileges(my_uid, my_gid);
1556             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1557
1558             PolicyEntry filter = PolicyEntry(
1559                         SECURITY_MANAGER_ANY,
1560                         std::to_string(target_uid),
1561                         SECURITY_MANAGER_ANY
1562                         );
1563
1564             //U2 requests contents of U1 privacy manager - should fail
1565             Api::getPolicyForSelf(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1566             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but is " << policyEntries.size());
1567
1568             filter = PolicyEntry(
1569                         SECURITY_MANAGER_ANY,
1570                         SECURITY_MANAGER_ANY,
1571                         SECURITY_MANAGER_ANY
1572                         );
1573
1574             policyEntries.clear();
1575
1576             //U2 requests contents of ADMIN bucket - should fail
1577             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
1578             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but is " << policyEntries.size());
1579             exit(0);
1580         } else { //parent
1581             sync[1].claimParentEp();
1582             std::vector<TemporaryTestUser> users = {
1583                 TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1584                 TemporaryTestUser(usernames.at(1), GUM_USERTYPE_NORMAL, false)
1585                 };
1586
1587             users.at(0).create();
1588             users.at(1).create();
1589
1590             //Install apps for both users
1591             for(const auto &user : users2AppsMap) {
1592
1593                 for(const auto &app : user.second) {
1594                     InstallRequest requestInst;
1595                     requestInst.setAppId(app.first.c_str());
1596                     try {
1597                         requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1598                     } catch (const std::out_of_range &e) {
1599                         RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1600                     };
1601                     requestInst.setUid(users.at(0).getUid());
1602
1603                     for (const auto &privilege : app.second) {
1604                         requestInst.addPrivilege(privilege.c_str());
1605                     };
1606
1607                     Api::install(requestInst);
1608                 };
1609
1610                 //check_app_after_install(MANY_APPS[i].c_str(), MANY_APPS_PKGS[i].c_str());
1611             };
1612
1613             //Start child #1
1614             sync[0].post();
1615             waitPid(pid[0]);
1616
1617             //Start child #2
1618             sync[1].post();
1619             waitPid(pid[1]);
1620
1621             for (auto &user : users)
1622                 user.remove();
1623         };
1624     };
1625 }
1626
1627 RUNNER_CHILD_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
1628 {
1629     //TEST DATA
1630     const std::vector<std::string> usernames = {"sm_test_14_user_name_1", "sm_test_14_user_name_2"};
1631     unsigned int privileges_count = 0;
1632
1633     std::map<std::string, std::map<std::string, std::set<std::string>>> users2AppsMap;
1634     std::map<std::string, std::set<std::string>> apps2PrivsMap;
1635
1636     for (const auto &username : usernames) {
1637
1638         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
1639             apps2PrivsMap.insert(std::pair<std::string, std::set<std::string>>(
1640                 MANY_APPS.at(i), std::set<std::string>(
1641                     MANY_APPS_PRIVILEGES.at(i).begin(),
1642                     MANY_APPS_PRIVILEGES.at(i).end())));
1643             privileges_count+=MANY_APPS_PRIVILEGES.at(i).size();
1644         };
1645
1646         users2AppsMap.insert(std::pair<std::string, std::map<std::string, std::set<std::string>>>(username, apps2PrivsMap));
1647     };
1648
1649     users2AppsMap.at(usernames.at(1)).insert(std::pair<std::string, std::set<std::string>>(
1650         PRIVILEGE_MANAGER_APP, std::set<std::string>{PRIVILEGE_MANAGER_SELF_PRIVILEGE}));
1651
1652     privileges_count += 2;
1653     //TEST DATA END
1654     SynchronizationPipe pipe;
1655
1656     pid_t pid = fork();
1657     if (pid != 0) {
1658         pipe.claimParentEp();
1659         std::vector<TemporaryTestUser> users = {
1660             TemporaryTestUser(usernames.at(0), GUM_USERTYPE_NORMAL, false),
1661             TemporaryTestUser(usernames.at(1), GUM_USERTYPE_ADMIN, false)
1662             };
1663
1664         users.at(0).create();
1665         users.at(1).create();
1666
1667         //Install apps for both users
1668         for(const auto &user : users) {
1669
1670             for(const auto &app : users2AppsMap.at(user.getUserName())) {
1671                 InstallRequest requestInst;
1672                 requestInst.setAppId(app.first.c_str());
1673                 try {
1674                     requestInst.setPkgId(MANY_APPS_PKGS.at(app.first).package.c_str());
1675                 } catch (const std::out_of_range &e) {
1676                     RUNNER_FAIL_MSG("Couldn't find package for app: " << app.first);
1677                 };
1678                 requestInst.setUid(user.getUid());
1679
1680                 for (const auto &privilege : app.second) {
1681                     requestInst.addPrivilege(privilege.c_str());
1682                 };
1683
1684                 Api::install(requestInst);
1685             };
1686         };
1687
1688         //Start child process
1689         pipe.post();
1690         waitPid(pid);
1691
1692         //switch back to root
1693         for (auto &user : users)
1694             user.remove();
1695
1696     } else { //child process
1697         pipe.claimChildEp();
1698         pipe.wait();
1699
1700         struct passwd *pw = getUserStruct(usernames.at(1));
1701         register_current_process_as_privilege_manager(pw->pw_uid, true);
1702
1703         //change uid to normal user
1704         int result = drop_root_privileges(pw->pw_uid, pw->pw_gid);
1705         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1706
1707         PolicyRequest *policyRequest = new PolicyRequest();
1708         PolicyEntry filter;
1709         std::vector<PolicyEntry> policyEntries;
1710         //this call should succeed as the calling user is privileged
1711         Api::getPolicyForSelf(filter, policyEntries);
1712
1713         unsigned int policyNum = policyEntries.size();
1714
1715         PolicyEntry policyEntry(
1716                 SECURITY_MANAGER_ANY,
1717                 SECURITY_MANAGER_ANY,
1718                 "http://tizen.org/privilege/internet"
1719                 );
1720         policyEntry.setMaxLevel("Deny");
1721
1722         policyRequest->addEntry(policyEntry);
1723         policyEntry = PolicyEntry(
1724                 SECURITY_MANAGER_ANY,
1725                 SECURITY_MANAGER_ANY,
1726                 "http://tizen.org/privilege/display"
1727                 );
1728         policyEntry.setMaxLevel("Deny");
1729
1730         policyRequest->addEntry(policyEntry);
1731         Api::sendPolicy(*policyRequest);
1732         Api::getPolicyForAdmin(filter, policyEntries);
1733
1734         RUNNER_ASSERT_MSG(policyEntries.size() == policyNum + 2, "Number of policies doesn't match - should be: "
1735                                     << policyNum + 2 << "  and is " << policyEntries.size());
1736
1737         delete policyRequest;
1738         policyRequest = new PolicyRequest();
1739         policyEntry = PolicyEntry(
1740                 SECURITY_MANAGER_ANY,
1741                 SECURITY_MANAGER_ANY,
1742                 "http://tizen.org/privilege/internet"
1743                 );
1744         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1745         policyRequest->addEntry(policyEntry);
1746
1747         policyEntry = PolicyEntry(
1748                 SECURITY_MANAGER_ANY,
1749                 SECURITY_MANAGER_ANY,
1750                 "http://tizen.org/privilege/display"
1751                 );
1752         policyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
1753
1754         policyRequest->addEntry(policyEntry);
1755         Api::sendPolicy(*policyRequest);
1756
1757         policyEntries.clear();
1758         Api::getPolicyForAdmin(filter, policyEntries);
1759         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0 and is " << policyEntries.size());
1760
1761         delete policyRequest;
1762
1763         exit(0);
1764     };
1765
1766 }
1767
1768 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
1769 {
1770     const char *const update_app_id = "security_manager_15_update_app_id";
1771     const char *const update_privilege = "http://tizen.org/privilege/led";
1772     const char *const check_start_bucket = "ADMIN";
1773     const std::string username("sm_test_15_username");
1774     PolicyRequest addPolicyRequest;
1775     CynaraTestAdmin::Admin admin;
1776     ScopedProcessLabel keepLabel;
1777
1778     struct message {
1779         uid_t uid;
1780         gid_t gid;
1781     } msg;
1782
1783     int pipefd[2];
1784     pid_t pid;
1785     int result = 0;
1786
1787     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1788
1789     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1790     user.create();
1791
1792     pid = fork();
1793     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1794     if (pid != 0)//parent process
1795     {
1796         FdUniquePtr pipeptr(pipefd+1);
1797         close(pipefd[0]);
1798
1799         register_current_process_as_privilege_manager(user.getUid(), true);
1800
1801         //send info to child
1802         msg.uid = user.getUid();
1803         msg.gid = user.getGid();
1804
1805         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1806         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1807
1808         waitPid(pid);
1809
1810         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1811                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1812     }
1813     if(pid == 0)
1814     {
1815         FdUniquePtr pipeptr(pipefd);
1816         close(pipefd[1]);
1817
1818         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1819         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1820
1821         //become admin privacy manager manager
1822         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1823         result = drop_root_privileges(msg.uid, msg.gid);
1824         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1825
1826         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1827         entry.setMaxLevel("Allow");
1828
1829         addPolicyRequest.addEntry(entry);
1830         Api::sendPolicy(addPolicyRequest);
1831         exit(0);
1832     }
1833 }
1834
1835 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
1836 {
1837     const char *const update_other_app_id = "security_manager_15_update_other_app_id";
1838     const char *const update_privilege = "http://tizen.org/privilege/led";
1839     const char *const check_start_bucket = "ADMIN";
1840     const std::string username("sm_test_15_username");
1841     PolicyRequest addPolicyRequest;
1842     CynaraTestAdmin::Admin admin;
1843     ScopedProcessLabel keepLabel;
1844
1845     struct message {
1846         uid_t uid;
1847         gid_t gid;
1848     } msg;
1849
1850     int pipefd[2];
1851     pid_t pid;
1852     int result = 0;
1853
1854     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1855
1856     TemporaryTestUser user(username, GUM_USERTYPE_ADMIN, false);
1857     user.create();
1858
1859     pid = fork();
1860     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1861     if (pid != 0)//parent process
1862     {
1863         FdUniquePtr pipeptr(pipefd+1);
1864         close(pipefd[0]);
1865
1866         register_current_process_as_privilege_manager(user.getUid(), true);
1867
1868         //send info to child
1869         msg.uid = user.getUid();
1870         msg.gid = user.getGid();
1871
1872         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1873         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1874
1875         waitPid(pid);
1876
1877         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_other_app_id).c_str(),
1878                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1879     }
1880     if(pid == 0)
1881     {
1882         FdUniquePtr pipeptr(pipefd);
1883         close(pipefd[1]);
1884
1885         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1886         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1887
1888         //become admin privacy manager manager
1889         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1890         result = drop_root_privileges(msg.uid, msg.gid);
1891         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1892
1893         // use wildcard as appId
1894         PolicyEntry entry(SECURITY_MANAGER_ANY, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1895         entry.setMaxLevel("Allow");
1896
1897         addPolicyRequest.addEntry(entry);
1898         Api::sendPolicy(addPolicyRequest);
1899         exit(0);
1900     }
1901 }
1902
1903 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
1904 {
1905     const char *const update_app_id = "security_manager_15_update_app_id";
1906     const char *const update_privilege = "http://tizen.org/privilege/led";
1907     const char *const check_start_bucket = "";
1908     const std::string username("sm_test_15_username");
1909     PolicyRequest addPolicyRequest;
1910     CynaraTestAdmin::Admin admin;
1911     ScopedProcessLabel keepLabel;
1912
1913     struct message {
1914         uid_t uid;
1915         gid_t gid;
1916     } msg;
1917
1918     int pipefd[2];
1919     pid_t pid;
1920     int result = 0;
1921
1922     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1923
1924     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1925     user.create();
1926
1927     pid = fork();
1928     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1929     if (pid != 0)//parent process
1930     {
1931         FdUniquePtr pipeptr(pipefd+1);
1932         close(pipefd[0]);
1933
1934         register_current_process_as_privilege_manager(user.getUid(), false);
1935
1936         //send info to child
1937         msg.uid = user.getUid();
1938         msg.gid = user.getGid();
1939
1940         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
1941         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
1942
1943         waitPid(pid);
1944
1945         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
1946                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
1947     }
1948     if(pid == 0)
1949     {
1950         FdUniquePtr pipeptr(pipefd);
1951         close(pipefd[1]);
1952
1953         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
1954         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
1955
1956         //become admin privacy manager manager
1957         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
1958         result = drop_root_privileges(msg.uid, msg.gid);
1959         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
1960
1961         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
1962         entry.setLevel("Allow");
1963
1964         addPolicyRequest.addEntry(entry);
1965         Api::sendPolicy(addPolicyRequest);
1966         exit(0);
1967     }
1968 }
1969
1970 RUNNER_CHILD_TEST(security_manager_16_policy_levels_get)
1971 {
1972     const std::string username("sm_test_16_user_cynara_policy");
1973     CynaraTestAdmin::Admin admin;
1974     int pipefd[2];
1975     pid_t pid;
1976     int result = 0;
1977
1978     struct message {
1979         uid_t uid;
1980         gid_t gid;
1981     } msg;
1982
1983     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
1984
1985     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
1986     user.create();
1987
1988     pid = fork();
1989     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
1990     if (pid != 0)//parent process
1991     {
1992         FdUniquePtr pipeptr(pipefd+1);
1993         close(pipefd[0]);
1994
1995         //send info to child
1996         msg.uid = user.getUid();
1997         msg.gid = user.getGid();
1998
1999         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2000         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2001
2002         waitPid(pid);
2003     }
2004     if(pid == 0)
2005     {
2006         int ret;
2007         char** levels;
2008         std::string allow_policy, deny_policy;
2009         size_t count;
2010         FdUniquePtr pipeptr(pipefd);
2011         close(pipefd[1]);
2012
2013         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2014         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2015
2016         //become admin privacy manager manager
2017         result = drop_root_privileges(msg.uid, msg.gid);
2018         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2019
2020         // 3 should be there when ask-user is installed
2021         ret = security_manager_policy_levels_get(&levels, &count);
2022
2023         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
2024                 "Invlid return code: " << ret);
2025
2026         RUNNER_ASSERT_MSG(count == 3, "Invalid number of policy levels. Should be 3, instead there is: " << static_cast<int>(count));
2027
2028         deny_policy = std::string(levels[0]);
2029         allow_policy = std::string(levels[count-1]);
2030
2031         // first should always be Deny
2032         RUNNER_ASSERT_MSG(deny_policy.compare("Deny") == 0,
2033                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
2034
2035         // last should always be Allow
2036         RUNNER_ASSERT_MSG(allow_policy.compare("Allow") == 0,
2037                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
2038
2039         security_manager_policy_levels_free(levels, count);
2040         exit(0);
2041     }
2042 }
2043
2044 RUNNER_CHILD_TEST(security_manager_17_privacy_manager_delete_policy_for_self)
2045 {
2046     const char *const update_app_id = "security_manager_17_update_app_id";
2047     const char *const update_privilege = "http://tizen.org/privilege/led";
2048     const char *const check_start_bucket = "";
2049     const std::string username("sm_test_17_username");
2050     PolicyRequest addPolicyRequest;
2051     CynaraTestAdmin::Admin admin;
2052
2053     struct message {
2054         uid_t uid;
2055         gid_t gid;
2056     } msg;
2057
2058     int pipefd[2];
2059     int pipefd2[2];
2060     pid_t pid[2];
2061     int result = 0;
2062     ScopedProcessLabel keepLabel;
2063
2064     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2065     RUNNER_ASSERT_MSG((pipe(pipefd2) != -1),"second pipe failed");
2066
2067     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2068     user.create();
2069
2070     pid[0] = fork();
2071     RUNNER_ASSERT_MSG(pid[0] >= 0, "fork failed");
2072     if (pid[0] != 0)//parent process
2073     {
2074         FdUniquePtr pipeptr(pipefd+1);
2075         close(pipefd[0]);
2076
2077         register_current_process_as_privilege_manager(user.getUid(), false);
2078
2079         //send info to child
2080         msg.uid = user.getUid();
2081         msg.gid = user.getGid();
2082
2083         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2084         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2085
2086         waitPid(pid[0]);
2087
2088         admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2089                 std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_ALLOW, nullptr);
2090
2091         pid[1] = fork();
2092         if (pid[1] != 0)//parent process
2093         {
2094             FdUniquePtr pipeptr(pipefd2+1);
2095             close(pipefd2[0]);
2096
2097             //send info to child
2098             msg.uid = user.getUid();
2099             msg.gid = user.getGid();
2100
2101             ssize_t written = TEMP_FAILURE_RETRY(write(pipefd2[1], &msg, sizeof(struct message)));
2102             RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2103
2104             waitPid(pid[1]);
2105
2106             admin.adminCheck(check_start_bucket, false, generateAppLabel(update_app_id).c_str(),
2107                     std::to_string(static_cast<int>(msg.uid)).c_str(), update_privilege, CYNARA_ADMIN_DENY, nullptr);
2108         }
2109         if(pid[1] == 0)
2110         {
2111             FdUniquePtr pipeptr(pipefd2);
2112             close(pipefd2[1]);
2113
2114             ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd2[0], &msg, sizeof(struct message)));
2115             RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2116
2117             //become admin privacy manager manager
2118             Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2119             result = drop_root_privileges(msg.uid, msg.gid);
2120             RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2121
2122             // delete this entry
2123             PolicyRequest deletePolicyRequest;
2124             PolicyEntry deleteEntry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2125             deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
2126
2127             deletePolicyRequest.addEntry(deleteEntry);
2128             Api::sendPolicy(deletePolicyRequest);
2129             exit(0);
2130         }
2131     }
2132     if(pid[0] == 0)
2133     {
2134         FdUniquePtr pipeptr(pipefd);
2135         close(pipefd[1]);
2136
2137         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2138         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2139
2140         //become admin privacy manager manager
2141         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2142         result = drop_root_privileges(msg.uid, msg.gid);
2143         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2144
2145         PolicyEntry entry(update_app_id, std::to_string(static_cast<int>(msg.uid)), update_privilege);
2146         entry.setLevel("Allow");
2147
2148         addPolicyRequest.addEntry(entry);
2149         Api::sendPolicy(addPolicyRequest);
2150         exit(0);
2151     }
2152 }
2153
2154 RUNNER_CHILD_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
2155 {
2156     const std::string username("sm_test_17_user_name");
2157
2158     struct message {
2159         uid_t uid;
2160         gid_t gid;
2161         unsigned int privileges_count;
2162     } msg;
2163
2164     int pipefd[2];
2165     pid_t pid;
2166     int result = 0;
2167     ScopedProcessLabel keepLabel;
2168
2169     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2170
2171     pid = fork();
2172     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2173     if (pid != 0)//parent process
2174     {
2175         FdUniquePtr pipeptr(pipefd+1);
2176         close(pipefd[0]);
2177
2178         TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
2179         user.create();
2180
2181         unsigned int privileges_count = 0;
2182
2183         for(unsigned int i = 0; i < MANY_APPS.size(); ++i) {
2184             InstallRequest requestInst;
2185             requestInst.setAppId(MANY_APPS[i].c_str());
2186             requestInst.setPkgId(MANY_APPS_PKGS.at(MANY_APPS[i]).package.c_str());
2187             requestInst.setUid(user.getUid());
2188
2189             for (auto &priv : MANY_APPS_PRIVILEGES.at(i)) {
2190                 requestInst.addPrivilege(priv.c_str());
2191             };
2192
2193             Api::install(requestInst);
2194             privileges_count += MANY_APPS_PRIVILEGES.at(i).size();
2195         };
2196
2197         register_current_process_as_privilege_manager(user.getUid(), false);
2198         //the above call, registers 1 new privilege for the given user, hence the incrementation of below variable
2199         ++privileges_count;
2200
2201         //send info to child
2202         msg.uid = user.getUid();
2203         msg.gid = user.getGid();
2204         msg.privileges_count = privileges_count;
2205
2206         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2207         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2208
2209         waitPid(pid);
2210     }
2211     if(pid == 0)
2212     {
2213         FdUniquePtr pipeptr(pipefd);
2214         close(pipefd[1]);
2215
2216         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2217         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2218
2219         //become admin privacy manager manager
2220         Api::setProcessLabel(PRIVILEGE_MANAGER_APP.c_str());
2221         result = drop_root_privileges(msg.uid, msg.gid);
2222         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2223
2224         // filter by privilege
2225         std::vector<PolicyEntry> policyEntries;
2226         PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/internet");
2227         Api::getPolicy(filter, policyEntries);
2228
2229         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2230         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2 and is " << policyEntries.size());
2231
2232         // filter by other privilege
2233         policyEntries.clear();
2234         PolicyEntry filter2(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, "http://tizen.org/privilege/email");
2235         Api::getPolicy(filter2, policyEntries);
2236
2237         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2238         RUNNER_ASSERT_MSG(policyEntries.size() == 3, "Number of policies doesn't match - should be: 3 and is " << policyEntries.size());
2239
2240         // filter by appId
2241         policyEntries.clear();
2242         PolicyEntry filter3(MANY_APPS[4].c_str(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
2243         Api::getPolicy(filter3, policyEntries);
2244
2245         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
2246         RUNNER_ASSERT_MSG(policyEntries.size() == 4, "Number of policies doesn't match - should be: 4 and is " << policyEntries.size());
2247     }
2248 }
2249
2250 RUNNER_TEST(security_manager_18_user_cynara_policy)
2251 {
2252     const char *const MAIN_BUCKET = "MAIN";
2253     const char *const MANIFESTS_BUCKET = "MANIFESTS";
2254     const char *const ADMIN_BUCKET = "ADMIN";
2255     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
2256     const std::string username("sm_test_10_user_cynara_policy");
2257     CynaraTestAdmin::Admin admin;
2258     std::string uid_string;
2259     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2260     user.create();
2261     user.getUidString(uid_string);
2262
2263     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
2264     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
2265     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
2266
2267     user.remove();
2268     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
2269
2270     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2271     admin.listPolicies(MANIFESTS_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2272     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2273     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
2274 }
2275
2276 RUNNER_TEST(security_manager_19_security_manager_cmd_install)
2277 {
2278     int ret;
2279     const int SUCCESS = 0;
2280     const int FAILURE = 256;
2281     const std::string app_id = "security_manager_10_app";
2282     const std::string pkg_id = "security_manager_10_pkg";
2283     const std::string username("sm_test_10_user_name");
2284     std::string uid_string;
2285     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2286     user.create();
2287     user.getUidString(uid_string);
2288     const std::string path1 = appDirPath(user, app_id, pkg_id) + "/p1";
2289     const std::string path2 = appDirPath(user, app_id, pkg_id) + "/p2";
2290     const std::string pkgopt = " --pkg=" + pkg_id;
2291     const std::string appopt = " --app=" + app_id;
2292     const std::string uidopt = " --uid=" + uid_string;
2293
2294     mktreeSafe(path1.c_str(), 0);
2295     mktreeSafe(path2.c_str(), 0);
2296
2297     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
2298
2299     struct operation {
2300         std::string command;
2301         int expected_result;
2302     };
2303     std::vector<struct operation> operations = {
2304             {"security-manager-cmd", FAILURE},//no option
2305             {"security-manager-cmd --blah", FAILURE},//blah option is not known
2306             {"security-manager-cmd --help", SUCCESS},
2307             {"security-manager-cmd --install", FAILURE},//no params
2308             {"security-manager-cmd -i", FAILURE},//no params
2309             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
2310             {installcmd, SUCCESS},
2311             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
2312             {installcmd + " --path " + path1 + " rw", SUCCESS},
2313             {installcmd + " --path " + path1, FAILURE},//no path type
2314             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
2315             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
2316             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
2317     };
2318
2319     for (auto &op : operations) {
2320         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
2321         RUNNER_ASSERT_MSG(ret == op.expected_result,
2322                 "Unexpected result for command '" << op.command <<"': "
2323                 << ret << " Expected was: "<< op.expected_result);
2324     }
2325 }
2326
2327 RUNNER_TEST(security_manager_20_security_manager_cmd_users)
2328 {
2329     int ret;
2330     const int SUCCESS = 0;
2331     const int FAILURE = 256;
2332     const std::string username("sm_test_11_user_name");
2333     std::string uid_string;
2334     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL, false);
2335     user.create();
2336     user.getUidString(uid_string);
2337     const std::string uidopt = " --uid=" + uid_string;
2338
2339     struct operation {
2340         std::string command;
2341         int expected_result;
2342     };
2343     std::vector<struct operation> operations = {
2344             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
2345             {"security-manager-cmd -m", FAILURE},//no params
2346             {"security-manager-cmd -mr", FAILURE},//no uid
2347             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
2348             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
2349             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
2350             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
2351             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
2352             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
2353             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
2354             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
2355     };
2356
2357     for (auto &op : operations) {
2358         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
2359         RUNNER_ASSERT_MSG(ret == op.expected_result,
2360                 "Unexpected result for command '" << op.command <<"': "
2361                 << ret << " Expected was: "<< op.expected_result);
2362     }
2363 }
2364
2365 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
2366 {
2367     const int BUFFER_SIZE = 128;
2368     struct message {
2369         uid_t uid;
2370         gid_t gid;
2371         char buf[BUFFER_SIZE];
2372     } msg;
2373
2374     privileges_t admin_required_privs = {
2375             PRIVILEGE_MANAGER_SELF_PRIVILEGE,
2376             PRIVILEGE_MANAGER_ADMIN_PRIVILEGE};
2377     privileges_t manifest_privs = {
2378             "http://tizen.org/privilege/internet",
2379             "http://tizen.org/privilege/datasharing"};
2380     privileges_t real_privs_allow = {"http://tizen.org/privilege/datasharing"};
2381     privileges_t real_privs_deny = {"http://tizen.org/privilege/internet"};
2382
2383     const std::string pirivman_id = "sm_test_13_ADMIN_APP";
2384     const std::string pirivman_pkg_id = "sm_test_13_ADMIN_PKG";
2385     const std::string app_id = "sm_test_13_SOME_APP";
2386     const std::string pkg_id = "sm_test_13_SOME_PKG";
2387
2388     int pipefd[2];
2389     pid_t pid;
2390     int result = 0;
2391
2392     RUNNER_ASSERT_MSG((pipe(pipefd) != -1),"pipe failed");
2393     pid = fork();
2394     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
2395     if (pid != 0)//parent process
2396     {
2397         std::string childuidstr;
2398         TemporaryTestUser admin("sm_test_13_ADMIN_USER", GUM_USERTYPE_ADMIN, false);
2399         TemporaryTestUser child("sm_test_13_NORMAL_USER", GUM_USERTYPE_NORMAL, false);
2400
2401         InstallRequest request,request2;
2402         FdUniquePtr pipeptr(pipefd+1);
2403         close(pipefd[0]);
2404
2405         admin.create();
2406         child.create();
2407         child.getUidString(childuidstr);
2408
2409         //install privacy manager for admin
2410         request.setAppId(pirivman_id.c_str());
2411         request.setPkgId(pirivman_pkg_id.c_str());
2412         request.setUid(admin.getUid());
2413         for (auto &priv: admin_required_privs)
2414             request.addPrivilege(priv.c_str());
2415         Api::install(request);
2416
2417         //install app for child that has internet privilege
2418         request2.setAppId(app_id.c_str());
2419         request2.setPkgId(pkg_id.c_str());
2420         request2.setUid(child.getUid());
2421         for (auto &priv: manifest_privs)
2422             request2.addPrivilege(priv.c_str());
2423         Api::install(request2);
2424
2425         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2426                               manifest_privs, SM_NO_PRIVILEGES);
2427
2428         //send info to child
2429         msg.uid = admin.getUid();
2430         msg.gid = admin.getGid();
2431         strncpy (msg.buf, childuidstr.c_str(), BUFFER_SIZE);
2432
2433         ssize_t written = TEMP_FAILURE_RETRY(write(pipefd[1], &msg, sizeof(struct message)));
2434         RUNNER_ASSERT_MSG((written == sizeof(struct message)),"write failed");
2435
2436         waitPid(pid);
2437
2438         check_app_permissions(app_id.c_str(), pkg_id.c_str(), childuidstr.c_str(),
2439                               real_privs_allow, real_privs_deny);
2440     }
2441     if (pid == 0)//child
2442     {
2443         FdUniquePtr pipeptr(pipefd);
2444         close(pipefd[1]);
2445
2446         ssize_t fetched = TEMP_FAILURE_RETRY(read(pipefd[0], &msg, sizeof(struct message)));
2447         RUNNER_ASSERT_MSG(fetched == sizeof(struct message), "read failed");
2448
2449         //become admin privacy manager manager
2450         Api::setProcessLabel(pirivman_id.c_str());
2451         result = drop_root_privileges(msg.uid, msg.gid);
2452         RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
2453         PolicyRequest addPolicyReq;
2454         //change rights
2455         for (auto &denypriv:real_privs_deny) {
2456             /*this entry will deny some privileges for user whose uid (as c string)
2457               was sent in message's buf field.
2458               That user would be denying internet for child in this case*/
2459             PolicyEntry entry(SECURITY_MANAGER_ANY, msg.buf, denypriv);
2460             entry.setMaxLevel("Deny");
2461             addPolicyReq.addEntry(entry);
2462         }
2463         Api::sendPolicy(addPolicyReq);
2464         exit(0);
2465     }
2466 }
2467
2468 void setupPrivilegeGroups(const privileges_t &privileges, const std::vector<std::string> &groups)
2469 {
2470     TestSecurityManagerDatabase db;
2471     for (const auto &privilege : privileges) {
2472         db.setup_privilege_groups(privilege, groups);
2473     }
2474 }
2475
2476 std::vector<std::string> readPrivilegeGroups()
2477 {
2478     std::vector<std::string> groups;
2479     const static std::string privilegeGroupMappingPath("/usr/share/security-manager/policy/privilege-group.list");
2480     std::ifstream mappingFile(privilegeGroupMappingPath);
2481
2482     RUNNER_ASSERT_MSG(mappingFile.is_open(),
2483         "Unable to read group mapping file " << privilegeGroupMappingPath);
2484
2485     std::string line;
2486     std::regex r("^[^ #]+ +(.*)");
2487     while (std::getline(mappingFile, line)) {
2488         std::smatch m;
2489         if (std::regex_search(line, m, r))
2490             groups.push_back(m[1]);
2491     }
2492
2493     return groups;
2494 }
2495
2496 RUNNER_TEST(security_manager_22_groups_get)
2497 {
2498     setupPrivilegeGroups(SM_ALLOWED_PRIVILEGES, SM_ALLOWED_GROUPS);
2499
2500     std::unordered_set<std::string> groups;
2501     auto tmp = readPrivilegeGroups();
2502     groups.insert(tmp.begin(), tmp.end());
2503     groups.insert(SM_ALLOWED_GROUPS.begin(), SM_ALLOWED_GROUPS.end());
2504
2505     char ** c_groups;
2506     size_t count = 0;
2507
2508     Api::getSecurityManagerGroups(&c_groups, &count);
2509     RUNNER_ASSERT_MSG(count == groups.size(), "security_manager_groups_get should set count to: "
2510                       << groups.size() << " but count is: " << count);
2511
2512     for (const auto &group : groups) {
2513         bool found = false;
2514         for (size_t i = 0; i < count; ++i) {
2515             if (group == c_groups[i]) {
2516                 found = true;
2517                 break;
2518             }
2519         }
2520         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
2521     }
2522     security_manager_groups_free(c_groups, count);
2523 }
2524
2525 namespace {
2526 const int sm_app_shared_test_id = 27;
2527 const char *const sm_app_shared_id = "sm_test_27_app_id_full";
2528 const char *const sm_app_shared_another_in_package_id = "sm_test_27_app_2_id_full";
2529 const char *const sm_pkg_shared_id = "sm_test_27_pkg_id_full";
2530
2531 void test_success_worker(const std::string &appName, int test_num)
2532 {
2533     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2534
2535     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2536
2537     RUNNER_ASSERT_ERRNO_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) != -1,
2538         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName << " failed " << " to " << SM_OWNER_RW_OTHERS_RO_PATH );
2539 }
2540
2541 void test_fail_worker(const std::string &appName, int test_num)
2542 {
2543     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(test_num);
2544
2545     changeSecurityContext(generateAppLabel(appName), APP_UID, APP_GID);
2546
2547     RUNNER_ASSERT_MSG(::access(SM_OWNER_RW_OTHERS_RO_PATH.c_str(), R_OK|X_OK) == -1,
2548         "access (" << SM_OWNER_RW_OTHERS_RO_PATH << ") from " << appName
2549         << " surprisingly succeeded, while expecting fail");
2550 }
2551 }
2552
2553 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_PUBLIC_SHARING)
2554
2555 RUNNER_TEST(security_manager_27a_API2X_app_install)
2556 {
2557     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2558     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2559     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2560     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2561     prepare_app_env(sm_app_shared_test_id, true);
2562
2563     // install other apps
2564     for(const auto &app : MANY_APPS_PKGS) {
2565         InstallRequest requestInst;
2566         requestInst.setAppId(app.first.c_str());
2567         requestInst.setPkgId(app.second.package.c_str());
2568         requestInst.setAppTizenVersion(app.second.Tizen_ver.c_str());
2569
2570         Api::install(requestInst);
2571     };
2572
2573     // install
2574     {
2575         InstallRequest requestInst;
2576         requestInst.setAppId(sm_app_shared_id);
2577         requestInst.setPkgId(sm_pkg_shared_id);
2578         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2579         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2580         requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2581         requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2582         requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2583         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2584         requestInst.setAppTizenVersion("2.4");
2585         Api::install(requestInst);
2586     }
2587
2588     // another app in package
2589     {
2590         InstallRequest requestInst;
2591         requestInst.setAppId(sm_app_shared_another_in_package_id);
2592         requestInst.setPkgId(sm_pkg_shared_id);
2593         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2594         requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2595         requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2596         requestInst.setAppTizenVersion("2.4");
2597         Api::install(requestInst);
2598     }
2599
2600     /* Check records in the security-manager database */
2601     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2602                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2603     /* Check records in the security-manager database */
2604     check_app_after_install(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2605                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2606
2607     /* TODO: add parameters to this function */
2608     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2609
2610     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");
2611 }
2612
2613 RUNNER_CHILD_TEST(security_manager_27b_owner_1_have_access)
2614 {
2615     test_success_worker(sm_app_shared_id, sm_app_shared_test_id);
2616 }
2617
2618 RUNNER_CHILD_TEST(security_manager_27c_owner_2_have_access)
2619 {
2620     test_success_worker(sm_app_shared_another_in_package_id, sm_app_shared_test_id);
2621 }
2622
2623 RUNNER_CHILD_TEST(security_manager_27d_API2X_apps_have_access_app_1)
2624 {
2625     test_success_worker("security_manager_10_app_1", sm_app_shared_test_id);
2626 }
2627
2628 RUNNER_CHILD_TEST(security_manager_27e_API2X_apps_dont_have_access_app_2)
2629 {
2630     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2631 }
2632
2633 RUNNER_CHILD_TEST(security_manager_27f_API2X_apps_have_access_app_3)
2634 {
2635     test_success_worker("security_manager_10_app_3", sm_app_shared_test_id);
2636 }
2637
2638 RUNNER_CHILD_TEST(security_manager_27g_API2X_apps_dont_have_access_app_4)
2639 {
2640     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2641 }
2642
2643 RUNNER_CHILD_TEST(security_manager_27h_API2X_apps_have_access_app_5)
2644 {
2645     test_success_worker("security_manager_10_app_5", sm_app_shared_test_id);
2646 }
2647
2648
2649 RUNNER_TEST(security_manager_27i_API2X_app_uninstall)
2650 {
2651     {
2652         InstallRequest requestUninst;
2653         requestUninst.setAppId(sm_app_shared_id);
2654         Api::uninstall(requestUninst);
2655     }
2656     {
2657         InstallRequest requestUninst;
2658         requestUninst.setAppId(sm_app_shared_another_in_package_id);
2659         Api::uninstall(requestUninst);
2660     }
2661
2662     /* Check records in the security-manager database,
2663      * all previously allowed privileges should be removed */
2664     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2665                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2666     check_app_after_uninstall(sm_app_shared_another_in_package_id, sm_pkg_shared_id,
2667                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2668 }
2669
2670 RUNNER_TEST(security_manager_27j_API30_app_install)
2671 {
2672     std::string SM_RW_PATH = genRWPath(sm_app_shared_test_id);
2673     std::string SM_RO_PATH = genROPath(sm_app_shared_test_id);
2674     std::string SM_PUBLIC_RO_PATH = genPublicROPath(sm_app_shared_test_id);
2675     std::string SM_OWNER_RW_OTHERS_RO_PATH = genOwnerRWOthersROPath(sm_app_shared_test_id);
2676     prepare_app_env(sm_app_shared_test_id, true);
2677
2678     // install
2679     InstallRequest requestInst;
2680     requestInst.setAppId(sm_app_shared_id);
2681     requestInst.setPkgId(sm_pkg_shared_id);
2682     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[0].c_str());
2683     requestInst.addPrivilege(SM_ALLOWED_PRIVILEGES[1].c_str());
2684     requestInst.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
2685     requestInst.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
2686     requestInst.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
2687     requestInst.addPath(SM_OWNER_RW_OTHERS_RO_PATH, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
2688     requestInst.setAppTizenVersion("3.0");
2689
2690     Api::install(requestInst);
2691
2692     /* Check records in the security-manager database */
2693     check_app_after_install(sm_app_shared_id, sm_pkg_shared_id,
2694                             SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES, SM_ALLOWED_GROUPS);
2695
2696     /* TODO: add parameters to this function */
2697     check_app_path_after_install(sm_app_shared_test_id, sm_pkg_shared_id, true);
2698
2699     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");
2700 }
2701
2702 RUNNER_CHILD_TEST(security_manager_27k_API30_apps_dont_have_access_app_1)
2703 {
2704     test_fail_worker("security_manager_10_app_1", sm_app_shared_test_id);
2705 }
2706
2707 RUNNER_CHILD_TEST(security_manager_27l_API30_apps_dont_have_access_app_2)
2708 {
2709     test_fail_worker("security_manager_10_app_2", sm_app_shared_test_id);
2710 }
2711
2712 RUNNER_CHILD_TEST(security_manager_27m_API30_apps_dont_have_access_app_3)
2713 {
2714     test_fail_worker("security_manager_10_app_3", sm_app_shared_test_id);
2715 }
2716
2717 RUNNER_CHILD_TEST(security_manager_27n_API30_apps_dont_have_access_app_4)
2718 {
2719     test_fail_worker("security_manager_10_app_4", sm_app_shared_test_id);
2720 }
2721
2722 RUNNER_CHILD_TEST(security_manager_27o_API30_apps_dont_have_access_app_5)
2723 {
2724     test_fail_worker("security_manager_10_app_5", sm_app_shared_test_id);
2725 }
2726
2727 RUNNER_TEST(security_manager_27p_API30_app_uninstall)
2728 {
2729     InstallRequest requestUninst;
2730     requestUninst.setAppId(sm_app_shared_id);
2731
2732     Api::uninstall(requestUninst);
2733
2734     /* Check records in the security-manager database,
2735      * all previously allowed privileges should be removed */
2736     check_app_after_uninstall(sm_app_shared_id, sm_pkg_shared_id,
2737                               SM_ALLOWED_PRIVILEGES, TestSecurityManagerDatabase::REMOVED);
2738
2739     // install other apps
2740     for(const auto &app : MANY_APPS_PKGS) {
2741         InstallRequest requestUninst;
2742         requestUninst.setAppId(app.first);
2743
2744         Api::uninstall(requestUninst);
2745     };
2746 }
2747
2748 namespace {
2749 const char *const owner_access = "rwxat";
2750 const char *const target_path_access = "rxl";
2751 const char *const target_dir_access = "x";
2752 const char *const no_access = "";
2753
2754 void check_system_access(const std::string pathLabel, bool apply = true) {
2755     check_exact_smack_accesses("User", pathLabel, (apply ? owner_access : no_access));
2756     check_exact_smack_accesses("System", pathLabel, (apply ? owner_access : no_access));
2757 }
2758
2759 void check_owner_access(const std::string &ownerLabel, const std::string &pathLabel, bool apply = true) {
2760     check_exact_smack_accesses(ownerLabel, pathLabel, (apply ? owner_access : no_access));
2761 }
2762
2763 void check_target_access(const std::string &ownerPkgLabel, const std::string &targetLabel,
2764         const std::string &pathLabel, bool pathShared = true, bool anyPathShared = true) {
2765     check_exact_smack_accesses(targetLabel, pathLabel, (pathShared ? target_path_access : no_access));
2766     check_exact_smack_accesses(targetLabel, ownerPkgLabel, (anyPathShared ? target_dir_access : no_access));
2767 }
2768
2769 void check_path_label(const std::string &path, const std::string &expectedLabel) {
2770     char *label = nullptr;
2771     int ret = smack_new_label_from_path(path.c_str(), XATTR_NAME_SMACK, 0, &label);
2772     RUNNER_ASSERT_MSG(ret > 0, "smack_new_label_from_path failed for " << path);
2773     SmackLabelPtr realLabel(label);
2774     RUNNER_ASSERT_MSG(realLabel.get() == expectedLabel, "Fetched label from " << path << " different"
2775             " than expected, is : " << realLabel.get() << " should be " << expectedLabel);
2776 }
2777
2778 void createFile(const std::string &filePath)
2779 {
2780     //create temporary file and set label for it
2781     mode_t systemMask;
2782
2783     unlink(filePath.c_str());
2784     //allow to create file with 777 rights
2785     systemMask = umask(0000);
2786     int fd = open(filePath.c_str(), O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
2787     //restore system mask
2788     umask(systemMask);
2789     RUNNER_ASSERT_ERRNO_MSG(fd > -1, "Unable to create file for tests");
2790
2791     //for descriptor protection
2792     FdUniquePtr fd_ptr(&fd);
2793
2794     //change owner and group to user APP
2795     int ret = chown(filePath.c_str(), APP_UID, APP_GID);
2796     RUNNER_ASSERT_ERRNO_MSG(ret == 0, "Unable to change file owner");
2797 }
2798
2799 }
2800
2801 RUNNER_TEST_GROUP_INIT(SECURIT_MANAGER_PRIVATE_SHARING)
2802
2803 RUNNER_TEST(security_manager_30a_send_incomplete_req1)
2804 {
2805     SharingRequest request;
2806     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2807     request.setOwnerAppId("someOwner");
2808     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2809     request.setTargetAppId("someTarget");
2810     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2811 }
2812
2813 RUNNER_TEST(security_manager_30b_send_incomplete_req2)
2814 {
2815     SharingRequest request;
2816     request.setTargetAppId("someTarget");
2817     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2818     request.setOwnerAppId("someOwner");
2819     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2820 }
2821
2822 RUNNER_TEST(security_manager_30c_send_incomplete_req3)
2823 {
2824     SharingRequest request;
2825     const char *somePaths[] = {"path1", "path2"};
2826     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2827     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2828     request.setOwnerAppId("someOwner");
2829     Api::applySharing(request, SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
2830 }
2831
2832 RUNNER_TEST(security_manager_30d_unknown_owner)
2833 {
2834     // This test depends on order of checks in security-manager service implementation
2835     SharingRequest request;
2836     request.setOwnerAppId("ImPrettySureIDontExist");
2837     request.setTargetAppId("IDontMatter");
2838     const char *somePaths[] = {"path1", "path2"};
2839     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2840     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2841 }
2842
2843 struct PathInfo {
2844     const std::string &path;
2845     app_install_path_type path_type;
2846 };
2847
2848 static InstallRequest createInstallReq(const std::string &appName, const std::string &pkgName,
2849                                        const std::vector<PathInfo> &paths){
2850     InstallRequest req;
2851     req.setAppId(appName);
2852     req.setPkgId(pkgName);
2853     for (const auto &pathInfo : paths) {
2854         req.addPath(pathInfo.path, pathInfo.path_type);
2855     }
2856     return req;
2857 }
2858
2859 static InstallRequest createInstallReq(const AppInstallHelper &info,
2860                                        const std::vector<PathInfo> &paths = std::vector<PathInfo>()){
2861     return createInstallReq(info.getAppId(), info.getPkgId(), paths);
2862 }
2863
2864 static void clearLabels(const std::string &path) {
2865     int result = nftw(path.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
2866     RUNNER_ASSERT_MSG(result == 0, "Unable to remove Smack labels in " << path);
2867 }
2868
2869
2870 RUNNER_TEST(security_manager_30e_unknown_target)
2871 {
2872     // This test depends on order of checks in security-manager service implementation
2873     AppInstallHelper owner("installedApp");
2874     owner.revokeRules();
2875     owner.createInstallDir();
2876     InstallRequest ownerInst;
2877     ownerInst.setAppId(owner.getAppId());
2878     ownerInst.setPkgId(owner.getPkgId());
2879     Api::install(ownerInst);
2880
2881     SharingRequest request;
2882     request.setOwnerAppId(owner.getAppId());
2883     request.setTargetAppId("NowImPrettySureIDontExist");
2884     const char *somePaths[] = {"path1", "path2"};
2885     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2886     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
2887
2888     Api::uninstall(ownerInst);
2889 }
2890
2891 RUNNER_TEST(security_manager_30f_bad_paths)
2892 {
2893     // This test depends on order of checks in security-manager service implementation
2894     AppInstallHelper owner("installedApp");
2895     owner.revokeRules();
2896     owner.createInstallDir();
2897     InstallRequest ownerInst = createInstallReq(owner);
2898     Api::install(ownerInst);
2899
2900     AppInstallHelper target("secondInstalledApp");
2901     target.revokeRules();
2902     target.createInstallDir();
2903     InstallRequest targetInst = createInstallReq(target);
2904     Api::install(targetInst);
2905
2906     SharingRequest request;
2907     request.setOwnerAppId(owner.getAppId());
2908     request.setTargetAppId(target.getAppId());
2909
2910     const char *somePath = "/tmp/somePath";
2911     createFile(somePath);
2912     const char *somePaths[] = {somePath};
2913     request.addPaths(somePaths, sizeof(somePaths)/sizeof(somePaths[0]));
2914     Api::applySharing(request, SECURITY_MANAGER_ERROR_APP_NOT_PATH_OWNER);
2915
2916     Api::uninstall(ownerInst);
2917     Api::uninstall(targetInst);
2918 }
2919
2920 RUNNER_TEST(security_manager_31_simple_share)
2921 {
2922     std::vector<AppInstallHelper> helper {{"app31a"}, {"app31b"}};
2923     auto &owner = helper[0];
2924     auto &target = helper[1];
2925
2926     for (auto &e : helper) {
2927         e.revokeRules();
2928         e.createInstallDir();
2929     }
2930
2931     owner.createPrivateDir();
2932     owner.createSharedFile();
2933     clearLabels(owner.getInstallDir());
2934     InstallRequest ownerReq = createInstallReq(owner,
2935             {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
2936     Api::install(ownerReq);
2937
2938     InstallRequest targetReq = createInstallReq(target);
2939     Api::install(targetReq);
2940
2941     SharingRequest share1;
2942     std::string sharedPath = owner.getSharedPath();
2943     share1.setOwnerAppId(owner.getAppId());
2944     share1.setTargetAppId(target.getAppId());
2945     const char *path[] = {sharedPath.c_str()};
2946     share1.addPaths(path, 1);
2947     Api::applySharing(share1);
2948
2949     TestSecurityManagerDatabase db;
2950     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
2951     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
2952
2953     check_system_access(pathLabel1);
2954     check_owner_access(owner.generateAppLabel(), pathLabel1);
2955     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
2956     check_path_label(sharedPath, pathLabel1);
2957
2958     Api::dropSharing(share1);
2959     check_system_access(pathLabel1, false);
2960     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
2961     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
2962     check_path_label(sharedPath, owner.generatePkgLabel());
2963
2964     Api::uninstall(ownerReq);
2965     Api::uninstall(targetReq);
2966 }
2967
2968 RUNNER_TEST(security_manager_32_double_share)
2969 {
2970     std::vector<AppInstallHelper> helper {{"app32a"}, {"app32b"}};
2971     auto &owner = helper[0];
2972     auto &target = helper[1];
2973
2974     // cleanup
2975     for (auto &e : helper) {
2976         e.revokeRules();
2977         e.createInstallDir();
2978     }
2979     owner.createPrivateDir();
2980     owner.createSharedFile();
2981     clearLabels(owner.getInstallDir());
2982
2983     InstallRequest ownerReq = createInstallReq(owner,
2984             {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
2985     Api::install(ownerReq);
2986
2987     InstallRequest targetReq = createInstallReq(target);
2988     Api::install(targetReq);
2989
2990     SharingRequest share1;
2991     std::string sharedPath = owner.getSharedPath(0);
2992     share1.setOwnerAppId(owner.getAppId());
2993     share1.setTargetAppId(target.getAppId());
2994     const char *path[] = {sharedPath.c_str()};
2995     share1.addPaths(path, 1);
2996     Api::applySharing(share1);
2997
2998     TestSecurityManagerDatabase db;
2999     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3000     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3001
3002     check_system_access(pathLabel);
3003     check_owner_access(owner.generateAppLabel(), pathLabel);
3004     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3005     check_path_label(sharedPath, pathLabel);
3006
3007     Api::applySharing(share1);
3008     check_system_access(pathLabel);
3009     check_owner_access(owner.generateAppLabel(), pathLabel);
3010     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3011     check_path_label(sharedPath, pathLabel);
3012
3013     Api::dropSharing(share1);
3014     check_system_access(pathLabel);
3015     check_owner_access(owner.generateAppLabel(), pathLabel);
3016     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel);
3017     check_path_label(sharedPath, pathLabel);
3018
3019     Api::dropSharing(share1);
3020     check_system_access(pathLabel, false);
3021     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3022     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel, false, false);
3023     check_path_label(sharedPath, owner.generatePkgLabel());
3024
3025     Api::uninstall(ownerReq);
3026     Api::uninstall(targetReq);
3027 }
3028 RUNNER_TEST(security_manager_33_share_two_with_one)
3029 {
3030     std::vector<AppInstallHelper> helper {{"app33a"}, {"app33b"}};
3031     auto &owner = helper[0];
3032     auto &target = helper[1];
3033
3034     // cleanup
3035     for (auto &e : helper) {
3036         e.revokeRules();
3037         e.createInstallDir();
3038     }
3039     owner.createPrivateDir();
3040     owner.createSharedFile(0);
3041     owner.createSharedFile(1);
3042     clearLabels(owner.getInstallDir());
3043     InstallRequest ownerReq = createInstallReq(owner,
3044         {PathInfo{owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW},
3045          PathInfo{owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW}});
3046     Api::install(ownerReq);
3047
3048     InstallRequest targetReq = createInstallReq(target);
3049     Api::install(targetReq);
3050
3051     SharingRequest share1, share2;
3052     std::string sharedPath1 = owner.getSharedPath(0);
3053     std::string sharedPath2 = owner.getSharedPath(1);
3054     share1.setOwnerAppId(owner.getAppId());
3055     share2.setOwnerAppId(owner.getAppId());
3056     share1.setTargetAppId(target.getAppId());
3057     share2.setTargetAppId(target.getAppId());
3058     const char *path1[] = {sharedPath1.c_str()};
3059     const char *path2[] = {sharedPath2.c_str()};
3060     share1.addPaths(path1, 1);
3061     share2.addPaths(path2, 1);
3062
3063     Api::applySharing(share1);
3064     TestSecurityManagerDatabase db;
3065     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3066     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3067
3068     check_system_access(pathLabel1);
3069     check_owner_access(owner.generateAppLabel(), pathLabel1);
3070     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3071     check_path_label(sharedPath1, pathLabel1);
3072
3073     Api::applySharing(share2);
3074     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3075     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3076     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for private shared paths should be unique!");
3077
3078     check_system_access(pathLabel1);
3079     check_system_access(pathLabel2);
3080     check_owner_access(owner.generateAppLabel(), pathLabel1);
3081     check_owner_access(owner.generateAppLabel(), pathLabel2);
3082     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3083     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3084     check_path_label(sharedPath1, pathLabel1);
3085     check_path_label(sharedPath2, pathLabel2);
3086
3087     Api::dropSharing(share1);
3088     check_system_access(pathLabel1, false);
3089     check_system_access(pathLabel2);
3090     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3091     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false);
3092     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2);
3093     check_path_label(sharedPath1, owner.generatePkgLabel());
3094     check_path_label(sharedPath2, pathLabel2);
3095
3096     Api::dropSharing(share2);
3097     check_system_access(pathLabel1, false);
3098     check_system_access(pathLabel2, false);
3099     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3100     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3101     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3102     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel2, false, false);
3103     check_path_label(sharedPath1, owner.generatePkgLabel());
3104     check_path_label(sharedPath2, owner.generatePkgLabel());
3105
3106     Api::uninstall(ownerReq);
3107     Api::uninstall(targetReq);
3108 }
3109
3110 RUNNER_TEST(security_manager_34_share_one_with_two)
3111 {
3112     std::vector<AppInstallHelper> helper {{"app34a"}, {"app34b"}, {"app34c"}};
3113     auto &owner = helper[0];
3114     auto &target1 = helper[1];
3115     auto &target2 = helper[2];
3116
3117     // cleanup
3118     for (auto &e : helper) {
3119         e.revokeRules();
3120         e.createInstallDir();
3121     }
3122     owner.createPrivateDir();
3123     owner.createSharedFile();
3124     clearLabels(owner.getInstallDir());
3125
3126     InstallRequest ownerReq = createInstallReq(owner,
3127                                {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3128     Api::install(ownerReq);
3129
3130     for (size_t i = 1; i < helper.size(); i++) {
3131         InstallRequest targetReq = createInstallReq(helper[i]);
3132         Api::install(targetReq);
3133     }
3134
3135     SharingRequest share1, share2;
3136     std::string sharedPath = owner.getSharedPath(0).c_str();
3137     share1.setOwnerAppId(owner.getAppId());
3138     share2.setOwnerAppId(owner.getAppId());
3139     share1.setTargetAppId(target1.getAppId());
3140     share2.setTargetAppId(target2.getAppId());
3141
3142     const char *path[] = {sharedPath.c_str()};
3143     share1.addPaths(path, 1);
3144     share2.addPaths(path, 1);
3145
3146     Api::applySharing(share1);
3147     TestSecurityManagerDatabase db;
3148     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3149     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3150
3151     check_system_access(pathLabel);
3152     check_owner_access(owner.generateAppLabel(), pathLabel);
3153     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3154     check_path_label(sharedPath, pathLabel);
3155
3156     Api::applySharing(share2);
3157     check_system_access(pathLabel);
3158     check_owner_access(owner.generateAppLabel(), pathLabel);
3159     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3160     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3161     check_path_label(sharedPath, pathLabel);
3162
3163     Api::dropSharing(share1);
3164     check_system_access(pathLabel);
3165     check_owner_access(owner.generateAppLabel(), pathLabel);
3166     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3167     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3168     check_path_label(sharedPath, pathLabel);
3169
3170     Api::dropSharing(share2);
3171     check_system_access(pathLabel, false);
3172     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3173     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3174     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel, false, false);
3175     check_path_label(sharedPath, owner.generatePkgLabel());
3176
3177     Api::uninstall(ownerReq);
3178     for (size_t i = 1; i < helper.size(); i++) {
3179         InstallRequest targetReq = createInstallReq(helper[i]);
3180         Api::uninstall(targetReq);
3181     }
3182 }
3183
3184 RUNNER_TEST(security_manager_35_share_two_with_two)
3185 {
3186     std::vector<AppInstallHelper> helper {{"app35a"}, {"app35b"}, {"app35c"}};
3187     auto &owner = helper[0];
3188     auto &target1 = helper[1];
3189     auto &target2 = helper[2];
3190
3191     // cleanup
3192     for (auto &e : helper) {
3193         e.revokeRules();
3194         e.createInstallDir();
3195     }
3196     owner.createPrivateDir();
3197     owner.createSharedFile(0);
3198     owner.createSharedFile(1);
3199     clearLabels(owner.getInstallDir());
3200
3201     InstallRequest ownerReq = createInstallReq(owner,
3202            {PathInfo{owner.getSharedPath(0), SECURITY_MANAGER_PATH_RW},
3203             PathInfo{owner.getSharedPath(1), SECURITY_MANAGER_PATH_RW}});
3204
3205     Api::install(ownerReq);
3206
3207     for (size_t i = 1; i < helper.size(); i++) {
3208         InstallRequest targetReq = createInstallReq(helper[i]);
3209         Api::install(targetReq);
3210     }
3211
3212     SharingRequest share1, share2;
3213     std::string sharedPath1 = owner.getSharedPath(0).c_str();
3214     std::string sharedPath2 = owner.getSharedPath(1).c_str();
3215     share1.setOwnerAppId(owner.getAppId());
3216     share2.setOwnerAppId(owner.getAppId());
3217     share1.setTargetAppId(target1.getAppId());
3218     share2.setTargetAppId(target2.getAppId());
3219
3220     const char *path1[] = {sharedPath1.c_str()};
3221     const char *path2[] = {sharedPath2.c_str()};
3222     share1.addPaths(path1, 1);
3223     share2.addPaths(path2, 1);
3224
3225     Api::applySharing(share1);
3226     TestSecurityManagerDatabase db;
3227     std::string pathLabel1 = db.get_path_label(sharedPath1.c_str());
3228     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath1);
3229
3230     check_system_access(pathLabel1);
3231     check_owner_access(owner.generateAppLabel(), pathLabel1);
3232     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3233     check_path_label(sharedPath1, pathLabel1);
3234
3235     Api::applySharing(share2);
3236     std::string pathLabel2 = db.get_path_label(sharedPath2.c_str());
3237     RUNNER_ASSERT_MSG(!pathLabel2.empty(), "Couldn't fetch path label from database for file " << sharedPath2);
3238     RUNNER_ASSERT_MSG(pathLabel1 != pathLabel2, "Labels for shared files should be unique!");
3239
3240     check_system_access(pathLabel1);
3241     check_system_access(pathLabel2);
3242     check_owner_access(owner.generateAppLabel(), pathLabel1);
3243     check_owner_access(owner.generateAppLabel(), pathLabel2);
3244     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3245     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2);
3246     check_path_label(sharedPath1, pathLabel1);
3247     check_path_label(sharedPath2, pathLabel2);
3248
3249     Api::dropSharing(share2);
3250     check_system_access(pathLabel1);
3251     check_system_access(pathLabel2, false);
3252     check_owner_access(owner.generateAppLabel(), pathLabel1);
3253     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3254     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1);
3255     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3256     check_path_label(sharedPath1, pathLabel1);
3257     check_path_label(sharedPath2, owner.generatePkgLabel());
3258
3259     Api::dropSharing(share1);
3260     check_system_access(pathLabel1, false);
3261     check_system_access(pathLabel2, false);
3262     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3263     check_owner_access(owner.generateAppLabel(), pathLabel2, false);
3264     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel1, false, false);
3265     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel2, false, false);
3266     check_path_label(sharedPath1, owner.generatePkgLabel());
3267     check_path_label(sharedPath2, owner.generatePkgLabel());
3268     Api::uninstall(ownerReq);
3269     for (size_t i = 1; i < helper.size(); i++) {
3270         InstallRequest targetReq;
3271         targetReq.setAppId(helper[i].getAppId());
3272         targetReq.setPkgId(helper[i].getAppId());
3273         Api::uninstall(targetReq);
3274     }
3275 }
3276
3277 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_TRUSTED_SHARING)
3278
3279 RUNNER_TEST(security_manager_35_share_uninstall_target) {
3280     std::vector<AppInstallHelper> helper {{"app35aa"}, {"app35bb"}};
3281     auto &owner = helper[0];
3282     auto &target = helper[1];
3283
3284     for (auto &e : helper) {
3285         e.revokeRules();
3286         e.createInstallDir();
3287     }
3288
3289     owner.createPrivateDir();
3290     owner.createSharedFile();
3291     clearLabels(owner.getInstallDir());
3292
3293     InstallRequest ownerReq = createInstallReq(owner,
3294                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3295     Api::install(ownerReq);
3296
3297     InstallRequest targetReq = createInstallReq(target);
3298     Api::install(targetReq);
3299
3300     SharingRequest share1;
3301     std::string sharedPath = owner.getSharedPath();
3302     share1.setOwnerAppId(owner.getAppId());
3303     share1.setTargetAppId(target.getAppId());
3304     const char *path[] = {sharedPath.c_str()};
3305     share1.addPaths(path, 1);
3306     Api::applySharing(share1);
3307
3308     TestSecurityManagerDatabase db;
3309     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3310     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3311
3312     check_system_access(pathLabel1);
3313     check_owner_access(owner.generateAppLabel(), pathLabel1);
3314     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3315     check_path_label(sharedPath, pathLabel1);
3316
3317     Api::uninstall(targetReq);
3318
3319     check_system_access(pathLabel1, false);
3320     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3321     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3322     check_path_label(sharedPath, owner.generatePkgLabel());
3323
3324     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3325     Api::uninstall(ownerReq);
3326 }
3327
3328 RUNNER_TEST(security_manager_35_share_uninstall_owner) {
3329     std::vector<AppInstallHelper> helper {{"app35aaa"}, {"app35bbb"}};
3330     auto &owner = helper[0];
3331     auto &target = helper[1];
3332
3333     for (auto &e : helper) {
3334         e.revokeRules();
3335         e.createInstallDir();
3336     }
3337
3338     owner.createPrivateDir();
3339     owner.createSharedFile();
3340
3341     clearLabels(owner.getInstallDir());
3342
3343     InstallRequest ownerReq = createInstallReq(owner,
3344                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3345     Api::install(ownerReq);
3346
3347     InstallRequest targetReq = createInstallReq(target);
3348     Api::install(targetReq);
3349
3350     SharingRequest share1;
3351     std::string sharedPath = owner.getSharedPath();
3352     share1.setOwnerAppId(owner.getAppId());
3353     share1.setTargetAppId(target.getAppId());
3354     const char *path[] = {sharedPath.c_str()};
3355     share1.addPaths(path, 1);
3356     Api::applySharing(share1);
3357
3358     TestSecurityManagerDatabase db;
3359     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3360     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3361
3362     check_system_access(pathLabel1);
3363     check_owner_access(owner.generateAppLabel(), pathLabel1);
3364     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3365     check_path_label(sharedPath, pathLabel1);
3366
3367     owner.removePaths();
3368     Api::uninstall(ownerReq);
3369
3370     check_system_access(pathLabel1, false);
3371     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3372     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3373
3374     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3375     Api::uninstall(targetReq);
3376 }
3377
3378 RUNNER_TEST(security_manager_36_share_pkg_owner_uninstall) {
3379     std::vector<AppInstallHelper> helper {{"app36a", "pkg1"}, {"app36b", "pkg1"}, {"app36c", "pkg2"}};
3380     auto &owner = helper[0];
3381     auto &pkgApp = helper[1];
3382     auto &target = helper[2];
3383
3384     for (auto &e : helper) {
3385         e.revokeRules();
3386         e.createInstallDir();
3387     }
3388
3389     owner.createPrivateDir();
3390     owner.createSharedFile();
3391     clearLabels(owner.getInstallDir());
3392
3393     InstallRequest ownerReq = createInstallReq(owner,
3394                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3395     Api::install(ownerReq);
3396
3397     InstallRequest pkgAppReq = createInstallReq(pkgApp);
3398     Api::install(pkgAppReq);
3399     InstallRequest targetReq = createInstallReq(target);
3400     Api::install(targetReq);
3401
3402     SharingRequest share1;
3403     std::string sharedPath = owner.getSharedPath();
3404     share1.setOwnerAppId(owner.getAppId());
3405     share1.setTargetAppId(target.getAppId());
3406     const char *path[] = {sharedPath.c_str()};
3407     share1.addPaths(path, 1);
3408     Api::applySharing(share1);
3409
3410     TestSecurityManagerDatabase db;
3411     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3412     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3413
3414     check_system_access(pathLabel1);
3415     check_owner_access(owner.generateAppLabel(), pathLabel1);
3416     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3417     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3418     check_path_label(sharedPath, pathLabel1);
3419
3420     owner.removePaths();
3421     Api::uninstall(ownerReq);
3422
3423     check_system_access(pathLabel1, false);
3424     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3425     check_owner_access(pkgApp.generateAppLabel(), pathLabel1, false);
3426     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3427
3428     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3429     Api::uninstall(pkgAppReq);
3430     Api::uninstall(targetReq);
3431 }
3432
3433 RUNNER_TEST(security_manager_36_share_pkg_owner_drop) {
3434     std::vector<AppInstallHelper> helper {{"app36aa", "pkg1"}, {"app36bb", "pkg1"}, {"app36cc", "pkg2"}};
3435     auto &owner = helper[0];
3436     auto &pkgApp = helper[1];
3437     auto &target = helper[2];
3438
3439     for (auto &e : helper) {
3440         e.revokeRules();
3441         e.createInstallDir();
3442     }
3443
3444     owner.createPrivateDir();
3445     owner.createSharedFile();
3446     clearLabels(owner.getInstallDir());
3447
3448     InstallRequest ownerReq = createInstallReq(owner,
3449                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3450     Api::install(ownerReq);
3451
3452     InstallRequest pkgAppReq = createInstallReq(pkgApp);
3453     Api::install(pkgAppReq);
3454     InstallRequest targetReq = createInstallReq(target);
3455     Api::install(targetReq);
3456
3457     SharingRequest share1;
3458     std::string sharedPath = owner.getSharedPath();
3459     share1.setOwnerAppId(owner.getAppId());
3460     share1.setTargetAppId(target.getAppId());
3461     const char *path[] = {sharedPath.c_str()};
3462     share1.addPaths(path, 1);
3463     Api::applySharing(share1);
3464
3465     TestSecurityManagerDatabase db;
3466     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3467     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3468
3469     check_system_access(pathLabel1);
3470     check_owner_access(owner.generateAppLabel(), pathLabel1);
3471     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3472     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3473     check_path_label(sharedPath, pathLabel1);
3474
3475     Api::dropSharing(share1);
3476
3477     check_system_access(pathLabel1, false);
3478     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3479     check_owner_access(pkgApp.generateAppLabel(), pathLabel1, false);
3480     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3481     check_path_label(sharedPath, owner.generatePkgLabel());
3482
3483     Api::uninstall(ownerReq);
3484     Api::uninstall(pkgAppReq);
3485     Api::uninstall(targetReq);
3486 }
3487
3488 RUNNER_TEST(security_manager_36_share_pkg_target_uninstall) {
3489     std::vector<AppInstallHelper> helper {{"app36aaa", "pkg1"}, {"app36bbb", "pkg1"}, {"app36ccc", "pkg2"}};
3490     auto &owner = helper[0];
3491     auto &pkgApp = helper[1];
3492     auto &target = helper[2];
3493
3494     for (auto &e : helper) {
3495         e.revokeRules();
3496         e.createInstallDir();
3497     }
3498
3499     owner.createPrivateDir();
3500     owner.createSharedFile();
3501     clearLabels(owner.getInstallDir());
3502
3503     InstallRequest ownerReq = createInstallReq(owner,
3504                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3505     Api::install(ownerReq);
3506
3507     InstallRequest pkgAppReq = createInstallReq(pkgApp);
3508     Api::install(pkgAppReq);
3509     InstallRequest targetReq = createInstallReq(target);
3510     Api::install(targetReq);
3511
3512     SharingRequest share1;
3513     std::string sharedPath = owner.getSharedPath();
3514     share1.setOwnerAppId(owner.getAppId());
3515     share1.setTargetAppId(target.getAppId());
3516     const char *path[] = {sharedPath.c_str()};
3517     share1.addPaths(path, 1);
3518     Api::applySharing(share1);
3519
3520     TestSecurityManagerDatabase db;
3521     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3522     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3523
3524     check_system_access(pathLabel1);
3525     check_owner_access(owner.generateAppLabel(), pathLabel1);
3526     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3527     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3528     check_path_label(sharedPath, pathLabel1);
3529
3530     Api::uninstall(targetReq);
3531
3532     check_system_access(pathLabel1, false);
3533     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3534     check_owner_access(pkgApp.generateAppLabel(), pathLabel1, false);
3535     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3536     check_path_label(sharedPath, owner.generatePkgLabel());
3537
3538     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3539
3540     Api::uninstall(ownerReq);
3541     Api::uninstall(pkgAppReq);
3542 }
3543
3544 RUNNER_TEST(security_manager_37_pkg_double_share_target_uninstall) {
3545     std::vector<AppInstallHelper> helper {{"app37a", "pkg1"}, {"app37b", "pkg1"}, {"app37c", "pkg2"}};
3546     auto &owner = helper[0];
3547     auto &pkgApp = helper[1];
3548     auto &target = helper[2];
3549
3550     for (auto &e : helper) {
3551         e.revokeRules();
3552         e.createInstallDir();
3553     }
3554
3555     owner.createPrivateDir();
3556     owner.createSharedFile();
3557     clearLabels(owner.getInstallDir());
3558
3559     InstallRequest ownerReq = createInstallReq(owner,
3560                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3561     Api::install(ownerReq);
3562
3563     InstallRequest pkgAppReq = createInstallReq(pkgApp);
3564     Api::install(pkgAppReq);
3565     InstallRequest targetReq = createInstallReq(target);
3566     Api::install(targetReq);
3567
3568     SharingRequest share1;
3569     std::string sharedPath = owner.getSharedPath();
3570     share1.setOwnerAppId(owner.getAppId());
3571     share1.setTargetAppId(target.getAppId());
3572     const char *path[] = {sharedPath.c_str()};
3573     share1.addPaths(path, 1);
3574     Api::applySharing(share1);
3575
3576     TestSecurityManagerDatabase db;
3577     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3578     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3579
3580     check_system_access(pathLabel1);
3581     check_owner_access(owner.generateAppLabel(), pathLabel1);
3582     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3583     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3584     check_path_label(sharedPath, pathLabel1);
3585
3586     Api::applySharing(share1);
3587
3588     check_system_access(pathLabel1);
3589     check_owner_access(owner.generateAppLabel(), pathLabel1);
3590     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3591     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3592     check_path_label(sharedPath, pathLabel1);
3593
3594     Api::uninstall(targetReq);
3595
3596     check_system_access(pathLabel1, false);
3597     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3598     check_owner_access(pkgApp.generateAppLabel(), pathLabel1, false);
3599     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3600     check_path_label(sharedPath, owner.generatePkgLabel());
3601
3602     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3603
3604     Api::uninstall(ownerReq);
3605     Api::uninstall(pkgAppReq);
3606 }
3607
3608 RUNNER_TEST(security_manager_37_pkg_double_share_owner_uninstall) {
3609     std::vector<AppInstallHelper> helper {{"app37aa", "pkg1"}, {"app37bb", "pkg1"}, {"app37cc", "pkg2"}};
3610     auto &owner = helper[0];
3611     auto &pkgApp = helper[1];
3612     auto &target = helper[2];
3613
3614     for (auto &e : helper) {
3615         e.revokeRules();
3616         e.createInstallDir();
3617     }
3618
3619     owner.createPrivateDir();
3620     owner.createSharedFile();
3621     clearLabels(owner.getInstallDir());
3622
3623     InstallRequest ownerReq = createInstallReq(owner,
3624                                    {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3625     Api::install(ownerReq);
3626
3627     InstallRequest pkgAppReq = createInstallReq(pkgApp);
3628     Api::install(pkgAppReq);
3629     InstallRequest targetReq = createInstallReq(target);
3630     Api::install(targetReq);
3631
3632     SharingRequest share1;
3633     std::string sharedPath = owner.getSharedPath();
3634     share1.setOwnerAppId(owner.getAppId());
3635     share1.setTargetAppId(target.getAppId());
3636     const char *path[] = {sharedPath.c_str()};
3637     share1.addPaths(path, 1);
3638     Api::applySharing(share1);
3639
3640     TestSecurityManagerDatabase db;
3641     std::string pathLabel1 = db.get_path_label(sharedPath.c_str());
3642     RUNNER_ASSERT_MSG(!pathLabel1.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3643
3644     check_system_access(pathLabel1);
3645     check_owner_access(owner.generateAppLabel(), pathLabel1);
3646     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3647     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3648     check_path_label(sharedPath, pathLabel1);
3649
3650     Api::applySharing(share1);
3651
3652     check_system_access(pathLabel1);
3653     check_owner_access(owner.generateAppLabel(), pathLabel1);
3654     check_owner_access(pkgApp.generateAppLabel(), pathLabel1);
3655     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1);
3656     check_path_label(sharedPath, pathLabel1);
3657
3658     owner.removePaths();
3659     Api::uninstall(ownerReq);
3660
3661     check_system_access(pathLabel1, false);
3662     check_owner_access(owner.generateAppLabel(), pathLabel1, false);
3663     check_owner_access(pkgApp.generateAppLabel(), pathLabel1, false);
3664     check_target_access(owner.generatePkgLabel(), target.generateAppLabel(), pathLabel1, false, false);
3665
3666     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3667
3668     Api::uninstall(targetReq);
3669     Api::uninstall(pkgAppReq);
3670 }
3671
3672 RUNNER_TEST(security_manager_38_share_one_with_two_uninstall_target)
3673 {
3674     std::vector<AppInstallHelper> helper {{"app38a"}, {"app38b"}, {"app38c"}};
3675     auto &owner = helper[0];
3676     auto &target1 = helper[1];
3677     auto &target2 = helper[2];
3678
3679     // cleanup
3680     for (auto &e : helper) {
3681         e.revokeRules();
3682         e.createInstallDir();
3683     }
3684     owner.createPrivateDir();
3685     owner.createSharedFile();
3686     clearLabels(owner.getInstallDir());
3687
3688     InstallRequest ownerReq = createInstallReq(owner,
3689                                {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3690     Api::install(ownerReq);
3691
3692
3693     InstallRequest targetReq1 = createInstallReq(target1);
3694     Api::install(targetReq1);
3695     InstallRequest targetReq2 = createInstallReq(target2);
3696     Api::install(targetReq2);
3697
3698     SharingRequest share1, share2;
3699     std::string sharedPath = owner.getSharedPath(0).c_str();
3700     share1.setOwnerAppId(owner.getAppId());
3701     share2.setOwnerAppId(owner.getAppId());
3702     share1.setTargetAppId(target1.getAppId());
3703     share2.setTargetAppId(target2.getAppId());
3704
3705     const char *path[] = {sharedPath.c_str()};
3706     share1.addPaths(path, 1);
3707     share2.addPaths(path, 1);
3708
3709     Api::applySharing(share1);
3710     TestSecurityManagerDatabase db;
3711     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3712     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3713
3714     check_system_access(pathLabel);
3715     check_owner_access(owner.generateAppLabel(), pathLabel);
3716     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3717     check_path_label(sharedPath, pathLabel);
3718
3719     Api::applySharing(share2);
3720     check_system_access(pathLabel);
3721     check_owner_access(owner.generateAppLabel(), pathLabel);
3722     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3723     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3724     check_path_label(sharedPath, pathLabel);
3725
3726     Api::uninstall(targetReq1);
3727     check_system_access(pathLabel);
3728     check_owner_access(owner.generateAppLabel(), pathLabel);
3729     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3730     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3731     check_path_label(sharedPath, pathLabel);
3732
3733     Api::dropSharing(share2);
3734     check_system_access(pathLabel, false);
3735     check_owner_access(owner.generateAppLabel(), pathLabel, false);
3736     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3737     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel, false, false);
3738     check_path_label(sharedPath, owner.generatePkgLabel());
3739
3740     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3741     Api::uninstall(ownerReq);
3742     Api::uninstall(targetReq2);
3743 }
3744
3745 RUNNER_TEST(security_manager_38_share_one_with_two_uninstall_owner)
3746 {
3747     std::vector<AppInstallHelper> helper {{"app38aa"}, {"app38bb"}, {"app38cc"}};
3748     auto &owner = helper[0];
3749     auto &target1 = helper[1];
3750     auto &target2 = helper[2];
3751
3752     // cleanup
3753     for (auto &e : helper) {
3754         e.revokeRules();
3755         e.createInstallDir();
3756     }
3757     owner.createPrivateDir();
3758     owner.createSharedFile();
3759     clearLabels(owner.getInstallDir());
3760
3761     InstallRequest ownerReq = createInstallReq(owner,
3762                                {PathInfo{owner.getSharedPath(), SECURITY_MANAGER_PATH_RW}});
3763     Api::install(ownerReq);
3764
3765
3766     InstallRequest targetReq1 = createInstallReq(target1);
3767     Api::install(targetReq1);
3768     InstallRequest targetReq2 = createInstallReq(target2);
3769     Api::install(targetReq2);
3770
3771     SharingRequest share1, share2;
3772     std::string sharedPath = owner.getSharedPath(0).c_str();
3773     share1.setOwnerAppId(owner.getAppId());
3774     share2.setOwnerAppId(owner.getAppId());
3775     share1.setTargetAppId(target1.getAppId());
3776     share2.setTargetAppId(target2.getAppId());
3777
3778     const char *path[] = {sharedPath.c_str()};
3779     share1.addPaths(path, 1);
3780     share2.addPaths(path, 1);
3781
3782     Api::applySharing(share1);
3783     TestSecurityManagerDatabase db;
3784     std::string pathLabel = db.get_path_label(sharedPath.c_str());
3785     RUNNER_ASSERT_MSG(!pathLabel.empty(), "Couldn't fetch path label from database for file " << sharedPath);
3786
3787     check_system_access(pathLabel);
3788     check_owner_access(owner.generateAppLabel(), pathLabel);
3789     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3790     check_path_label(sharedPath, pathLabel);
3791
3792     Api::applySharing(share2);
3793     check_system_access(pathLabel);
3794     check_owner_access(owner.generateAppLabel(), pathLabel);
3795     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel);
3796     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel);
3797     check_path_label(sharedPath, pathLabel);
3798
3799     owner.removePaths();
3800     Api::uninstall(ownerReq);
3801     check_system_access(pathLabel, false);
3802     check_owner_access(owner.generateAppLabel(), pathLabel,false);
3803     check_target_access(owner.generatePkgLabel(), target1.generateAppLabel(), pathLabel, false, false);
3804     check_target_access(owner.generatePkgLabel(), target2.generateAppLabel(), pathLabel, false, false);
3805
3806     Api::dropSharing(share1, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3807     Api::dropSharing(share2, SECURITY_MANAGER_ERROR_APP_UNKNOWN);
3808     Api::uninstall(targetReq1);
3809     Api::uninstall(targetReq2);
3810 }
3811
3812 RUNNER_TEST(security_manager_40_set_wrong_author_id)
3813 {
3814     InstallRequest requestInst;
3815
3816     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3817         security_manager_app_inst_req_set_author_id(requestInst.get(), NULL));
3818
3819     RUNNER_ASSERT(SECURITY_MANAGER_ERROR_INPUT_PARAM ==
3820         security_manager_app_inst_req_set_author_id(requestInst.get(), ""));
3821 }
3822
3823 RUNNER_TEST(security_manager_41_set_author_id_multiple_times)
3824 {
3825     for(unsigned int i=0; i<10; ++i) {
3826         std::string authorId = "some-author-id" + std::to_string(i);
3827
3828         InstallRequest requestInst;
3829         requestInst.setAuthorId(authorId);
3830     }
3831 }
3832
3833 RUNNER_TEST(security_manager_43_app_install_with_trusted_path)
3834 {
3835     std::vector<AppInstallHelper> helper {{"app43a"}, {"app43b"}, {"app43c"}};
3836     auto &provider  = helper[0];
3837     auto &user      = helper[1];
3838     auto &untrusted = helper[2];
3839
3840     TestSecurityManagerDatabase dbtest;
3841     const char *author_id = "custom_author_id_test 41";
3842
3843     const char *const trusted_access = "rwxatl";
3844     const char *const system_access = "rwxatl";
3845
3846     int result;
3847
3848     // cleanup
3849     for (auto &e : helper) {
3850         e.revokeRules();
3851         e.createInstallDir();
3852         e.createTrustedDir();
3853     }
3854
3855     result = nftw(provider.getInstallDir().c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
3856     RUNNER_ASSERT_MSG(result == 0, "Unable to set Smack labels in " << SM_TRUSTED_PATH);
3857
3858     // install app with shared/trusted dir
3859     InstallRequest trustingApp;
3860     trustingApp.setAppId(provider.getAppId());
3861     trustingApp.setPkgId(provider.getPkgId());
3862     trustingApp.setAuthorId("author id to be overwritten");
3863     trustingApp.setAuthorId(author_id);
3864     trustingApp.addPath(provider.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3865     Api::install(trustingApp);
3866
3867     int64_t authorDb = dbtest.get_author_id(author_id);
3868     const std::string trusted_label = std::string("User::Author::") + std::to_string(authorDb);
3869
3870     // check trusted path label
3871     nftw_expected_label = trusted_label;
3872     nftw_expected_transmute = true;
3873     nftw_expected_exec = false;
3874
3875     // check labels
3876     result = nftw(provider.getTrustedDir().c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
3877     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << SM_TRUSTED_PATH);
3878
3879     // check rules
3880     check_exact_access("System", trusted_label, system_access);
3881     check_exact_access("User", trusted_label, system_access);
3882     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, trusted_access);
3883     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3884
3885     // install trusted app
3886     InstallRequest trustedApp;
3887     trustedApp.setAppId(user.getAppId());
3888     trustedApp.setPkgId(user.getPkgId());
3889     trustedApp.setAuthorId(author_id);
3890     Api::install(trustedApp);
3891
3892     // check rules
3893     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3894     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3895
3896     // install untrusted app
3897     InstallRequest untrustedApp;
3898     untrustedApp.setAppId(untrusted.getAppId());
3899     untrustedApp.setPkgId(untrusted.getPkgId());
3900     Api::install(untrustedApp);
3901
3902     // check rules
3903     check_exact_access(generateAppLabel(untrusted.getAppId()), trusted_label, "");
3904     check_exact_access(generatePkgLabel(untrusted.getPkgId()), trusted_label, "");
3905
3906     // uninstall trusting app
3907     Api::uninstall(trustingApp);
3908
3909     // there's still one app with author id, rules should be kept
3910     check_exact_access("System", trusted_label, system_access);
3911     check_exact_access("User", trusted_label, system_access);
3912     check_exact_access(generateAppLabel(provider.getAppId()), trusted_label, "");
3913     check_exact_access(generatePkgLabel(provider.getPkgId()), trusted_label, "");
3914     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, trusted_access);
3915     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3916
3917     Api::uninstall(trustedApp);
3918
3919     // no more apps with author id
3920     check_exact_access("System", trusted_label, "");
3921     check_exact_access("User", trusted_label, "");
3922     check_exact_access(generateAppLabel(user.getAppId()), trusted_label, "");
3923     check_exact_access(generatePkgLabel(user.getPkgId()), trusted_label, "");
3924
3925     Api::uninstall(untrustedApp);
3926 }
3927
3928
3929 RUNNER_TEST(security_manager_44_app_install_with_trusted_path_no_author_id)
3930 {
3931     AppInstallHelper help("app44");
3932     help.createInstallDir();
3933     help.createTrustedDir();
3934
3935     // install app with shared/trusted dir but without authors id
3936     InstallRequest app;
3937     app.setAppId(help.getAppId());
3938     app.setPkgId(help.getPkgId());
3939     app.addPath(help.getTrustedDir(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3940     Api::install(app, SECURITY_MANAGER_ERROR_INPUT_PARAM);
3941 }
3942
3943 RUNNER_TEST(security_manager_45_test_authorId_identificator_creation)
3944 {
3945     std::vector<AppInstallHelper> helper {{"a45"}, {"b45"}};
3946     auto &trusted1 = helper[0];
3947     auto &trusted2 = helper[1];
3948
3949     TestSecurityManagerDatabase dbtest;
3950     const char *authorId1 = "custom_author_id_test a45";
3951     const char *authorId2 = "custom_author_id_test b45";
3952
3953     // cleanup
3954     for (auto &e : helper) {
3955         e.revokeRules();
3956         e.createInstallDir();
3957         e.createTrustedDir();
3958     }
3959
3960     // install app with shared/trusted dir
3961     InstallRequest trustingApp;
3962     trustingApp.setAppId(trusted1.getAppId());
3963     trustingApp.setPkgId(trusted1.getPkgId());
3964     trustingApp.setAuthorId(authorId1);
3965     trustingApp.addPath(trusted1.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
3966     Api::install(trustingApp);
3967
3968     int64_t authorDb1 = dbtest.get_author_id(authorId1);
3969
3970     // install trusted app
3971     InstallRequest trustedApp;
3972     trustedApp.setAppId(trusted2.getAppId());
3973     trustedApp.setPkgId(trusted2.getPkgId());
3974     trustedApp.setAuthorId(authorId2);
3975     Api::install(trustedApp);
3976
3977     int64_t authorDb2 = dbtest.get_author_id(authorId2);
3978
3979     Api::uninstall(trustingApp);
3980     Api::uninstall(trustedApp);
3981
3982     RUNNER_ASSERT(authorDb1 != authorDb2);
3983 }
3984
3985 RUNNER_TEST(security_manager_46_pkgId_deinstalation_test)
3986 {
3987     /* Description:
3988      * Lets assume that app1 and app2 are part of pkg1.
3989      * Deinstalation of app1 mustnot remove rules:
3990      * System PKG1Label rwxatl
3991      * User PKGLabel rwxatl
3992      */
3993
3994     std::vector<AppInstallHelper> helper {{"a46"}, {"b46"}};
3995     auto &trusted1 = helper[0];
3996     auto &trusted2 = helper[1];
3997
3998     std::string authorId1 = "author46XYZ";
3999
4000     for (auto &e : helper) {
4001         e.revokeRules();
4002         e.createInstallDir();
4003         e.createTrustedDir();
4004     }
4005
4006     InstallRequest trustingApp;
4007     trustingApp.setAppId(trusted1.getAppId());
4008     trustingApp.setPkgId(trusted1.getPkgId());
4009     trustingApp.setAuthorId(authorId1);
4010     trustingApp.addPath(trusted1.getTrustedDir().c_str(), SECURITY_MANAGER_PATH_TRUSTED_RW);
4011     Api::install(trustingApp);
4012
4013     InstallRequest trustingApp2;
4014     trustingApp2.setAppId(trusted2.getAppId());
4015     trustingApp2.setPkgId(trusted1.getPkgId()); // both apps will be part of same pkgId
4016     trustingApp2.setAuthorId(authorId1);
4017     Api::install(trustingApp2);
4018
4019     check_exact_access("System", generateAppLabel(trusted1.getAppId()), "rwxl");
4020     check_exact_access("User", generateAppLabel(trusted1.getAppId()), "rwxl");
4021     check_exact_access("System", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
4022     check_exact_access("User", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
4023     check_exact_access("System", generateAppLabel(trusted2.getAppId()), "rwxl");
4024     check_exact_access("User", generateAppLabel(trusted2.getAppId()), "rwxl");
4025
4026     Api::uninstall(trustingApp2);
4027
4028     check_exact_access("System", generateAppLabel(trusted1.getAppId()), "rwxl");
4029     check_exact_access("User", generateAppLabel(trusted1.getAppId()), "rwxl");
4030     check_exact_access("System", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
4031     check_exact_access("User", generatePkgLabel(trusted1.getPkgId()), "rwxatl");
4032     check_exact_access("System", generateAppLabel(trusted2.getAppId()), "");
4033     check_exact_access("User", generateAppLabel(trusted2.getAppId()), "");
4034
4035     Api::uninstall(trustingApp);
4036
4037     check_exact_access("System", generateAppLabel(trusted1.getAppId()), "");
4038     check_exact_access("User", generateAppLabel(trusted1.getAppId()), "");
4039     check_exact_access("System", generatePkgLabel(trusted1.getPkgId()), "");
4040     check_exact_access("User", generatePkgLabel(trusted1.getPkgId()), "");
4041 }
4042
4043 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CREDENTIAL_API)
4044
4045 class ProcessCredentials {
4046 public:
4047     ProcessCredentials(const std::string &smackLabel) : m_label(smackLabel) {}
4048
4049     const std::string &label(void) const {
4050         return m_label;
4051     }
4052
4053     uid_t uid(void) const {
4054         return tzplatform_getuid(TZ_SYS_GLOBALAPP_USER);
4055     }
4056
4057     gid_t gid(void) const {
4058         return PasswdAccess::gid("users");
4059     }
4060
4061 private:
4062     std::string m_label;
4063 };
4064
4065 pid_t runInChild(const std::function<void(void)> &process) {
4066     pid_t pid = fork();
4067     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
4068
4069     if (pid == 0) {
4070         process();
4071         exit(EXIT_SUCCESS);
4072     }
4073
4074     return pid;
4075 }
4076
4077 void udsServer(SynchronizationPipe &pipe, const struct sockaddr_un &sockaddr,
4078                const struct ProcessCredentials &peerCredentials) {
4079     SecurityServer::AccessProvider ap(peerCredentials.label());
4080     ap.applyAndSwithToUser(peerCredentials.uid(), peerCredentials.gid());
4081     pipe.claimChildEp();
4082
4083     int sock = UDSHelpers::createServer(&sockaddr);
4084     SockUniquePtr sockPtr(&sock);
4085     pipe.post();
4086     int clientSock = UDSHelpers::acceptClient(sock);
4087
4088     UDSHelpers::waitForDisconnect(clientSock);
4089 }
4090
4091 typedef std::function<void(int sock, pid_t pid)> SocketAssertionFn;
4092
4093 void clientTestTemplate(SocketAssertionFn assertion, const std::string &scope, const std::string &smackLabel) {
4094     const auto sockaddr = UDSHelpers::makeAbstractAddress("test_sm_" + scope + ".socket");
4095     const ProcessCredentials peerCredentials(smackLabel);
4096
4097     SynchronizationPipe pipe;
4098
4099     pid_t pid = runInChild(std::bind(udsServer, std::ref(pipe), std::cref(sockaddr),
4100                            std::cref(peerCredentials)));
4101
4102     pipe.claimParentEp();
4103     pipe.wait();
4104     int sock = UDSHelpers::createClient(&sockaddr);
4105     SockUniquePtr sockPtr(&sock);
4106
4107     assertion(sock, pid);
4108 }
4109
4110 RUNNER_CHILD_TEST(security_manager_51a_get_id_by_socket)
4111 {
4112     const char *const sm_app_id = "sm_test_51a_app";
4113     const char *const sm_pkg_id = "sm_test_51a_pkg";
4114
4115     InstallRequest requestInst;
4116     requestInst.setAppId(sm_app_id);
4117     requestInst.setPkgId(sm_pkg_id);
4118
4119     Api::install(requestInst);
4120
4121     std::string smackLabel = generateAppLabel(sm_app_id);
4122
4123     clientTestTemplate([&] (int sock, pid_t) {
4124         std::string rcvPkgId, rcvAppId;
4125         Api::getPkgIdBySocket(sock, &rcvPkgId, &rcvAppId);
4126         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
4127                           << "; expected = " << sm_pkg_id);
4128         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
4129                           << "; expected = " << sm_app_id);
4130     }, "tcsm27a", smackLabel);
4131
4132     InstallRequest requestUninst;
4133     requestUninst.setAppId(sm_app_id);
4134
4135     Api::uninstall(requestUninst);
4136 }
4137
4138 RUNNER_CHILD_TEST(security_manager_51b_get_id_by_socket)
4139 {
4140     const char *const sm_app_id = "sm_test_51b_app";
4141     const char *const sm_pkg_id = "sm_test_51b_pkg";
4142
4143     InstallRequest requestInst;
4144     requestInst.setAppId(sm_app_id);
4145     requestInst.setPkgId(sm_pkg_id);
4146
4147     Api::install(requestInst);
4148
4149     std::string smackLabel = generateAppLabel(sm_app_id);
4150
4151     clientTestTemplate([&] (int sock, pid_t) {
4152         std::string rcvPkgId, rcvAppId;
4153         Api::getPkgIdBySocket(sock + 1, &rcvPkgId, &rcvAppId, SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT);
4154     }, "tcsm27b", smackLabel);
4155
4156     InstallRequest requestUninst;
4157     requestUninst.setAppId(sm_app_id);
4158
4159     Api::uninstall(requestUninst);
4160 }
4161
4162 RUNNER_CHILD_TEST(security_manager_51c_get_id_by_socket)
4163 {
4164     const char *const sm_app_id = "sm_test_51c_app";
4165     const char *const sm_pkg_id = "sm_test_51c_pkg";
4166
4167     InstallRequest requestInst;
4168     requestInst.setAppId(sm_app_id);
4169     requestInst.setPkgId(sm_pkg_id);
4170
4171     Api::install(requestInst);
4172
4173     std::string smackLabel = generateAppLabel(sm_app_id);
4174
4175     clientTestTemplate([&] (int sock, pid_t) {
4176         std::string rcvPkgId;
4177         Api::getPkgIdBySocket(sock, &rcvPkgId, nullptr);
4178         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
4179                           << "; expected = " << sm_pkg_id);
4180     }, "tcsm27c", smackLabel);
4181
4182     InstallRequest requestUninst;
4183     requestUninst.setAppId(sm_app_id);
4184
4185     Api::uninstall(requestUninst);
4186 }
4187
4188 RUNNER_CHILD_TEST(security_manager_51d_get_id_by_socket)
4189 {
4190     const char *const sm_app_id = "sm_test_51d_app";
4191     const char *const sm_pkg_id = "sm_test_51d_pkg";
4192
4193     InstallRequest requestInst;
4194     requestInst.setAppId(sm_app_id);
4195     requestInst.setPkgId(sm_pkg_id);
4196
4197     Api::install(requestInst);
4198
4199     std::string smackLabel = generateAppLabel(sm_app_id);
4200
4201     clientTestTemplate([&] (int sock, pid_t) {
4202         std::string rcvAppId;
4203         Api::getPkgIdBySocket(sock, nullptr, &rcvAppId);
4204         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
4205                           << "; expected = " << sm_app_id);
4206     }, "tcsm27d", smackLabel);
4207
4208     InstallRequest requestUninst;
4209     requestUninst.setAppId(sm_app_id);
4210
4211     Api::uninstall(requestUninst);
4212 }
4213
4214 RUNNER_CHILD_TEST(security_manager_51e_get_id_by_socket)
4215 {
4216     const char *const sm_app_id = "sm_test_51e_app";
4217     const char *const sm_pkg_id = "sm_test_51e_pkg";
4218
4219     InstallRequest requestInst;
4220     requestInst.setAppId(sm_app_id);
4221     requestInst.setPkgId(sm_pkg_id);
4222
4223     Api::install(requestInst);
4224
4225     std::string smackLabel = generateAppLabel(sm_app_id);
4226
4227     clientTestTemplate([&] (int sock, pid_t) {
4228         Api::getPkgIdBySocket(sock, nullptr, nullptr, SECURITY_MANAGER_ERROR_INPUT_PARAM);
4229     }, "tcsm27e", smackLabel);
4230
4231     InstallRequest requestUninst;
4232     requestUninst.setAppId(sm_app_id);
4233
4234     Api::uninstall(requestUninst);
4235 }
4236
4237 RUNNER_CHILD_TEST(security_manager_52a_get_id_by_pid)
4238 {
4239     const char *const sm_app_id = "sm_test_52a_app";
4240     const char *const sm_pkg_id = "sm_test_52a_pkg";
4241
4242     InstallRequest requestInst;
4243     requestInst.setAppId(sm_app_id);
4244     requestInst.setPkgId(sm_pkg_id);
4245
4246     Api::install(requestInst);
4247
4248     std::string smackLabel = generateAppLabel(sm_app_id);
4249
4250     clientTestTemplate([&] (int, pid_t pid) {
4251         std::string rcvPkgId, rcvAppId;
4252         Api::getPkgIdByPid(pid, &rcvPkgId, &rcvAppId);
4253         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
4254                           << "; expected = " << sm_pkg_id);
4255         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
4256                           << "; expected = " << sm_app_id);
4257     }, "tcsm28a", smackLabel);
4258
4259     InstallRequest requestUninst;
4260     requestUninst.setAppId(sm_app_id);
4261
4262     Api::uninstall(requestUninst);
4263 }
4264
4265 RUNNER_CHILD_TEST(security_manager_52b_get_id_by_pid)
4266 {
4267     const char *const sm_app_id = "sm_test_52b_app";
4268     const char *const sm_pkg_id = "sm_test_52b_pkg";
4269
4270     InstallRequest requestInst;
4271     requestInst.setAppId(sm_app_id);
4272     requestInst.setPkgId(sm_pkg_id);
4273
4274     Api::install(requestInst);
4275
4276     std::string smackLabel = generateAppLabel(sm_app_id);
4277
4278     clientTestTemplate([&] (int, pid_t pid) {
4279         std::string rcvPkgId, rcvAppId;
4280         Api::getPkgIdByPid(pid + 1, &rcvPkgId, &rcvAppId, SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT);
4281     }, "tcsm28b", smackLabel);
4282
4283     InstallRequest requestUninst;
4284     requestUninst.setAppId(sm_app_id);
4285
4286     Api::uninstall(requestUninst);
4287 }
4288
4289 RUNNER_CHILD_TEST(security_manager_52c_get_id_by_pid)
4290 {
4291     const char *const sm_app_id = "sm_test_52c_app";
4292     const char *const sm_pkg_id = "sm_test_52c_pkg";
4293
4294     InstallRequest requestInst;
4295     requestInst.setAppId(sm_app_id);
4296     requestInst.setPkgId(sm_pkg_id);
4297
4298     Api::install(requestInst);
4299
4300     std::string smackLabel = generateAppLabel(sm_app_id);
4301
4302     clientTestTemplate([&] (int, pid_t pid) {
4303         std::string rcvPkgId;
4304         Api::getPkgIdByPid(pid, &rcvPkgId, nullptr);
4305         RUNNER_ASSERT_MSG(rcvPkgId == sm_pkg_id, "pkgIds don't match ret = " << rcvPkgId
4306                           << "; expected = " << sm_pkg_id);
4307     }, "tcsm28c", smackLabel);
4308
4309     InstallRequest requestUninst;
4310     requestUninst.setAppId(sm_app_id);
4311
4312     Api::uninstall(requestUninst);
4313 }
4314
4315 RUNNER_CHILD_TEST(security_manager_52d_get_id_by_pid)
4316 {
4317     const char *const sm_app_id = "sm_test_52d_app";
4318     const char *const sm_pkg_id = "sm_test_52d_pkg";
4319
4320     InstallRequest requestInst;
4321     requestInst.setAppId(sm_app_id);
4322     requestInst.setPkgId(sm_pkg_id);
4323
4324     Api::install(requestInst);
4325
4326     std::string smackLabel = generateAppLabel(sm_app_id);
4327
4328     clientTestTemplate([&] (int, pid_t pid) {
4329         std::string rcvAppId;
4330         Api::getPkgIdByPid(pid, nullptr, &rcvAppId);
4331         RUNNER_ASSERT_MSG(rcvAppId == sm_app_id, "appIds don't match ret = " << rcvAppId
4332                           << "; expected = " << sm_app_id);
4333     }, "tcsm28d", smackLabel);
4334
4335     InstallRequest requestUninst;
4336     requestUninst.setAppId(sm_app_id);
4337
4338     Api::uninstall(requestUninst);
4339 }
4340
4341 RUNNER_CHILD_TEST(security_manager_52e_get_id_by_pid)
4342 {
4343     const char *const sm_app_id = "sm_test_52e_app";
4344     const char *const sm_pkg_id = "sm_test_52e_pkg";
4345
4346     InstallRequest requestInst;
4347     requestInst.setAppId(sm_app_id);
4348     requestInst.setPkgId(sm_pkg_id);
4349
4350     Api::install(requestInst);
4351
4352     std::string smackLabel = generateAppLabel(sm_app_id);
4353
4354     clientTestTemplate([&] (int sock, pid_t) {
4355         Api::getPkgIdByPid(sock, nullptr, nullptr, SECURITY_MANAGER_ERROR_INPUT_PARAM);
4356     }, "tcsm28e", smackLabel);
4357
4358     InstallRequest requestUninst;
4359     requestUninst.setAppId(sm_app_id);
4360
4361     Api::uninstall(requestUninst);
4362 }
4363
4364 RUNNER_CHILD_TEST(security_manager_53_app_has_privilege)
4365 {
4366     const char *const sm_app_id = "sm_test_53_app";
4367     const char *const sm_pkg_id = "sm_test_53_pkg";
4368     const std::string new_user_name = "sm_test_47_user_name";
4369
4370     InstallRequest requestInst;
4371     requestInst.setAppId(sm_app_id);
4372     requestInst.setPkgId(sm_pkg_id);
4373     for (auto const &privilege : SM_ALLOWED_PRIVILEGES)
4374         requestInst.addPrivilege(privilege.c_str());
4375     Api::install(requestInst);
4376
4377     for (auto const &privilege : SM_ALLOWED_PRIVILEGES) {
4378         int result;
4379         Api::appHasPrivilege(sm_app_id, privilege.c_str(), getGlobalUserId(), result);
4380         RUNNER_ASSERT_MSG(result == 1, "Application " << sm_app_id <<
4381             " should have access to privilege " << privilege);
4382     }
4383
4384     for (auto const &privilege : SM_DENIED_PRIVILEGES) {
4385         int result;
4386         Api::appHasPrivilege(sm_app_id, privilege.c_str(), getGlobalUserId(), result);
4387         RUNNER_ASSERT_MSG(result == 0, "Application " << sm_app_id <<
4388             " should not have access to privilege " << privilege);
4389     }
4390
4391     InstallRequest requestUninst;
4392     requestUninst.setAppId(sm_app_id);
4393     Api::uninstall(requestUninst);
4394 }
4395
4396 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
4397
4398 RUNNER_TEST(security_manager_49a_global_user_set_install_type_global)
4399 {
4400     const char *const sm_app_id = "sm_test_49a_app_id_global";
4401     const char *const sm_pkg_id = "sm_test_49a_pkg_id_global";
4402
4403     InstallRequest requestInst;
4404     requestInst.setAppId(sm_app_id);
4405     requestInst.setPkgId(sm_pkg_id);
4406     requestInst.setInstallType(SM_APP_INSTALL_GLOBAL);
4407
4408     Api::install(requestInst);
4409
4410     // Check records in the security-manager database
4411     check_app_after_install(sm_app_id, sm_pkg_id);
4412
4413     InstallRequest requestUninst;
4414     requestUninst.setAppId(sm_app_id);
4415
4416     Api::uninstall(requestUninst);
4417
4418     // Check records in the security-manager database
4419     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
4420 }
4421
4422 RUNNER_TEST(security_manager_49b_global_user_set_install_type_local)
4423 {
4424     const char *const sm_app_id = "sm_test_49b_app_id_local";
4425     const char *const sm_pkg_id = "sm_test_49b_pkg_id_local";
4426
4427     InstallRequest requestInst;
4428     requestInst.setAppId(sm_app_id);
4429     requestInst.setPkgId(sm_pkg_id);
4430     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
4431
4432     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
4433 }
4434
4435 RUNNER_TEST(security_manager_49c_global_user_set_install_type_preloaded)
4436 {
4437     const char *const sm_app_id = "sm_test_49c_app_id_preloaded";
4438     const char *const sm_pkg_id = "sm_test_49c_pkg_id_preloaded";
4439
4440     InstallRequest requestInst;
4441     requestInst.setAppId(sm_app_id);
4442     requestInst.setPkgId(sm_pkg_id);
4443     requestInst.setInstallType(SM_APP_INSTALL_PRELOADED);
4444
4445     Api::install(requestInst);
4446
4447     // Check records in the security-manager database
4448     check_app_after_install(sm_app_id, sm_pkg_id);
4449
4450     InstallRequest requestUninst;
4451     requestUninst.setAppId(sm_app_id);
4452
4453     Api::uninstall(requestUninst);
4454
4455     // Check records in the security-manager database
4456     check_app_after_uninstall(sm_app_id, sm_pkg_id, TestSecurityManagerDatabase::REMOVED);
4457 }
4458
4459 RUNNER_CHILD_TEST(security_manager_49d_local_user_set_install_type_global)
4460 {
4461     int result;
4462     const char *const sm_app_id = "sm_test_49d_app_id_global";
4463     const char *const sm_pkg_id = "sm_test_49d_pkg_id_global";
4464     const std::string new_user_name = "sm_test_49d_user_name";
4465
4466     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
4467     testUser.create();
4468
4469     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
4470     createTestDirs(testUser, sm_app_id, sm_pkg_id);
4471
4472     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
4473
4474     //switch user to non-root
4475     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
4476     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4477
4478     InstallRequest requestPrivateUser;
4479     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
4480                     SECURITY_MANAGER_PATH_RW, userAppDirPath.c_str(),
4481                     false);
4482
4483     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4484     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4485     requestPrivateUser.setInstallType(SM_APP_INSTALL_GLOBAL);
4486
4487     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
4488         requestPrivateUser.addPrivilege(privilege.c_str());
4489
4490     /*
4491      * It is possible for local user to install global application but one needs app_install privileges
4492      * By default only global user or root can install global apps
4493      */
4494     Api::install(requestPrivateUser, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
4495 }
4496
4497 RUNNER_CHILD_TEST(security_manager_49e_local_user_set_install_type_local)
4498 {
4499     int result;
4500     const char *const sm_app_id = "sm_test_49e_app_id_local";
4501     const char *const sm_pkg_id = "sm_test_49e_pkg_id_local";
4502     const std::string new_user_name = "sm_test_49e_user_name";
4503
4504     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
4505     testUser.create();
4506
4507     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
4508     createTestDirs(testUser, sm_app_id, sm_pkg_id);
4509
4510     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
4511
4512     //switch user to non-root
4513     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
4514     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4515
4516     InstallRequest requestPrivateUser;
4517     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
4518                     SECURITY_MANAGER_PATH_RW, userAppDirPath.c_str(),
4519                     false);
4520
4521     requestPrivateUser.setInstallType(SM_APP_INSTALL_LOCAL);
4522
4523     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
4524         requestPrivateUser.addPrivilege(privilege.c_str());
4525
4526     Api::install(requestPrivateUser);
4527
4528     check_app_permissions(sm_app_id, sm_pkg_id,
4529                           uidToStr(testUser.getUid()).c_str(),
4530                           SM_ALLOWED_PRIVILEGES, SM_DENIED_PRIVILEGES);
4531
4532     //uninstall app as non-root user
4533     InstallRequest request;
4534     request.setAppId(sm_app_id);
4535
4536     Api::uninstall(request);
4537
4538     check_app_permissions(sm_app_id, sm_pkg_id,
4539                           uidToStr(testUser.getUid()).c_str(),
4540                           SM_NO_PRIVILEGES, SM_ALLOWED_PRIVILEGES);
4541 }
4542
4543 RUNNER_CHILD_TEST(security_manager_49f_local_user_set_install_type_preloaded)
4544 {
4545     int result;
4546     const char *const sm_app_id = "sm_test_49f_app_id_preloaded";
4547     const char *const sm_pkg_id = "sm_test_49f_pkg_id_preloaded";
4548     const std::string new_user_name = "sm_test_49f_user_name";
4549
4550     TemporaryTestUser testUser(new_user_name, GUM_USERTYPE_NORMAL, false);
4551     testUser.create();
4552
4553     removeTestDirs(testUser, sm_app_id, sm_pkg_id);
4554     createTestDirs(testUser, sm_app_id, sm_pkg_id);
4555
4556     const std::string userAppDirPath = appDirPath(testUser, sm_app_id, sm_pkg_id);
4557
4558     //switch user to non-root
4559     result = drop_root_privileges(testUser.getUid(), testUser.getGid());
4560     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4561
4562     InstallRequest requestPrivateUser;
4563     prepare_request(requestPrivateUser, sm_app_id, sm_pkg_id,
4564                     SECURITY_MANAGER_PATH_RW, userAppDirPath.c_str(),
4565                     false);
4566
4567     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4568     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4569     requestPrivateUser.setInstallType(SM_APP_INSTALL_PRELOADED);
4570
4571     for (auto &privilege : SM_ALLOWED_PRIVILEGES)
4572         requestPrivateUser.addPrivilege(privilege.c_str());
4573
4574     /*
4575      * It is possible for local user to install preloaded application but one needs app_install privileges
4576      * By default only global user or root can install preloaded apps
4577      */
4578     Api::install(requestPrivateUser, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
4579 }
4580
4581 RUNNER_TEST(security_manager_50_app_install_constraint_check)
4582 {
4583     auto install = [](const TemporaryTestUser& user,
4584                       const char *pkgId,
4585                       const char *appId,
4586                       const char *version,
4587                       const char *author,
4588                       enum lib_retcode expected,
4589                       bool uninstall = true)
4590     {
4591         InstallRequest request;
4592         request.setAppId(appId);
4593         request.setPkgId(pkgId);
4594         request.setAppTizenVersion(version);
4595         request.setAuthorId(author);
4596         request.setUid(user.getUid());
4597
4598         Api::install(request, expected);
4599
4600         if(expected == SECURITY_MANAGER_SUCCESS) {
4601             // TODO add verification once check_app_after_install() supports uid
4602             // check_app_after_install(appId, pkgId);
4603             if(uninstall)
4604                 Api::uninstall(request);
4605         }
4606     };
4607
4608     std::vector<TemporaryTestUser> users = {
4609             {"sm_test_50_user_name_0", GUM_USERTYPE_NORMAL, false},
4610             {"sm_test_50_user_name_1", GUM_USERTYPE_NORMAL, false}
4611     };
4612
4613     for(auto& gu : users)
4614         gu.create();
4615
4616     const char *const pkgId[] =   {"sm_test_50_pkg_id_0",  "sm_test_50_pkg_id_1"};
4617     const char *const appId[] =   {"sm_test_50_app_id_0",  "sm_test_50_app_id_1"};
4618     const char *const version[] = {"sm_test_50_version_0", "sm_test_50_version_1"};
4619     const char *const author[] =  {"sm_test_50_author_0",  "sm_test_50_author_1"};
4620
4621     // uid_0, pkg_0, app_0, version_0, author_0
4622     install(users[0], pkgId[0], appId[0], version[0], author[0], SECURITY_MANAGER_SUCCESS, false);
4623
4624     // uid_1, pkg_0, app_0, version_0, author_0 -> ok (different uid)
4625     install(users[1], pkgId[0], appId[0], version[0], author[0], SECURITY_MANAGER_SUCCESS);
4626     // uid_1, pkg_0, app_0, version_0, author_1 -> fail (author of app_0 must be the same)
4627     install(users[1], pkgId[0], appId[0], version[0], author[1], SECURITY_MANAGER_ERROR_INPUT_PARAM);
4628     // uid_1, pkg_0, app_0, version_1, author_0 -> fail (version of app_0 must be the same)
4629     install(users[1], pkgId[0], appId[0], version[1], author[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
4630     // uid_1, pkg_1, app_0, version_0, author_0 -> fail (pkg of app_0 must be the same)
4631     install(users[1], pkgId[1], appId[0], version[0], author[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
4632     // uid_0, pkg_0, app_0, version_0, author_0 -> ok (the same app again)
4633     install(users[0], pkgId[0], appId[0], version[0], author[0], SECURITY_MANAGER_SUCCESS, false);
4634     // uid_0, pkg_1, app_0, version_0, author_0 -> fail (app_name + uid must be unique)
4635     install(users[0], pkgId[1], appId[0], version[0], author[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
4636     // uid_0, pkg_0, app_0, version_1, author_0 -> fail (app_name + uid must be unique)
4637     install(users[0], pkgId[0], appId[0], version[1], author[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
4638     // uid_0, pkg_0, app_0, version_0, author_1 -> fail (app_name + uid must be unique)
4639     install(users[0], pkgId[0], appId[0], version[0], author[1], SECURITY_MANAGER_ERROR_INPUT_PARAM);
4640 }
4641
4642 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_REGISTER_PATH)
4643
4644 RUNNER_TEST(security_manager_54_path_req_no_pkg)
4645 {
4646     const char *const sm_app_id = "sm_test_54_app_id";
4647     const char *const sm_pkg_id = "sm_test_54_pkg_id";
4648
4649     TemporaryTestUser user("sm_test_54_user_name", GUM_USERTYPE_NORMAL, false);
4650     user.create();
4651     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4652
4653     removeTestDirs(user, sm_app_id, sm_pkg_id);
4654     createTestDirs(user, sm_app_id, sm_pkg_id);
4655
4656     PathsRequest req;
4657     req.setPkgId("non-existing-pkg-id");
4658     req.setUid(user.getUid());
4659     req.addPath(path, SECURITY_MANAGER_PATH_RW);
4660
4661     Api::registerPaths(req, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4662 }
4663
4664 RUNNER_TEST(security_manager_55_path_req_empty_pkg)
4665 {
4666     const char *const sm_app_id = "sm_test_55_app_id";
4667     const char *const sm_pkg_id = "sm_test_55_pkg_id";
4668
4669     TemporaryTestUser user("sm_test_55_user_name", GUM_USERTYPE_NORMAL, false);
4670     user.create();
4671     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4672
4673     removeTestDirs(user, sm_app_id, sm_pkg_id);
4674     createTestDirs(user, sm_app_id, sm_pkg_id);
4675
4676     PathsRequest req;
4677     req.setPkgId("");
4678     req.setUid(user.getUid());
4679     req.addPath(path, SECURITY_MANAGER_PATH_RW);
4680
4681     Api::registerPaths(req, (lib_retcode)SECURITY_MANAGER_ERROR_REQ_NOT_COMPLETE);
4682 }
4683
4684 RUNNER_TEST(security_manager_56_path_req_wrong_type)
4685 {
4686     PathsRequest req;
4687     req.setInstallType(SM_APP_INSTALL_END,
4688                        (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4689     req.setInstallType((app_install_type)(SM_APP_INSTALL_NONE-1),
4690                        (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
4691 }
4692
4693 RUNNER_TEST(security_manager_57_path_req_wrong_uid)
4694 {
4695     const char *const sm_app_id = "sm_test_57_app_id";
4696     const char *const sm_pkg_id = "sm_test_57_pkg_id";
4697
4698     TemporaryTestUser user("sm_test_57_user_name", GUM_USERTYPE_NORMAL, false);
4699     user.create();
4700     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4701
4702     removeTestDirs(user, sm_app_id, sm_pkg_id);
4703     createTestDirs(user, sm_app_id, sm_pkg_id);
4704
4705     install_app(sm_app_id, sm_pkg_id, user.getUid());
4706
4707     PathsRequest preq;
4708     preq.setPkgId(sm_pkg_id);
4709     preq.setUid(-1);
4710     preq.setInstallType(SM_APP_INSTALL_LOCAL);
4711     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4712
4713     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
4714 }
4715
4716 RUNNER_TEST(security_manager_58_path_req_empty_paths)
4717 {
4718     const char *const sm_app_id = "sm_test_58_app_id";
4719     const char *const sm_pkg_id = "sm_test_58_pkg_id";
4720
4721     TemporaryTestUser user("sm_test_58_user_name", GUM_USERTYPE_NORMAL, false);
4722     user.create();
4723
4724     install_app(sm_app_id, sm_pkg_id, user.getUid());
4725
4726     PathsRequest req;
4727     req.setPkgId(sm_pkg_id);
4728     req.setUid(user.getUid());
4729     Api::registerPaths(req);
4730 }
4731
4732 RUNNER_TEST(security_manager_59_path_req_as_root_positive)
4733 {
4734     const char *const sm_app_id = "sm_test_59_app_id";
4735     const char *const sm_pkg_id = "sm_test_59_pkg_id";
4736
4737     TemporaryTestUser user("sm_test_59_user_name", GUM_USERTYPE_NORMAL, false);
4738     user.create();
4739     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4740
4741     removeTestDirs(user, sm_app_id, sm_pkg_id);
4742     createTestDirs(user, sm_app_id, sm_pkg_id);
4743
4744     install_app(sm_app_id, sm_pkg_id, user.getUid());
4745
4746     PathsRequest preq;
4747     preq.setPkgId(sm_pkg_id);
4748     preq.setUid(user.getUid());
4749     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4750
4751     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_SUCCESS);
4752 }
4753
4754 RUNNER_CHILD_TEST(security_manager_60_path_req_as_user_positive)
4755 {
4756     const char *const sm_app_id = "sm_test_60_app_id";
4757     const char *const sm_pkg_id = "sm_test_60_pkg_id";
4758
4759     TemporaryTestUser user("sm_test_60_user_name", GUM_USERTYPE_NORMAL, false);
4760     user.create();
4761     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4762
4763     removeTestDirs(user, sm_app_id, sm_pkg_id);
4764     createTestDirs(user, sm_app_id, sm_pkg_id);
4765
4766     install_app(sm_app_id, sm_pkg_id, user.getUid());
4767
4768     int result = drop_root_privileges(user.getUid(), user.getGid());
4769     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4770
4771     PathsRequest preq;
4772     preq.setPkgId(sm_pkg_id);
4773     preq.setUid(user.getUid());
4774     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4775
4776     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_SUCCESS);
4777 }
4778
4779 RUNNER_CHILD_TEST(security_manager_61_path_req_different_user)
4780 {
4781     const char *const sm_app_id = "sm_test_61_app_id";
4782     const char *const sm_pkg_id = "sm_test_61_pkg_id";
4783
4784     TemporaryTestUser user1("sm_test_61_1_user_name", GUM_USERTYPE_NORMAL, false);
4785     user1.create();
4786     TemporaryTestUser user2("sm_test_61_2_user_name", GUM_USERTYPE_NORMAL, false);
4787     user2.create();
4788
4789     std::string path = appDirPath(user2, sm_app_id, sm_pkg_id);
4790
4791     removeTestDirs(user2, sm_app_id, sm_pkg_id);
4792     createTestDirs(user2, sm_app_id, sm_pkg_id);
4793
4794     install_app(sm_app_id, sm_pkg_id, user2.getUid());
4795
4796     int result = drop_root_privileges(user1.getUid(), user1.getGid());
4797     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4798
4799     PathsRequest preq;
4800     preq.setPkgId(sm_pkg_id);
4801     preq.setUid(user2.getUid());
4802     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4803
4804     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
4805 }
4806
4807 void testPathOutside(const std::string& pkgId, uid_t uid, const std::string& path)
4808 {
4809     PathsRequest preq;
4810     preq.setPkgId(pkgId);
4811     preq.setUid(uid);
4812     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4813
4814     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
4815 }
4816
4817 RUNNER_TEST(security_manager_62_path_req_path_outside)
4818 {
4819     const char *const sm_app_id = "sm_test_62_app_id";
4820     const char *const sm_pkg_id = "sm_test_62_pkg_id";
4821
4822     TemporaryTestUser user1("sm_test_62_1_user_name", GUM_USERTYPE_NORMAL, false);
4823     user1.create();
4824     TemporaryTestUser user2("sm_test_62_2_user_name", GUM_USERTYPE_NORMAL, false);
4825     user2.create();
4826
4827     install_app(sm_app_id, sm_pkg_id, user1.getUid());
4828
4829     removeTestDirs(user1, sm_app_id, sm_pkg_id);
4830     removeTestDirs(user2, sm_app_id, sm_pkg_id);
4831     createTestDirs(user1, sm_app_id, sm_pkg_id);
4832     createTestDirs(user2, sm_app_id, sm_pkg_id);
4833
4834     testPathOutside(sm_pkg_id, user1.getUid(), appDirPath(user2, sm_app_id, sm_pkg_id));
4835     testPathOutside(sm_pkg_id, user1.getUid(), appDirPath(user1, sm_app_id, "sm_test_62_non_existing_pkg_id"));
4836     testPathOutside(sm_pkg_id, user1.getUid(), std::string("/home/") + user1.getUserName());
4837 }
4838
4839 void testPathsReqAsUser(const enum app_install_type &type, lib_retcode expectedResult) {
4840     const char *const sm_app_id = "sm_test_63_app_id";
4841     const char *const sm_pkg_id = "sm_test_63_pkg_id";
4842
4843     TemporaryTestUser user("sm_test_63_user_name", GUM_USERTYPE_NORMAL, false);
4844     user.create();
4845     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4846
4847     removeTestDirs(user, sm_app_id, sm_pkg_id);
4848     createTestDirs(user, sm_app_id, sm_pkg_id);
4849
4850     install_app(sm_app_id, sm_pkg_id, user.getUid());
4851
4852     int result = drop_root_privileges(user.getUid(), user.getGid());
4853     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4854
4855     PathsRequest preq;
4856     preq.setPkgId(sm_pkg_id);
4857     preq.setUid(user.getUid());
4858     preq.setInstallType(type);
4859     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4860
4861     Api::registerPaths(preq, expectedResult);
4862 }
4863
4864 RUNNER_CHILD_TEST(security_manager_63a_path_req_as_user)
4865 {
4866     testPathsReqAsUser(SM_APP_INSTALL_GLOBAL,
4867                            (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
4868 }
4869
4870 RUNNER_CHILD_TEST(security_manager_63b_path_req_preloaded_as_user)
4871 {
4872     testPathsReqAsUser(SM_APP_INSTALL_PRELOADED,
4873                            (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
4874 }
4875
4876 void testPathsReqLocal(uid_t uid, gid_t gid)
4877 {
4878     const char *const sm_app_id = "sm_test_64_app_id";
4879     const char *const sm_pkg_id = "sm_test_64_pkg_id";
4880
4881     TemporaryTestUser user("sm_test_64_user_name", GUM_USERTYPE_NORMAL, false);
4882     user.create();
4883     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4884
4885     removeTestDirs(user, sm_app_id, sm_pkg_id);
4886     createTestDirs(user, sm_app_id, sm_pkg_id);
4887
4888     install_app(sm_app_id, sm_pkg_id, user.getUid());
4889
4890     int result = drop_root_privileges(uid, gid);
4891     RUNNER_ASSERT_MSG(result == 0, "drop_root_privileges failed");
4892
4893     PathsRequest preq;
4894     preq.setPkgId(sm_pkg_id);
4895     preq.setUid(user.getUid());
4896     preq.setInstallType(SM_APP_INSTALL_LOCAL);
4897     preq.addPath(path, SECURITY_MANAGER_PATH_RW);
4898
4899     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_SUCCESS);
4900 }
4901
4902
4903 RUNNER_CHILD_TEST(security_manager_64a_path_req_as_local_as_root)
4904 {
4905     testPathsReqLocal(0, 0);
4906 }
4907
4908 RUNNER_CHILD_TEST(security_manager_64b_path_req_as_local_asuser)
4909 {
4910     testPathsReqLocal(getGlobalUserId(), getGlobalGroupId());
4911 }
4912
4913 RUNNER_TEST(security_manager_66_path_req_check_labels)
4914 {
4915     const char *const sm_app_id = "sm_test_66_app_id_full";
4916     const char *const sm_pkg_id = "sm_test_66_pkg_id_full";
4917
4918     std::string SM_RW_PATH = genRWPath(66);
4919     std::string SM_RO_PATH = genROPath(66);
4920     std::string SM_PUBLIC_RO_PATH = genPublicROPath(66);
4921
4922     prepare_app_env(66);
4923
4924     install_app(sm_app_id, sm_pkg_id);
4925
4926     PathsRequest preq;
4927     preq.setPkgId(sm_pkg_id);
4928     preq.addPath(SM_RW_PATH, SECURITY_MANAGER_PATH_RW);
4929     preq.addPath(SM_RO_PATH, SECURITY_MANAGER_PATH_RO);
4930     preq.addPath(SM_PUBLIC_RO_PATH, SECURITY_MANAGER_PATH_PUBLIC_RO);
4931     Api::registerPaths(preq);
4932
4933     uninstall_app(sm_app_id, sm_pkg_id, true);
4934 }
4935
4936 RUNNER_TEST(security_manager_67_path_req_shared_ro_3_0)
4937 {
4938     const char *const sm_app_id = "sm_test_67_app_id";
4939     const char *const sm_pkg_id = "sm_test_67_pkg_id";
4940
4941     TemporaryTestUser user("sm_test_67_user_name", GUM_USERTYPE_NORMAL, false);
4942     user.create();
4943     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4944
4945     removeTestDirs(user, sm_app_id, sm_pkg_id);
4946     createTestDirs(user, sm_app_id, sm_pkg_id);
4947
4948     InstallRequest ireq;
4949     ireq.setAppId(sm_app_id);
4950     ireq.setPkgId(sm_pkg_id);
4951     ireq.setUid(user.getUid());
4952     ireq.setAppTizenVersion("3.0");
4953     Api::install(ireq);
4954
4955     PathsRequest preq;
4956     preq.setPkgId(sm_pkg_id);
4957     preq.setUid(user.getUid());
4958     preq.addPath(path, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
4959
4960     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_SUCCESS);
4961 }
4962
4963 RUNNER_TEST(security_manager_68_path_req_shared_ro_2_X)
4964 {
4965     const char *const sm_app_id = "sm_test_68_app_id";
4966     const char *const sm_pkg_id = "sm_test_68_pkg_id";
4967
4968     TemporaryTestUser user("sm_test_68_user_name", GUM_USERTYPE_NORMAL, false);
4969     user.create();
4970     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
4971
4972     removeTestDirs(user, sm_app_id, sm_pkg_id);
4973     createTestDirs(user, sm_app_id, sm_pkg_id);
4974
4975     InstallRequest ireq;
4976     ireq.setAppId(sm_app_id);
4977     ireq.setPkgId(sm_pkg_id);
4978     ireq.setUid(user.getUid());
4979     ireq.setAppTizenVersion("2.4");
4980     Api::install(ireq);
4981
4982     PathsRequest preq;
4983     preq.setPkgId(sm_pkg_id);
4984     preq.setUid(user.getUid());
4985     preq.addPath(path, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
4986
4987     Api::registerPaths(preq);
4988
4989     // check labels
4990     nftw_expected_label = generatePkgLabel(sm_pkg_id) + "::SharedRO";
4991     nftw_expected_transmute = true;
4992     nftw_expected_exec = false;
4993     int result = nftw(path.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
4994     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << path);
4995 }
4996
4997 RUNNER_TEST(security_manager_69_path_req_trusted_rw_no_author)
4998 {
4999     const char *const sm_app_id = "sm_test_69_app_id";
5000     const char *const sm_pkg_id = "sm_test_69_pkg_id";
5001
5002     TemporaryTestUser user("sm_test_69_user_name", GUM_USERTYPE_NORMAL, false);
5003     user.create();
5004     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
5005
5006     removeTestDirs(user, sm_app_id, sm_pkg_id);
5007     createTestDirs(user, sm_app_id, sm_pkg_id);
5008
5009     install_app(sm_app_id, sm_pkg_id, user.getUid());
5010
5011     PathsRequest preq;
5012     preq.setPkgId(sm_pkg_id);
5013     preq.setUid(user.getUid());
5014     preq.addPath(path, SECURITY_MANAGER_PATH_TRUSTED_RW);
5015
5016     Api::registerPaths(preq, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
5017 }
5018
5019 RUNNER_TEST(security_manager_70_path_req_trusted_rw_positive)
5020 {
5021     const char *const sm_app_id = "sm_test_70_app_id";
5022     const char *const sm_pkg_id = "sm_test_70_pkg_id";
5023     const char *const author_id = "sm_test_70_author_id";
5024
5025     TemporaryTestUser user("sm_test_70_user_name", GUM_USERTYPE_NORMAL, false);
5026     user.create();
5027     std::string path = appDirPath(user, sm_app_id, sm_pkg_id);
5028
5029     removeTestDirs(user, sm_app_id, sm_pkg_id);
5030     createTestDirs(user, sm_app_id, sm_pkg_id);
5031
5032     InstallRequest ireq;
5033     ireq.setAppId(sm_app_id);
5034     ireq.setPkgId(sm_pkg_id);
5035     ireq.setUid(user.getUid());
5036     ireq.setAuthorId(author_id);
5037     Api::install(ireq);
5038
5039     PathsRequest preq;
5040     preq.setPkgId(sm_pkg_id);
5041     preq.setUid(user.getUid());
5042     preq.addPath(path, SECURITY_MANAGER_PATH_TRUSTED_RW);
5043
5044     Api::registerPaths(preq);
5045
5046     // check labels
5047     TestSecurityManagerDatabase dbtest;
5048     int64_t authorDb = dbtest.get_author_id(author_id);
5049     nftw_expected_label = std::string("User::Author::") + std::to_string(authorDb);
5050     nftw_expected_transmute = true;
5051     nftw_expected_exec = false;
5052     int result = nftw(path.c_str(), &nftw_check_sm_labels, FTW_MAX_FDS, FTW_PHYS);
5053     RUNNER_ASSERT_MSG(result == 0, "Unable to check Smack labels for " << path);
5054 }
5055
5056 int main(int argc, char *argv[])
5057 {
5058     return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
5059 }