b009a931e868bfec48c5916bdf63d8a7a223927e
[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_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         app.checkPrivilegeGroups(defaultAllowedPrivs);
164
165         check_path(app.getPrivateDir(), generatePathRWLabel(app.getPkgId()));
166         check_path(app.getPrivateRODir(), generatePathROLabel(app.getPkgId()), false);
167         check_path(app.getPublicDir(), getPublicPathLabel());
168         check_path(app.getSharedRODir(), getSharedROPathLabel());
169     }
170
171     app.checkAfterUninstall();
172 }
173
174 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
175 {
176     std::string expectedSockLabel = "labelExpectedOnlyFromSocket";
177
178     AppInstallHelper app("sm_test_03a");
179     std::string expectedProcLabel = generateProcessLabel(app.getAppId(), app.getPkgId());
180
181     const auto sockaddr = UDSHelpers::makeAbstractAddress("sm_test_03a.socket");
182     int sock = UDSHelpers::createServer(&sockaddr);
183     SockUniquePtr sockPtr(&sock);
184
185     //Set socket label to something different than expeced process label
186     int result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPIN, expectedSockLabel.c_str());
187     RUNNER_ASSERT_ERRNO_MSG(result == 0,
188         "Can't set socket label. Result: " << result);
189     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPOUT, expectedSockLabel.c_str());
190     RUNNER_ASSERT_ERRNO_MSG(result == 0,
191         "Can't set socket label. Result: " << result);
192
193     ScopedInstaller appInstall(app);
194
195     pid_t pid = fork();
196     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "Fork failed");
197     if (pid == 0) { // child
198         Api::setProcessLabel(app.getAppId());
199
200         char *label = nullptr;
201         CStringPtr labelPtr;
202         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPIN, &label);
203         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
204         labelPtr.reset(label);
205         result = expectedSockLabel.compare(label);
206         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
207             expectedProcLabel << " Actual: " << label);
208
209         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPOUT, &label);
210         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
211         labelPtr.reset(label);
212         result = expectedSockLabel.compare(label);
213         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
214             expectedProcLabel << " Actual: " << label);
215
216         result = smack_new_label_from_self(&label);
217         RUNNER_ASSERT_MSG(result >= 0,
218                 " Error getting current process label");
219         RUNNER_ASSERT_MSG(label != nullptr,
220                 " Process label is not set");
221         labelPtr.reset(label);
222
223         result = expectedProcLabel.compare(label);
224         RUNNER_ASSERT_MSG(result == 0,
225                 " Process label is incorrect. Expected: \"" << expectedProcLabel <<
226                 "\" Actual: \"" << label << "\"");
227     } else { // parent
228         waitPid(pid);
229     }
230 }
231
232 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
233 {
234     const PrivilegeVector allowedPrivs = {PRIV_BLUETOOTH, PRIV_POWER};
235     const PrivilegeVector someDeniedPrivs = {PRIV_DISPLAY, PRIV_NFC};
236
237     TemporaryTestUser testUser("sm_test_04a_user_name", GUM_USERTYPE_NORMAL);
238     testUser.create();
239
240     AppInstallHelperExt app("sm_test_04a", testUser.getUid());
241     app.addPrivileges(allowedPrivs);
242
243     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
244                             "drop_root_privileges failed");
245     {
246         ScopedInstaller appInstall(app, false);
247         app.checkAfterInstall();
248         app.checkDeniedPrivileges(someDeniedPrivs);
249     }
250     app.checkAfterUninstall();
251     app.checkDeniedPrivileges(someDeniedPrivs);
252 }
253
254 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user) {
255     const PrivilegeVector allowedPrivs = {PRIV_INTERNET, PRIV_LED};
256     const PrivilegeVector someDeniedPrivs = {PRIV_LOCATION, PRIV_NOTIFICATION};
257
258     TemporaryTestUser testUser("sm_test_04b_user_name", GUM_USERTYPE_NORMAL);
259     testUser.create();
260
261     AppInstallHelperExt app("sm_test_04b", testUser.getUid());
262     app.addPrivileges(allowedPrivs);
263
264     {
265         ScopedInstaller appInstall(app);
266         app.checkAfterInstall();
267         app.checkDeniedPrivileges(someDeniedPrivs);
268
269         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
270                                 "drop_root_privileges failed");
271     }
272     app.checkAfterUninstall();
273     app.checkDeniedPrivileges(someDeniedPrivs);
274 }
275
276 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
277 {
278     int result;
279     CapsSetsUniquePtr caps_empty(cap_init());
280     auto caps = setCaps("all=eip");
281     Api::dropProcessPrivileges();
282
283     caps.reset(cap_get_proc());
284     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
285
286     result = cap_compare(caps.get(), caps_empty.get());
287     RUNNER_ASSERT_MSG(result == 0,
288         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
289 }
290
291 RUNNER_TEST(security_manager_06_install_app_offline)
292 {
293     ServiceManager("security-manager.service").stopService();
294
295     ServiceManager serviceManager("security-manager.socket");
296     serviceManager.stopService();
297
298     AppInstallHelper app("sm_test_06");
299     ScopedInstaller appInstall(app);
300     // TODO - check if app is installed properly
301     // start service before uninstall, offline mode doesn't support uninstall
302     serviceManager.startService();
303     appInstall.uninstallApp();
304     // TODO - check if app is uninstalled properly
305 }
306
307 RUNNER_CHILD_TEST(security_manager_07a_user_add_app_install)
308 {
309     const PrivilegeVector allowedPrivs = {PRIV_INTERNET, PRIV_LED};
310     const PrivilegeVector someDeniedPrivs = {PRIV_LOCATION, PRIV_NOTIFICATION};
311
312     TemporaryTestUser testUser("sm_test_07a_user_name", GUM_USERTYPE_NORMAL);
313     testUser.create();
314
315     AppInstallHelperExt app("sm_test_07a", testUser.getUid());
316     app.addPrivileges(allowedPrivs);
317
318     InstallRequest req;
319     req.setAppId(app.getAppId());
320     req.setPkgId(app.getPkgId());
321     req.setUid(app.getUID());
322     for (const auto &priv: app.getPrivileges()) {
323         req.addPrivilege(priv);
324     }
325     Api::install(req);
326     app.checkAfterInstall();
327     app.checkDeniedPrivileges(someDeniedPrivs);
328
329     testUser.remove();
330
331     app.checkAfterUninstall();
332     app.checkDeniedPrivileges(someDeniedPrivs);
333 }
334
335 RUNNER_TEST(security_manager_07b_user_add_offline)
336 {
337     ServiceManager("security-manager.service").stopService();
338
339     ServiceManager serviceManager("security-manager.socket");
340     serviceManager.stopService();
341
342     TemporaryTestUser testUser("sm_test_07b_user_name", GUM_USERTYPE_NORMAL, true);
343     testUser.create();
344
345     AppInstallHelperExt app("sm_test_07b", testUser.getUid());
346     ScopedInstaller appInstall(app);
347
348     serviceManager.startService();
349     app.checkAfterInstall();
350
351     testUser.remove();
352     app.checkAfterUninstall();
353 }
354
355 RUNNER_TEST(security_manager_08_user_double_add_double_remove)
356 {
357     const PrivilegeVector somePrivs = {PRIV_LED, PRIV_NOTIFICATION};
358
359     // gumd
360     TemporaryTestUser testUser("sm_test_08_user_name", GUM_USERTYPE_NORMAL);
361     testUser.create();
362
363     // security-manager
364     UserRequest addUserRequest;
365     addUserRequest.setUid(testUser.getUid());
366     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
367     Api::addUser(addUserRequest);
368
369     AppInstallHelperExt app("sm_test_08", testUser.getUid());
370     ScopedInstaller appInstall(app);
371
372     app.checkAfterInstall();
373     app.checkDeniedPrivileges(somePrivs);
374
375     // gumd
376     testUser.remove();
377
378     app.checkAfterUninstall();
379
380     // security-manager
381     UserRequest deleteUserRequest;
382     deleteUserRequest.setUid(testUser.getUid());
383     Api::deleteUser(deleteUserRequest);
384 }
385
386 RUNNER_TEST(security_manager_09_app_install_constraint_check)
387 {
388     auto install = [](const AppInstallHelperExt& app, bool success)
389     {
390         auto expected = success ? SECURITY_MANAGER_SUCCESS : SECURITY_MANAGER_ERROR_INPUT_PARAM;
391         ScopedInstaller appInstall(app, true, expected);
392         if (success)
393             app.checkAfterInstall();
394         return appInstall;
395     };
396
397     auto update = [](const AppInstallHelperExt& app)
398     {
399         InstallRequest request;
400         request.setAppId(app.getAppId());
401         request.setPkgId(app.getPkgId());
402         request.setAppTizenVersion(app.getVersion());
403         request.setAuthorId(app.getAuthor());
404         request.setUid(app.getUID());
405         if (app.getIsHybrid())
406             request.setHybrid();
407         Api::update(request);
408     };
409
410     TemporaryTestUser users[] = {
411         {"sm_test_09_user_name_0", GUM_USERTYPE_NORMAL, false},
412         {"sm_test_09_user_name_1", GUM_USERTYPE_NORMAL, false}
413     };
414
415     for (auto& gu : users)
416         gu.create();
417
418     const char *const pkgIdPrefix[] =   {"sm_test_09_0",            "sm_test_09_1"};
419     const char *const appIdPrefix[] =   {"sm_test_09_0",            "sm_test_09_1"};
420     const char *const version[] =       {"sm_test_09_0_version",    "sm_test_09_1_version"};
421     const char *const author[] =        {"sm_test_09_0_author",     "sm_test_09_1_author"};
422     bool hybrid[] = {false, true};
423
424     std::list<AppInstallHelperExt> apps;
425
426     auto make_helper = [&](size_t userIdx,
427                            size_t pkgIdx,
428                            size_t appIdx,
429                            size_t verIdx,
430                            size_t authorIdx,
431                            size_t hybridIdx) -> AppInstallHelperExt&
432     {
433         apps.emplace_back(appIdPrefix[appIdx], pkgIdPrefix[pkgIdx], users[userIdx].getUid());
434         apps.back().setAuthor(author[authorIdx]);
435         apps.back().setVersion(version[verIdx]);
436         if (hybrid[hybridIdx])
437             apps.back().setHybrid();
438         return apps.back();
439     };
440
441     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> ok
442     auto &app000000 = make_helper(0, 0, 0, 0, 0, 0);
443     auto i1 = install(app000000, true);
444
445     // uid_1, pkg_0, app_0, version_0, author_0, not hybrid -> ok (different uid)
446     auto& app100000 = make_helper(1, 0, 0, 0, 0, 0);
447     install(app100000, true);
448
449     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> conflicts with existing non hybrid app
450     auto& app000001 = make_helper(0, 0, 0, 0, 0, 1);
451     install(app000001, false);
452
453     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> ok (app updated to hybrid)
454     update(app000001);
455
456     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> ok (app installed again)
457     auto i2 = install(app000001, true);
458
459     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> conflicts with existing hybrid app
460     install(app000000, false);
461
462     // uid_0, pkg_0, app_1, version_0, author_0, hybrid -> ok (new app id)
463     auto& app001001 = make_helper(0, 0, 1, 0, 0, 1);
464     auto i3 = install(app001001, true);
465
466     // uid_1, pkg_0, app_0, version_0, author_0, hybrid -> ok (hybrid, different uid)
467     auto& app100001 = make_helper(1, 0, 0, 0, 0, 1);
468     auto i4 = install(app100001, true);
469
470     // uid_1, pkg_0, app_0, version_0, author_1, not hybrid -> author of app_0 must be the same
471     auto& app100010 = make_helper(1, 0, 0, 0, 1, 0);
472     install(app100010, false);
473
474     // uid_1, pkg_0, app_0, version_1, author_0, not hybrid -> ok (app version and hybridity changed)
475     auto& app100100 = make_helper(1, 0, 0, 1, 0, 0);
476     update(app100100);
477
478     // uid_1, pkg_1, app_0, version_1, author_0, not hybrid -> pkg of app_0 must be the same
479     auto& app110100 = make_helper(1, 1, 0, 1, 0, 0);
480     install(app110100, false);
481
482     for (auto& gu : users)
483         gu.remove();
484
485     RUNNER_IGNORED_MSG("Disabled until hybridity update works properly for all users");
486     for (auto& app : apps)
487         app.checkAfterUninstall();
488 }
489
490 RUNNER_TEST(security_manager_09a_install_many_apps_in_single_request)
491 {
492     constexpr char pkgIdPrefix[] = "sm_test_09a";
493     const AppInstallHelperExt apps[] = {{"sm_test_09a_0", pkgIdPrefix},
494                                         {"sm_test_09a_1", pkgIdPrefix},
495                                         {"sm_test_09a_2", pkgIdPrefix}};
496     static_assert(sizeof(apps) > 0);
497
498     std::vector<std::string> appIds;
499     for (auto &app : apps)
500         appIds.push_back(app.getAppId());
501
502     {
503         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
504         // Installing many applications in single request
505         for (auto &app : apps) {
506             app.checkAfterInstall();
507         }
508     }
509
510     for (auto &app : apps) {
511         app.checkAfterUninstall();
512     }
513 }
514
515 RUNNER_TEST(security_manager_09b_install_many_apps_in_single_request_duplicated_ids)
516 {
517     AppInstallHelperExt app("sm_test_09b");
518     {
519         ScopedInstaller appsInstall({app.getAppId(), app.getAppId()}, app.getPkgId());
520         app.checkAfterInstall();
521     }
522
523     app.checkAfterUninstall();
524 }
525
526 RUNNER_TEST(security_manager_09c_update_many_apps_in_single_request_hybrid_package)
527 {
528     constexpr char pkgIdPrefix[] = "sm_test_09c";
529     AppInstallHelperExt apps[] = {{"sm_test_09c_0", pkgIdPrefix},
530                                   {"sm_test_09c_1", pkgIdPrefix},
531                                   {"sm_test_09c_2", pkgIdPrefix}};
532     static_assert(sizeof(apps) > 0);
533
534     std::vector<std::string> appIds;
535     for (const auto &app : apps)
536         appIds.push_back(app.getAppId());
537
538     {
539         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
540         // Package is not hybrid, every app has same policy.
541         for (const auto &app : apps) {
542             app.checkAfterInstall();
543         }
544
545         // Updating package -- changing set of apps in package and setting hybrid mode
546         InstallRequest updateRequest;
547         updateRequest.setPkgId(apps[0].getPkgId());
548         updateRequest.setAppId(appIds[0]);
549         updateRequest.nextApp();
550         updateRequest.setAppId(appIds[1]);
551         updateRequest.setHybrid();
552
553         Api::update(updateRequest);
554
555         // Package became hybrid, so every app has its own Smack label
556         for (auto &app : apps) {
557             app.setHybrid();
558         }
559         apps[0].checkAfterInstall();
560         apps[1].checkAfterInstall();
561
562         // Package became hybrid properly,
563         // so app not included in updated version of package was uninstalled.
564         apps[2].checkAfterUninstall(false);
565     }
566
567     for (const auto &app : apps) {
568         app.checkAfterUninstall();
569     }
570 }
571
572 RUNNER_TEST(security_manager_09d_uninstall_app_from_hybrid_package)
573 {
574     constexpr char pkgIdPrefix[] = "sm_test_09d";
575     AppInstallHelperExt apps[] = {{"sm_test_09d_0", pkgIdPrefix},
576                                   {"sm_test_09d_1", pkgIdPrefix},
577                                   {"sm_test_09d_2", pkgIdPrefix}};
578     static_assert(sizeof(apps) > 0);
579
580     std::vector<std::string> appIds;
581     for (const auto &app : apps)
582         appIds.push_back(app.getAppId());
583
584     {
585         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
586
587         InstallRequest updateRequest;
588         updateRequest.setPkgId(apps[0].getPkgId());
589         for (unsigned int i = 0; i < appIds.size(); i++) {
590             if (i > 0) {
591                 updateRequest.nextApp();
592             }
593             updateRequest.setAppId(appIds[i]);
594         }
595         updateRequest.setHybrid();
596         Api::update(updateRequest);
597
598         InstallRequest uninstRequest;
599         uninstRequest.setPkgId(apps[0].getPkgId());
600         uninstRequest.setAppId(appIds[0]);
601         Api::uninstall(uninstRequest);
602
603         for (auto &app : apps) {
604             app.setHybrid();
605         }
606         apps[0].checkAfterUninstall(false);
607     }
608     for (const auto &app : apps) {
609         app.checkAfterUninstall();
610     }
611 }
612
613 RUNNER_CHILD_TEST(security_manager_10_app_has_privilege)
614 {
615     const PrivilegeVector allowedPrivs = {PRIV_WIFIDIRECT, PRIV_TELEPHONY};
616     const PrivilegeVector someDeniedPrivs = {PRIV_VPNSERVICE, PRIV_NOTIFICATION};
617
618     AppInstallHelperExt app("sm_test_10");
619     app.addPrivileges(allowedPrivs);
620     ScopedInstaller appInstall(app);
621
622     app.checkAfterInstall();
623     app.checkDeniedPrivileges(someDeniedPrivs);
624     // FIXME - all other existing privileges should be checked
625 }
626
627 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_POLICY)
628
629 RUNNER_TEST(security_manager_20_user_cynara_policy)
630 {
631     // FIXME - whitebox - cynara
632     const char *const MAIN_BUCKET = "MAIN";
633     const char *const MANIFESTS_GLOBAL_BUCKET = "MANIFESTS_GLOBAL";
634     const char *const MANIFESTS_LOCAL_BUCKET = "MANIFESTS_LOCAL";
635     const char *const ADMIN_BUCKET = "ADMIN";
636     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
637     CynaraTestAdmin::Admin admin;
638
639     TemporaryTestUser user("sm_test_20_user_name", GUM_USERTYPE_NORMAL, false);
640     user.create();
641     std::string uid_string = user.getUidString();
642
643     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
644     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
645     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
646
647     user.remove();
648     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
649
650     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
651     admin.listPolicies(MANIFESTS_GLOBAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
652     admin.listPolicies(MANIFESTS_LOCAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
653     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
654     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
655 }
656
657 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
658 {
659     const PrivilegeVector adminRequiredPrivs = {PRIV_NOTEXIST, PRIV_INTERNAL_USERMANAGEMENT};
660     const PrivilegeVector manifestPrivs = {PRIV_INTERNET, PRIV_DATASHARING};
661     const PrivilegeVector allowedPrivsAfterChange = {PRIV_DATASHARING};
662     const PrivilegeVector deniedPrivsAfterChange = {PRIV_INTERNET};
663
664     TemporaryTestUser adminUser("sm_test_21_admin_user_name", GUM_USERTYPE_ADMIN, false);
665     TemporaryTestUser normalUser("sm_test_21_normal_user_name", GUM_USERTYPE_NORMAL, false);
666
667     adminUser.create();
668     normalUser.create();
669
670     AppInstallHelper adminApp("sm_test_21_admin", adminUser.getUid());
671     adminApp.addPrivileges(adminRequiredPrivs);
672     ScopedInstaller adminAppInstall(adminApp);
673
674     AppInstallHelperExt normalApp("sm_test_21_normal", normalUser.getUid());
675     normalApp.addPrivileges(manifestPrivs);
676     ScopedInstaller normalAppInstall(normalApp);
677     normalApp.checkAfterInstall();
678
679     pid_t pid = fork();
680     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
681     if (pid != 0) { //parent process
682         waitPid(pid);
683         normalApp.checkPrivileges(allowedPrivsAfterChange, deniedPrivsAfterChange);
684     } else {
685         Api::setProcessLabel(adminApp.getAppId());
686         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(),adminUser.getGid()) == 0,
687                                 "drop_root_privileges failed");
688
689         PolicyRequest addPolicyReq;
690         for (auto &deniedPriv : deniedPrivsAfterChange) {
691             PolicyEntry entry(SECURITY_MANAGER_ANY, normalUser.getUidString(), deniedPriv);
692             entry.setMaxLevel(PolicyEntry::LEVEL_DENY);
693             addPolicyReq.addEntry(entry);
694         }
695         Api::sendPolicy(addPolicyReq);
696         exit(0);
697     }
698 }
699
700 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CMD)
701
702 RUNNER_TEST(security_manager_22_security_manager_cmd_install)
703 {
704     int ret;
705     const int SUCCESS = 0;
706     const int FAILURE = 256;
707     const std::string app_id = "sm_test_22_app_id";
708     const std::string pkg_id = "sm_test_22_pkg_id";
709     const std::string username("sm_test_22_user_name");
710
711     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL);
712     user.create();
713
714     const std::string path1 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p1";
715     const std::string path2 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p2";
716     const std::string pkgopt = " --pkg=" + pkg_id;
717     const std::string appopt = " --app=" + app_id;
718     const std::string uidopt = " --uid=" + user.getUidString();
719
720     mktreeSafe(path1.c_str(), 0);
721     mktreeSafe(path2.c_str(), 0);
722
723     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
724
725     struct operation {
726         std::string command;
727         int expected_result;
728     };
729     std::vector<struct operation> operations = {
730             {"security-manager-cmd", FAILURE},//no option
731             {"security-manager-cmd --blah", FAILURE},//blah option is not known
732             {"security-manager-cmd --help", SUCCESS},
733             {"security-manager-cmd --install", FAILURE},//no params
734             {"security-manager-cmd -i", FAILURE},//no params
735             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
736             {installcmd, SUCCESS},
737             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
738             {installcmd + " --path " + path1 + " rw", SUCCESS},
739             {installcmd + " --path " + path1, FAILURE},//no path type
740             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
741             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
742             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
743     };
744
745     for (auto &op : operations) {
746         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
747         RUNNER_ASSERT_MSG(ret == op.expected_result,
748                 "Unexpected result for command '" << op.command <<"': "
749                 << ret << " Expected was: "<< op.expected_result);
750     }
751 }
752
753 RUNNER_TEST(security_manager_23_security_manager_cmd_users)
754 {
755     const int SUCCESS = 0;
756     const int FAILURE = 256;
757     TemporaryTestUser user("sm_test_23_user_name", GUM_USERTYPE_NORMAL, false);
758     user.create();
759     const std::string uidopt = " --uid=" + user.getUidString();
760
761     struct operation {
762         std::string command;
763         int expected_result;
764     };
765     std::vector<struct operation> operations = {
766             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
767             {"security-manager-cmd -m", FAILURE},//no params
768             {"security-manager-cmd -mr", FAILURE},//no uid
769             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
770             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
771             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
772             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
773             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
774             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
775             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
776             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
777     };
778
779     for (auto &op : operations) {
780         int 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_GROUP_INIT(SECURITY_MANAGER_GROUPS)
788
789 RUNNER_TEST(security_manager_24_groups_get)
790 {
791     PolicyConfiguration pc;
792     gid_t * c_groups;
793     size_t count = 0;
794
795     Api::getSecurityManagerGroups(&c_groups, &count);
796     std::unique_ptr<gid_t, decltype(free)*> groupsPtr(c_groups, free);
797
798     auto policyGroups = pc.getGid();
799     RUNNER_ASSERT_MSG(count == policyGroups.size(), "security_manager_groups_get should set count to: "
800                       << policyGroups.size() << " but count is: " << count);
801
802     for (const auto &group : policyGroups) {
803         bool found = false;
804         for (size_t i = 0; i < count; ++i) {
805             if (group == c_groups[i]) {
806                 found = true;
807                 break;
808             }
809         }
810         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
811     }
812 }
813
814 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
815
816 RUNNER_TEST(security_manager_25a_global_user_set_install_type_global)
817 {
818     AppInstallHelperExt app("sm_test_25a");
819     app.setInstallType(SM_APP_INSTALL_GLOBAL);
820     {
821         ScopedInstaller appInstall(app);
822
823         app.checkAfterInstall();
824     }
825
826     // Check records in the security-manager database
827     app.checkAfterUninstall();
828 }
829
830 RUNNER_TEST(security_manager_25b_global_user_set_install_type_local)
831 {
832     AppInstallHelper app("sm_test_25b");
833
834     InstallRequest requestInst;
835     requestInst.setAppId(app.getAppId());
836     requestInst.setPkgId(app.getPkgId());
837     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
838
839     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
840 }
841
842 RUNNER_TEST(security_manager_25c_global_user_set_install_type_preloaded)
843 {
844     AppInstallHelperExt app("sm_test_25c");
845     app.setInstallType(SM_APP_INSTALL_PRELOADED);
846     {
847         ScopedInstaller appInstall(app);
848         app.checkAfterInstall();
849     }
850     app.checkAfterUninstall();
851 }
852
853 RUNNER_TEST(security_manager_25d_local_user_set_install_type_invalid)
854 {
855     InstallRequest requestPrivateUser;
856     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
857     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
858 }
859
860 /*
861  * It is possible for local user to install global application but one needs app_install privileges
862  * By default only global user or root can install global apps (or "User", "System", "System::Privileged"...)
863  */
864 RUNNER_CHILD_TEST(security_manager_25e_unprivileged_install_type_global)
865 {
866     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
867
868     TemporaryTestUser testUser("sm_test_25e_user_name", GUM_USERTYPE_NORMAL);
869     testUser.create();
870
871     AppInstallHelper app("sm_test_25e");
872
873     ScopedProcessLabel spl("_", false);
874     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
875                             "drop_root_privileges failed");
876
877     InstallRequest invalidReq;
878     invalidReq.setAppId(app.getAppId());
879     invalidReq.setPkgId(app.getPkgId());
880     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
881
882     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
883 }
884
885 RUNNER_CHILD_TEST(security_manager_25f_unprivileged_install_type_preloaded)
886 {
887     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
888
889     TemporaryTestUser testUser("sm_test_25f_user_name", GUM_USERTYPE_NORMAL);
890     testUser.create();
891
892     AppInstallHelper app("sm_test_25f");
893
894     ScopedProcessLabel spl("_", false);
895     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
896                             "drop_root_privileges failed");
897     InstallRequest invalidReq;
898     invalidReq.setAppId(app.getAppId());
899     invalidReq.setPkgId(app.getPkgId());
900     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
901     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
902 }
903
904 RUNNER_CHILD_TEST(security_manager_25g_local_user_set_install_type_local)
905 {
906     const PrivilegeVector allowedPrivs = {PRIV_VOLUME_SET, PRIV_SYSTEMMONITOR, PRIV_INTERNET};
907     const PrivilegeVector someDeniedPrivs = {PRIV_PUSH, PRIV_POWER, PRIV_NOTIFICATION};
908
909     TemporaryTestUser testUser("sm_test_25g_user_name", GUM_USERTYPE_NORMAL);
910     testUser.create();
911
912     AppInstallHelperExt app("sm_test_25g", testUser.getUid());
913     app.createPrivateDir();
914     app.setInstallType(SM_APP_INSTALL_LOCAL);
915     app.addPrivileges(allowedPrivs);
916
917     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
918                             "drop_root_privileges failed");
919     {
920         ScopedInstaller appInstall(app);
921         app.checkAfterInstall();
922         app.checkDeniedPrivileges(someDeniedPrivs);
923     }
924     app.checkAfterUninstall();
925 }
926
927 RUNNER_CHILD_TEST(security_manager_25h_local_path_global_install)
928 {
929     TemporaryTestUser testUser("sm_test_25h_user_name", GUM_USERTYPE_NORMAL);
930     testUser.create();
931
932     AppInstallHelper app("sm_test_25h", testUser.getUid());
933     app.createPrivateDir();
934
935     InstallRequest invalidReq;
936     invalidReq.setAppId(app.getAppId());
937     invalidReq.setPkgId(app.getPkgId());
938     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
939     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
940     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
941 }
942
943 RUNNER_CHILD_TEST(security_manager_25i_local_path_preloaded_install)
944 {
945     TemporaryTestUser testUser("sm_test_25i_user_name", GUM_USERTYPE_NORMAL);
946     testUser.create();
947
948     AppInstallHelper app("sm_test_25i", testUser.getUid());
949     app.createPrivateDir();
950
951     InstallRequest invalidReq;
952     invalidReq.setAppId(app.getAppId());
953     invalidReq.setPkgId(app.getPkgId());
954     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
955     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
956     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
957 }
958
959 RUNNER_CHILD_TEST(security_manager_25j_global_path_local_install)
960 {
961     TemporaryTestUser testUser("sm_test_25j_user_name", GUM_USERTYPE_NORMAL);
962     testUser.create();
963
964     AppInstallHelper appLocal("sm_test_25j", testUser.getUid());
965
966     AppInstallHelper appGlobal("sm_test_25");
967     appGlobal.createPrivateDir();
968
969     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
970                             "drop_root_privileges failed");
971
972     InstallRequest invalidReq;
973     invalidReq.setAppId(appLocal.getAppId());
974     invalidReq.setPkgId(appLocal.getPkgId());
975     invalidReq.addPath(appGlobal.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
976     invalidReq.setInstallType(SM_APP_INSTALL_LOCAL);
977
978     Api::install(invalidReq, SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
979 }
980
981 RUNNER_CHILD_TEST(security_manager_26_hybrid_pkg_uninstall_artifacts_check)
982 {
983     TemporaryTestUser testUser("sm_test_26_user_name", GUM_USERTYPE_NORMAL);
984     testUser.create();
985
986     const PrivilegeVector allowedPrivs = {PRIV_WIFIDIRECT, PRIV_TELEPHONY};
987
988     AppInstallHelperExt app1("sm_test_26_1", "sm_test_26", testUser.getUid());
989     app1.addPrivileges(allowedPrivs);
990     app1.setHybrid();
991
992     AppInstallHelperExt app2("sm_test_26_2", "sm_test_26", testUser.getUid());
993     app2.addPrivileges(allowedPrivs);
994     app2.setHybrid();
995
996     {
997         ScopedInstaller appInstall1(app1);
998         ScopedInstaller appInstall2(app2);
999         app1.checkAfterInstall();
1000         app2.checkAfterInstall();
1001
1002     }
1003     app1.checkAfterUninstall(false);
1004     app2.checkAfterUninstall();
1005 }