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