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