Group privilege check refactoring
[platform/core/test/security-tests.git] / src / security-manager-tests / test_cases.cpp
1 /*
2  * Copyright (c) 2016 - 2020 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16
17 // cstdlibg has to be included before attr/xattr
18 #include <cstdlib>
19 #include <attr/xattr.h>
20 #include <fstream>
21 #include <memory>
22 #include <regex>
23 #include <string>
24 #include <sys/capability.h>
25 #include <sys/smack.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28
29 #include <cynara-admin.h>
30
31 #include <cynara_test_admin.h>
32 #include <dpl/test/test_runner.h>
33 #include <label_generator.h>
34 #include <message_pipe.h>
35 #include <policy_configuration.h>
36 #include <scoped_installer.h>
37 #include <service_manager.h>
38 #include <sm_api.h>
39 #include <sm_commons.h>
40 #include <sm_request.h>
41 #include <synchronization_pipe.h>
42 #include <temp_test_user.h>
43 #include <tests_common.h>
44 #include <tzplatform.h>
45 #include <uds.h>
46 #include <scoped_process_label.h>
47 #include <scoped_app_launcher.h>
48 #include <app_install_helper_ext.h>
49 #include <privilege_names.h>
50 #include <app_def_privilege.h>
51
52 using namespace SecurityManagerTest;
53 using namespace PrivilegeNames;
54
55 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER)
56
57 RUNNER_TEST(security_manager_01a_app_double_install_double_uninstall)
58 {
59     AppInstallHelperExt app("sm_test_01a_app");
60     {
61         ScopedInstaller appInstall(app);
62         app.checkAfterInstall();
63         {
64             ScopedInstaller appInstall2(app);
65             app.checkAfterInstall();
66         }
67         app.checkAfterUninstall();
68     }
69 }
70
71 RUNNER_TEST(security_manager_01b_app_double_install_wrong_pkg_id)
72 {
73     AppInstallHelperExt app("sm_test_01b");
74     {
75         ScopedInstaller appInstall(app);
76
77         InstallRequest requestInst2;
78         requestInst2.setAppId(app.getAppId());
79         requestInst2.setPkgId(app.getPkgId() + "_wrong");
80
81         Api::install(requestInst2, SECURITY_MANAGER_ERROR_INPUT_PARAM);
82
83         app.checkAfterInstall();
84     }
85     app.checkAfterUninstall();
86 }
87
88 RUNNER_TEST(security_manager_01c_app_uninstall_wrong_pkg_id)
89 {
90     AppInstallHelperExt app("sm_test_01c");
91     ScopedInstaller appInstall(app);
92
93     app.checkAfterInstall();
94
95     InstallRequest requestUninst;
96     requestUninst.setAppId(app.getAppId());
97     requestUninst.setPkgId(app.getPkgId() + "_wrong_pkg_id");
98
99     Api::uninstall(requestUninst, SECURITY_MANAGER_ERROR_NO_SUCH_OBJECT);
100 }
101
102 /*
103  * This test uses files installed with security-tests package
104  */
105 RUNNER_TEST(security_manager_01d_app_install_complicated_dir_tree)
106 {
107     const std::string appId = "sm_test_01d_app_id_full";
108     const std::string pkgId = "sm_test_01d_pkg_id_full";
109
110     const std::string rootDir = TzPlatformConfig::globalAppDir() + "/" + pkgId + "/";
111     const std::string privateDir = rootDir + "app_dir/";
112     const std::string privateRODir = rootDir + "app_dir_ro/";
113     const std::string publicRODir = rootDir + "app_dir_public_ro/";
114     const std::string sharedRODir = rootDir + "app_dir_rw_others_ro/";
115
116     int result = nftw(rootDir.c_str(), &nftw_remove_labels, FTW_MAX_FDS, FTW_PHYS);
117     RUNNER_ASSERT_MSG(result == 0, "Unable to clean Smack labels in " << rootDir);
118
119     InstallRequest requestInst;
120     requestInst.setAppId(appId);
121     requestInst.setPkgId(pkgId);
122     requestInst.addPath(privateDir, SECURITY_MANAGER_PATH_RW);
123     requestInst.addPath(privateRODir, SECURITY_MANAGER_PATH_RO);
124     requestInst.addPath(publicRODir, SECURITY_MANAGER_PATH_PUBLIC_RO);
125     requestInst.addPath(sharedRODir, SECURITY_MANAGER_PATH_OWNER_RW_OTHER_RO);
126     Api::install(requestInst);
127
128     std::unique_ptr<InstallRequest, std::function<void(InstallRequest*)>> appCleanup(&requestInst,
129             [](InstallRequest *req) {
130                 Api::uninstall(*req);
131     });
132
133     check_path(privateDir, generatePathRWLabel(pkgId));
134     check_path(privateRODir, generatePathROLabel(pkgId), false);
135     check_path(publicRODir, getPublicPathLabel());
136     check_path(sharedRODir, getSharedROPathLabel());
137 }
138
139 RUNNER_CHILD_TEST(security_manager_02_app_install_uninstall_full)
140 {
141     const PrivilegeVector defaultPrivs = {
142         PRIV_INTERNAL_AUDIO,
143         PRIV_INTERNAL_DISPLAY,
144         PRIV_INTERNAL_VIDEO,
145     };
146     const PrivilegeVector allowedPrivs = {PRIV_CAMERA, PRIV_MEDIASTORAGE};
147     const PrivilegeVector someDeniedPrivs = {PRIV_INTERNET, PRIV_EXTERNALSTORAGE};
148
149     PrivilegeVector defaultAllowedPrivs = defaultPrivs;
150     defaultAllowedPrivs.insert(defaultAllowedPrivs.end(), allowedPrivs.begin(), allowedPrivs.end());
151
152     AppInstallHelperExt app("sm_test_02");
153     app.createPrivateDir();
154     app.createPrivateRODir();
155     app.createPublicDir();
156     app.createSharedRODir();
157     app.addPrivileges(allowedPrivs);
158     {
159         ScopedInstaller appInstall(app);
160
161         app.checkAfterInstall();
162         app.checkDeniedPrivileges(someDeniedPrivs);
163         {
164             ScopedAppLauncher launcher(app, [&]{ app.checkGroupPrivileges(defaultAllowedPrivs); });
165         }
166
167         check_path(app.getPrivateDir(), generatePathRWLabel(app.getPkgId()));
168         check_path(app.getPrivateRODir(), generatePathROLabel(app.getPkgId()), false);
169         check_path(app.getPublicDir(), getPublicPathLabel());
170         check_path(app.getSharedRODir(), getSharedROPathLabel());
171     }
172
173     app.checkAfterUninstall();
174 }
175
176 RUNNER_CHILD_TEST(security_manager_02a_set_process_groups)
177 {
178     const PrivilegeVector defaultPrivs = {
179         PRIV_INTERNAL_AUDIO,
180         PRIV_INTERNAL_DISPLAY,
181         PRIV_INTERNAL_VIDEO,
182     };
183     const PrivilegeVector allowedPrivs = {PRIV_CAMERA, PRIV_MEDIASTORAGE};
184
185     auto defaultAllowedPrivs = defaultPrivs;
186     defaultAllowedPrivs.insert(defaultAllowedPrivs.end(), allowedPrivs.begin(), allowedPrivs.end());
187
188     AppInstallHelperExt app("sm_test_02a");
189     app.addPrivileges(allowedPrivs);
190     {
191         ScopedInstaller appInstall(app);
192
193         app.checkAfterInstall();
194
195         pid_t pid = fork();
196         RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "Fork failed");
197         if (pid != 0) {
198             waitPid(pid);
199         } else {
200             Api::setProcessGroups(app.getAppId());
201             app.checkGroupPrivileges(defaultAllowedPrivs);
202             exit(0);
203         }
204     }
205     app.checkAfterUninstall();
206 }
207
208 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
209 {
210     std::string expectedSockLabel = "labelExpectedOnlyFromSocket";
211
212     AppInstallHelper app("sm_test_03a");
213     std::string expectedProcLabel = generateProcessLabel(app.getAppId(), app.getPkgId());
214
215     const auto sockaddr = UDSHelpers::makeAbstractAddress("sm_test_03a.socket");
216     int sock = UDSHelpers::createServer(&sockaddr);
217     SockUniquePtr sockPtr(&sock);
218
219     //Set socket label to something different than expeced process label
220     int result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPIN, expectedSockLabel.c_str());
221     RUNNER_ASSERT_ERRNO_MSG(result == 0,
222         "Can't set socket label. Result: " << result);
223     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPOUT, expectedSockLabel.c_str());
224     RUNNER_ASSERT_ERRNO_MSG(result == 0,
225         "Can't set socket label. Result: " << result);
226
227     ScopedInstaller appInstall(app);
228
229     pid_t pid = fork();
230     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "Fork failed");
231     if (pid == 0) { // child
232         Api::setProcessLabel(app.getAppId());
233
234         char *label = nullptr;
235         CStringPtr labelPtr;
236         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPIN, &label);
237         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
238         labelPtr.reset(label);
239         result = expectedSockLabel.compare(label);
240         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
241             expectedProcLabel << " Actual: " << label);
242
243         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPOUT, &label);
244         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
245         labelPtr.reset(label);
246         result = expectedSockLabel.compare(label);
247         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
248             expectedProcLabel << " Actual: " << label);
249
250         result = smack_new_label_from_self(&label);
251         RUNNER_ASSERT_MSG(result >= 0,
252                 " Error getting current process label");
253         RUNNER_ASSERT_MSG(label != nullptr,
254                 " Process label is not set");
255         labelPtr.reset(label);
256
257         result = expectedProcLabel.compare(label);
258         RUNNER_ASSERT_MSG(result == 0,
259                 " Process label is incorrect. Expected: \"" << expectedProcLabel <<
260                 "\" Actual: \"" << label << "\"");
261     } else { // parent
262         waitPid(pid);
263     }
264 }
265
266 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
267 {
268     const PrivilegeVector allowedPrivs = {PRIV_BLUETOOTH, PRIV_POWER};
269     const PrivilegeVector someDeniedPrivs = {PRIV_DISPLAY, PRIV_NFC};
270
271     TemporaryTestUser testUser("sm_test_04a_user_name", GUM_USERTYPE_NORMAL);
272     testUser.create();
273
274     AppInstallHelperExt app("sm_test_04a", testUser.getUid());
275     app.addPrivileges(allowedPrivs);
276
277     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
278                             "drop_root_privileges failed");
279     {
280         ScopedInstaller appInstall(app, false);
281         app.checkAfterInstall();
282         app.checkDeniedPrivileges(someDeniedPrivs);
283     }
284     app.checkAfterUninstall();
285     app.checkDeniedPrivileges(someDeniedPrivs);
286 }
287
288 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user) {
289     const PrivilegeVector allowedPrivs = {PRIV_INTERNET, PRIV_LED};
290     const PrivilegeVector someDeniedPrivs = {PRIV_LOCATION, PRIV_NOTIFICATION};
291
292     TemporaryTestUser testUser("sm_test_04b_user_name", GUM_USERTYPE_NORMAL);
293     testUser.create();
294
295     AppInstallHelperExt app("sm_test_04b", testUser.getUid());
296     app.addPrivileges(allowedPrivs);
297
298     {
299         ScopedInstaller appInstall(app);
300         app.checkAfterInstall();
301         app.checkDeniedPrivileges(someDeniedPrivs);
302
303         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
304                                 "drop_root_privileges failed");
305     }
306     app.checkAfterUninstall();
307     app.checkDeniedPrivileges(someDeniedPrivs);
308 }
309
310 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
311 {
312     int result;
313     CapsSetsUniquePtr caps_empty(cap_init());
314     auto caps = setCaps("all=eip");
315     Api::dropProcessPrivileges();
316
317     caps.reset(cap_get_proc());
318     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
319
320     result = cap_compare(caps.get(), caps_empty.get());
321     RUNNER_ASSERT_MSG(result == 0,
322         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
323 }
324
325 RUNNER_TEST(security_manager_06_install_app_offline)
326 {
327     ServiceManager("security-manager.service").stopService();
328
329     ServiceManager serviceManager("security-manager.socket");
330     serviceManager.stopService();
331
332     AppInstallHelper app("sm_test_06");
333     ScopedInstaller appInstall(app);
334     // TODO - check if app is installed properly
335     // start service before uninstall, offline mode doesn't support uninstall
336     serviceManager.startService();
337     appInstall.uninstallApp();
338     // TODO - check if app is uninstalled properly
339 }
340
341 RUNNER_CHILD_TEST(security_manager_07a_user_add_app_install)
342 {
343     const PrivilegeVector allowedPrivs = {PRIV_INTERNET, PRIV_LED};
344     const PrivilegeVector someDeniedPrivs = {PRIV_LOCATION, PRIV_NOTIFICATION};
345
346     TemporaryTestUser testUser("sm_test_07a_user_name", GUM_USERTYPE_NORMAL);
347     testUser.create();
348
349     AppInstallHelperExt app("sm_test_07a", testUser.getUid());
350     app.addPrivileges(allowedPrivs);
351
352     InstallRequest req;
353     req.setAppId(app.getAppId());
354     req.setPkgId(app.getPkgId());
355     req.setUid(app.getUID());
356     for (const auto &priv: app.getPrivileges()) {
357         req.addPrivilege(priv);
358     }
359     Api::install(req);
360     app.checkAfterInstall();
361     app.checkDeniedPrivileges(someDeniedPrivs);
362
363     testUser.remove();
364
365     app.checkAfterUninstall();
366     app.checkDeniedPrivileges(someDeniedPrivs);
367 }
368
369 RUNNER_TEST(security_manager_07b_user_add_offline)
370 {
371     ServiceManager("security-manager.service").stopService();
372
373     ServiceManager serviceManager("security-manager.socket");
374     serviceManager.stopService();
375
376     TemporaryTestUser testUser("sm_test_07b_user_name", GUM_USERTYPE_NORMAL, true);
377     testUser.create();
378
379     AppInstallHelperExt app("sm_test_07b", testUser.getUid());
380     ScopedInstaller appInstall(app);
381
382     serviceManager.startService();
383     app.checkAfterInstall();
384
385     testUser.remove();
386     app.checkAfterUninstall();
387 }
388
389 RUNNER_TEST(security_manager_08_user_double_add_double_remove)
390 {
391     const PrivilegeVector somePrivs = {PRIV_LED, PRIV_NOTIFICATION};
392
393     // gumd
394     TemporaryTestUser testUser("sm_test_08_user_name", GUM_USERTYPE_NORMAL);
395     testUser.create();
396
397     // security-manager
398     UserRequest addUserRequest;
399     addUserRequest.setUid(testUser.getUid());
400     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
401     Api::addUser(addUserRequest);
402
403     AppInstallHelperExt app("sm_test_08", testUser.getUid());
404     ScopedInstaller appInstall(app);
405
406     app.checkAfterInstall();
407     app.checkDeniedPrivileges(somePrivs);
408
409     // gumd
410     testUser.remove();
411
412     app.checkAfterUninstall();
413
414     // security-manager
415     UserRequest deleteUserRequest;
416     deleteUserRequest.setUid(testUser.getUid());
417     Api::deleteUser(deleteUserRequest);
418 }
419
420 RUNNER_TEST(security_manager_09_app_install_constraint_check)
421 {
422     auto install = [](const AppInstallHelperExt& app, bool success)
423     {
424         auto expected = success ? SECURITY_MANAGER_SUCCESS : SECURITY_MANAGER_ERROR_INPUT_PARAM;
425         ScopedInstaller appInstall(app, true, expected);
426         if (success)
427             app.checkAfterInstall();
428         return appInstall;
429     };
430
431     auto update = [](const AppInstallHelperExt& app)
432     {
433         InstallRequest request;
434         request.setAppId(app.getAppId());
435         request.setPkgId(app.getPkgId());
436         request.setAppTizenVersion(app.getVersion());
437         request.setAuthorId(app.getAuthor());
438         request.setUid(app.getUID());
439         if (app.getIsHybrid())
440             request.setHybrid();
441         Api::update(request);
442     };
443
444     TemporaryTestUser users[] = {
445         {"sm_test_09_user_name_0", GUM_USERTYPE_NORMAL, false},
446         {"sm_test_09_user_name_1", GUM_USERTYPE_NORMAL, false}
447     };
448
449     for (auto& gu : users)
450         gu.create();
451
452     const char *const pkgIdPrefix[] =   {"sm_test_09_0",            "sm_test_09_1"};
453     const char *const appIdPrefix[] =   {"sm_test_09_0",            "sm_test_09_1"};
454     const char *const version[] =       {"sm_test_09_0_version",    "sm_test_09_1_version"};
455     const char *const author[] =        {"sm_test_09_0_author",     "sm_test_09_1_author"};
456     bool hybrid[] = {false, true};
457
458     std::list<AppInstallHelperExt> apps;
459
460     auto make_helper = [&](size_t userIdx,
461                            size_t pkgIdx,
462                            size_t appIdx,
463                            size_t verIdx,
464                            size_t authorIdx,
465                            size_t hybridIdx) -> AppInstallHelperExt&
466     {
467         apps.emplace_back(appIdPrefix[appIdx], pkgIdPrefix[pkgIdx], users[userIdx].getUid());
468         apps.back().setAuthor(author[authorIdx]);
469         apps.back().setVersion(version[verIdx]);
470         if (hybrid[hybridIdx])
471             apps.back().setHybrid();
472         return apps.back();
473     };
474
475     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> ok
476     auto &app000000 = make_helper(0, 0, 0, 0, 0, 0);
477     auto i1 = install(app000000, true);
478
479     // uid_1, pkg_0, app_0, version_0, author_0, not hybrid -> ok (different uid)
480     auto& app100000 = make_helper(1, 0, 0, 0, 0, 0);
481     install(app100000, true);
482
483     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> conflicts with existing non hybrid app
484     auto& app000001 = make_helper(0, 0, 0, 0, 0, 1);
485     install(app000001, false);
486
487     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> ok (app updated to hybrid)
488     update(app000001);
489
490     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> ok (app installed again)
491     auto i2 = install(app000001, true);
492
493     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> conflicts with existing hybrid app
494     install(app000000, false);
495
496     // uid_0, pkg_0, app_1, version_0, author_0, hybrid -> ok (new app id)
497     auto& app001001 = make_helper(0, 0, 1, 0, 0, 1);
498     auto i3 = install(app001001, true);
499
500     // uid_1, pkg_0, app_0, version_0, author_0, hybrid -> ok (hybrid, different uid)
501     auto& app100001 = make_helper(1, 0, 0, 0, 0, 1);
502     auto i4 = install(app100001, true);
503
504     // uid_1, pkg_0, app_0, version_0, author_1, not hybrid -> author of app_0 must be the same
505     auto& app100010 = make_helper(1, 0, 0, 0, 1, 0);
506     install(app100010, false);
507
508     // uid_1, pkg_0, app_0, version_1, author_0, not hybrid -> ok (app version and hybridity changed)
509     auto& app100100 = make_helper(1, 0, 0, 1, 0, 0);
510     update(app100100);
511
512     // uid_1, pkg_1, app_0, version_1, author_0, not hybrid -> pkg of app_0 must be the same
513     auto& app110100 = make_helper(1, 1, 0, 1, 0, 0);
514     install(app110100, false);
515
516     for (auto& gu : users)
517         gu.remove();
518
519     RUNNER_IGNORED_MSG("Disabled until hybridity update works properly for all users");
520     for (auto& app : apps)
521         app.checkAfterUninstall();
522 }
523
524 RUNNER_TEST(security_manager_09a_install_many_apps_in_single_request)
525 {
526     constexpr char pkgIdPrefix[] = "sm_test_09a";
527     const AppInstallHelperExt apps[] = {{"sm_test_09a_0", pkgIdPrefix},
528                                         {"sm_test_09a_1", pkgIdPrefix},
529                                         {"sm_test_09a_2", pkgIdPrefix}};
530     static_assert(sizeof(apps) > 0);
531
532     std::vector<std::string> appIds;
533     for (auto &app : apps)
534         appIds.push_back(app.getAppId());
535
536     {
537         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
538         // Installing many applications in single request
539         for (auto &app : apps) {
540             app.checkAfterInstall();
541         }
542     }
543
544     for (auto &app : apps) {
545         app.checkAfterUninstall();
546     }
547 }
548
549 RUNNER_TEST(security_manager_09b_install_many_apps_in_single_request_duplicated_ids)
550 {
551     AppInstallHelperExt app("sm_test_09b");
552     {
553         ScopedInstaller appsInstall({app.getAppId(), app.getAppId()}, app.getPkgId());
554         app.checkAfterInstall();
555     }
556
557     app.checkAfterUninstall();
558 }
559
560 RUNNER_TEST(security_manager_09c_update_many_apps_in_single_request_hybrid_package)
561 {
562     constexpr char pkgIdPrefix[] = "sm_test_09c";
563     AppInstallHelperExt apps[] = {{"sm_test_09c_0", pkgIdPrefix},
564                                   {"sm_test_09c_1", pkgIdPrefix},
565                                   {"sm_test_09c_2", pkgIdPrefix}};
566     static_assert(sizeof(apps) > 0);
567
568     std::vector<std::string> appIds;
569     for (const auto &app : apps)
570         appIds.push_back(app.getAppId());
571
572     {
573         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
574         // Package is not hybrid, every app has same policy.
575         for (const auto &app : apps) {
576             app.checkAfterInstall();
577         }
578
579         // Updating package -- changing set of apps in package and setting hybrid mode
580         InstallRequest updateRequest;
581         updateRequest.setPkgId(apps[0].getPkgId());
582         updateRequest.setAppId(appIds[0]);
583         updateRequest.nextApp();
584         updateRequest.setAppId(appIds[1]);
585         updateRequest.setHybrid();
586
587         Api::update(updateRequest);
588
589         // Package became hybrid, so every app has its own Smack label
590         for (auto &app : apps) {
591             app.setHybrid();
592         }
593         apps[0].checkAfterInstall();
594         apps[1].checkAfterInstall();
595
596         // Package became hybrid properly,
597         // so app not included in updated version of package was uninstalled.
598         apps[2].checkAfterUninstall(false);
599     }
600
601     for (const auto &app : apps) {
602         app.checkAfterUninstall();
603     }
604 }
605
606 RUNNER_TEST(security_manager_09d_uninstall_app_from_hybrid_package)
607 {
608     constexpr char pkgIdPrefix[] = "sm_test_09d";
609     AppInstallHelperExt apps[] = {{"sm_test_09d_0", pkgIdPrefix},
610                                   {"sm_test_09d_1", pkgIdPrefix},
611                                   {"sm_test_09d_2", pkgIdPrefix}};
612     static_assert(sizeof(apps) > 0);
613
614     std::vector<std::string> appIds;
615     for (const auto &app : apps)
616         appIds.push_back(app.getAppId());
617
618     {
619         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
620
621         InstallRequest updateRequest;
622         updateRequest.setPkgId(apps[0].getPkgId());
623         for (unsigned int i = 0; i < appIds.size(); i++) {
624             if (i > 0) {
625                 updateRequest.nextApp();
626             }
627             updateRequest.setAppId(appIds[i]);
628         }
629         updateRequest.setHybrid();
630         Api::update(updateRequest);
631
632         InstallRequest uninstRequest;
633         uninstRequest.setPkgId(apps[0].getPkgId());
634         uninstRequest.setAppId(appIds[0]);
635         Api::uninstall(uninstRequest);
636
637         for (auto &app : apps) {
638             app.setHybrid();
639         }
640         apps[0].checkAfterUninstall(false);
641     }
642     for (const auto &app : apps) {
643         app.checkAfterUninstall();
644     }
645 }
646
647 RUNNER_CHILD_TEST(security_manager_10_app_has_privilege)
648 {
649     const PrivilegeVector allowedPrivs = {PRIV_WIFIDIRECT, PRIV_TELEPHONY};
650     const PrivilegeVector someDeniedPrivs = {PRIV_VPNSERVICE, PRIV_NOTIFICATION};
651
652     AppInstallHelperExt app("sm_test_10");
653     app.addPrivileges(allowedPrivs);
654     ScopedInstaller appInstall(app);
655
656     app.checkAfterInstall();
657     app.checkDeniedPrivileges(someDeniedPrivs);
658     // FIXME - all other existing privileges should be checked
659 }
660
661 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_POLICY)
662
663 RUNNER_TEST(security_manager_20_user_cynara_policy)
664 {
665     // FIXME - whitebox - cynara
666     const char *const MAIN_BUCKET = "MAIN";
667     const char *const MANIFESTS_GLOBAL_BUCKET = "MANIFESTS_GLOBAL";
668     const char *const MANIFESTS_LOCAL_BUCKET = "MANIFESTS_LOCAL";
669     const char *const ADMIN_BUCKET = "ADMIN";
670     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
671     CynaraTestAdmin::Admin admin;
672
673     TemporaryTestUser user("sm_test_20_user_name", GUM_USERTYPE_NORMAL, false);
674     user.create();
675     std::string uid_string = user.getUidString();
676
677     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
678     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
679     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
680
681     user.remove();
682     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
683
684     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
685     admin.listPolicies(MANIFESTS_GLOBAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
686     admin.listPolicies(MANIFESTS_LOCAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
687     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
688     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
689 }
690
691 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
692 {
693     const PrivilegeVector adminRequiredPrivs = {PRIV_NOTEXIST, PRIV_INTERNAL_USERMANAGEMENT};
694     const PrivilegeVector manifestPrivs = {PRIV_INTERNET, PRIV_DATASHARING};
695     const PrivilegeVector allowedPrivsAfterChange = {PRIV_DATASHARING};
696     const PrivilegeVector deniedPrivsAfterChange = {PRIV_INTERNET};
697
698     TemporaryTestUser adminUser("sm_test_21_admin_user_name", GUM_USERTYPE_ADMIN, false);
699     TemporaryTestUser normalUser("sm_test_21_normal_user_name", GUM_USERTYPE_NORMAL, false);
700
701     adminUser.create();
702     normalUser.create();
703
704     AppInstallHelper adminApp("sm_test_21_admin", adminUser.getUid());
705     adminApp.addPrivileges(adminRequiredPrivs);
706     ScopedInstaller adminAppInstall(adminApp);
707
708     AppInstallHelperExt normalApp("sm_test_21_normal", normalUser.getUid());
709     normalApp.addPrivileges(manifestPrivs);
710     ScopedInstaller normalAppInstall(normalApp);
711     normalApp.checkAfterInstall();
712
713     pid_t pid = fork();
714     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
715     if (pid != 0) { //parent process
716         waitPid(pid);
717         normalApp.checkPrivileges(allowedPrivsAfterChange, deniedPrivsAfterChange);
718     } else {
719         Api::setProcessLabel(adminApp.getAppId());
720         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(),adminUser.getGid()) == 0,
721                                 "drop_root_privileges failed");
722
723         PolicyRequest addPolicyReq;
724         for (auto &deniedPriv : deniedPrivsAfterChange) {
725             PolicyEntry entry(SECURITY_MANAGER_ANY, normalUser.getUidString(), deniedPriv);
726             entry.setMaxLevel(PolicyEntry::LEVEL_DENY);
727             addPolicyReq.addEntry(entry);
728         }
729         Api::sendPolicy(addPolicyReq);
730         exit(0);
731     }
732 }
733
734 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CMD)
735
736 RUNNER_TEST(security_manager_22_security_manager_cmd_install)
737 {
738     int ret;
739     const int SUCCESS = 0;
740     const int FAILURE = 256;
741     const std::string app_id = "sm_test_22_app_id";
742     const std::string pkg_id = "sm_test_22_pkg_id";
743     const std::string username("sm_test_22_user_name");
744
745     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL);
746     user.create();
747
748     const std::string path1 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p1";
749     const std::string path2 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p2";
750     const std::string pkgopt = " --pkg=" + pkg_id;
751     const std::string appopt = " --app=" + app_id;
752     const std::string uidopt = " --uid=" + user.getUidString();
753
754     mktreeSafe(path1.c_str(), 0);
755     mktreeSafe(path2.c_str(), 0);
756
757     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
758
759     struct operation {
760         std::string command;
761         int expected_result;
762     };
763     std::vector<struct operation> operations = {
764             {"security-manager-cmd", FAILURE},//no option
765             {"security-manager-cmd --blah", FAILURE},//blah option is not known
766             {"security-manager-cmd --help", SUCCESS},
767             {"security-manager-cmd --install", FAILURE},//no params
768             {"security-manager-cmd -i", FAILURE},//no params
769             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
770             {installcmd, SUCCESS},
771             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
772             {installcmd + " --path " + path1 + " rw", SUCCESS},
773             {installcmd + " --path " + path1, FAILURE},//no path type
774             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
775             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
776             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
777     };
778
779     for (auto &op : operations) {
780         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
781         RUNNER_ASSERT_MSG(ret == op.expected_result,
782                 "Unexpected result for command '" << op.command <<"': "
783                 << ret << " Expected was: "<< op.expected_result);
784     }
785 }
786
787 RUNNER_TEST(security_manager_23_security_manager_cmd_users)
788 {
789     const int SUCCESS = 0;
790     const int FAILURE = 256;
791     TemporaryTestUser user("sm_test_23_user_name", GUM_USERTYPE_NORMAL, false);
792     user.create();
793     const std::string uidopt = " --uid=" + user.getUidString();
794
795     struct operation {
796         std::string command;
797         int expected_result;
798     };
799     std::vector<struct operation> operations = {
800             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
801             {"security-manager-cmd -m", FAILURE},//no params
802             {"security-manager-cmd -mr", FAILURE},//no uid
803             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
804             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
805             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
806             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
807             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
808             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
809             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
810             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
811     };
812
813     for (auto &op : operations) {
814         int ret = system((op.command + " 1>/dev/null 2>&1").c_str());
815         RUNNER_ASSERT_MSG(ret == op.expected_result,
816                 "Unexpected result for command '" << op.command <<"': "
817                 << ret << " Expected was: "<< op.expected_result);
818     }
819 }
820
821 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_GROUPS)
822
823 RUNNER_TEST(security_manager_24_groups_get)
824 {
825     PolicyConfiguration pc;
826     gid_t * c_groups;
827     size_t count = 0;
828
829     Api::getSecurityManagerGroups(&c_groups, &count);
830     std::unique_ptr<gid_t, decltype(free)*> groupsPtr(c_groups, free);
831
832     auto policyGroups = pc.getGid();
833     RUNNER_ASSERT_MSG(count == policyGroups.size(), "security_manager_groups_get should set count to: "
834                       << policyGroups.size() << " but count is: " << count);
835
836     for (const auto &group : policyGroups) {
837         bool found = false;
838         for (size_t i = 0; i < count; ++i) {
839             if (group == c_groups[i]) {
840                 found = true;
841                 break;
842             }
843         }
844         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
845     }
846 }
847
848 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
849
850 RUNNER_TEST(security_manager_25a_global_user_set_install_type_global)
851 {
852     AppInstallHelperExt app("sm_test_25a");
853     app.setInstallType(SM_APP_INSTALL_GLOBAL);
854     {
855         ScopedInstaller appInstall(app);
856
857         app.checkAfterInstall();
858     }
859
860     // Check records in the security-manager database
861     app.checkAfterUninstall();
862 }
863
864 RUNNER_TEST(security_manager_25b_global_user_set_install_type_local)
865 {
866     AppInstallHelper app("sm_test_25b");
867
868     InstallRequest requestInst;
869     requestInst.setAppId(app.getAppId());
870     requestInst.setPkgId(app.getPkgId());
871     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
872
873     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
874 }
875
876 RUNNER_TEST(security_manager_25c_global_user_set_install_type_preloaded)
877 {
878     AppInstallHelperExt app("sm_test_25c");
879     app.setInstallType(SM_APP_INSTALL_PRELOADED);
880     {
881         ScopedInstaller appInstall(app);
882         app.checkAfterInstall();
883     }
884     app.checkAfterUninstall();
885 }
886
887 RUNNER_TEST(security_manager_25d_local_user_set_install_type_invalid)
888 {
889     InstallRequest requestPrivateUser;
890     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
891     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
892 }
893
894 /*
895  * It is possible for local user to install global application but one needs app_install privileges
896  * By default only global user or root can install global apps (or "User", "System", "System::Privileged"...)
897  */
898 RUNNER_CHILD_TEST(security_manager_25e_unprivileged_install_type_global)
899 {
900     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
901
902     TemporaryTestUser testUser("sm_test_25e_user_name", GUM_USERTYPE_NORMAL);
903     testUser.create();
904
905     AppInstallHelper app("sm_test_25e");
906
907     ScopedProcessLabel spl("_", false);
908     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
909                             "drop_root_privileges failed");
910
911     InstallRequest invalidReq;
912     invalidReq.setAppId(app.getAppId());
913     invalidReq.setPkgId(app.getPkgId());
914     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
915
916     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
917 }
918
919 RUNNER_CHILD_TEST(security_manager_25f_unprivileged_install_type_preloaded)
920 {
921     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
922
923     TemporaryTestUser testUser("sm_test_25f_user_name", GUM_USERTYPE_NORMAL);
924     testUser.create();
925
926     AppInstallHelper app("sm_test_25f");
927
928     ScopedProcessLabel spl("_", false);
929     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
930                             "drop_root_privileges failed");
931     InstallRequest invalidReq;
932     invalidReq.setAppId(app.getAppId());
933     invalidReq.setPkgId(app.getPkgId());
934     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
935     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
936 }
937
938 RUNNER_CHILD_TEST(security_manager_25g_local_user_set_install_type_local)
939 {
940     const PrivilegeVector allowedPrivs = {PRIV_VOLUME_SET, PRIV_SYSTEMMONITOR, PRIV_INTERNET};
941     const PrivilegeVector someDeniedPrivs = {PRIV_PUSH, PRIV_POWER, PRIV_NOTIFICATION};
942
943     TemporaryTestUser testUser("sm_test_25g_user_name", GUM_USERTYPE_NORMAL);
944     testUser.create();
945
946     AppInstallHelperExt app("sm_test_25g", testUser.getUid());
947     app.createPrivateDir();
948     app.setInstallType(SM_APP_INSTALL_LOCAL);
949     app.addPrivileges(allowedPrivs);
950
951     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
952                             "drop_root_privileges failed");
953     {
954         ScopedInstaller appInstall(app);
955         app.checkAfterInstall();
956         app.checkDeniedPrivileges(someDeniedPrivs);
957     }
958     app.checkAfterUninstall();
959 }
960
961 RUNNER_CHILD_TEST(security_manager_25h_local_path_global_install)
962 {
963     TemporaryTestUser testUser("sm_test_25h_user_name", GUM_USERTYPE_NORMAL);
964     testUser.create();
965
966     AppInstallHelper app("sm_test_25h", testUser.getUid());
967     app.createPrivateDir();
968
969     InstallRequest invalidReq;
970     invalidReq.setAppId(app.getAppId());
971     invalidReq.setPkgId(app.getPkgId());
972     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
973     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
974     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
975 }
976
977 RUNNER_CHILD_TEST(security_manager_25i_local_path_preloaded_install)
978 {
979     TemporaryTestUser testUser("sm_test_25i_user_name", GUM_USERTYPE_NORMAL);
980     testUser.create();
981
982     AppInstallHelper app("sm_test_25i", testUser.getUid());
983     app.createPrivateDir();
984
985     InstallRequest invalidReq;
986     invalidReq.setAppId(app.getAppId());
987     invalidReq.setPkgId(app.getPkgId());
988     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
989     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
990     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
991 }
992
993 RUNNER_CHILD_TEST(security_manager_25j_global_path_local_install)
994 {
995     TemporaryTestUser testUser("sm_test_25j_user_name", GUM_USERTYPE_NORMAL);
996     testUser.create();
997
998     AppInstallHelper appLocal("sm_test_25j", testUser.getUid());
999
1000     AppInstallHelper appGlobal("sm_test_25");
1001     appGlobal.createPrivateDir();
1002
1003     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
1004                             "drop_root_privileges failed");
1005
1006     InstallRequest invalidReq;
1007     invalidReq.setAppId(appLocal.getAppId());
1008     invalidReq.setPkgId(appLocal.getPkgId());
1009     invalidReq.addPath(appGlobal.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
1010     invalidReq.setInstallType(SM_APP_INSTALL_LOCAL);
1011
1012     Api::install(invalidReq, SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
1013 }
1014
1015 RUNNER_CHILD_TEST(security_manager_26_hybrid_pkg_uninstall_artifacts_check)
1016 {
1017     TemporaryTestUser testUser("sm_test_26_user_name", GUM_USERTYPE_NORMAL);
1018     testUser.create();
1019
1020     const PrivilegeVector allowedPrivs = {PRIV_WIFIDIRECT, PRIV_TELEPHONY};
1021
1022     AppInstallHelperExt app1("sm_test_26_1", "sm_test_26", testUser.getUid());
1023     app1.addPrivileges(allowedPrivs);
1024     app1.setHybrid();
1025
1026     AppInstallHelperExt app2("sm_test_26_2", "sm_test_26", testUser.getUid());
1027     app2.addPrivileges(allowedPrivs);
1028     app2.setHybrid();
1029
1030     {
1031         ScopedInstaller appInstall1(app1);
1032         ScopedInstaller appInstall2(app2);
1033         app1.checkAfterInstall();
1034         app2.checkAfterInstall();
1035
1036     }
1037     app1.checkAfterUninstall(false);
1038     app2.checkAfterUninstall();
1039 }