Unify privilege representation
[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 TemporaryTestUser& user,
389                       const char *pkgId,
390                       const char *appId,
391                       const char *version,
392                       const char *author,
393                       bool isHybrid,
394                       enum lib_retcode expected,
395                       bool uninstall = true)
396     {
397         InstallRequest request;
398         request.setAppId(appId);
399         request.setPkgId(pkgId);
400         request.setAppTizenVersion(version);
401         request.setAuthorId(author);
402         request.setUid(user.getUid());
403         if (isHybrid)
404             request.setHybrid();
405         Api::install(request, expected);
406
407         if(expected == SECURITY_MANAGER_SUCCESS && uninstall) {
408             Api::uninstall(request);
409         }
410     };
411
412     auto update = [](const TemporaryTestUser& user,
413                      const char *pkgId,
414                      const char *appId,
415                      const char *version,
416                      const char *author,
417                      bool isHybrid,
418                      enum lib_retcode expected,
419                      bool uninstall = true)
420     {
421         InstallRequest request;
422         request.setAppId(appId);
423         request.setPkgId(pkgId);
424         request.setAppTizenVersion(version);
425         request.setAuthorId(author);
426         request.setUid(user.getUid());
427         if (isHybrid)
428             request.setHybrid();
429         Api::update(request, expected);
430
431         if(expected == SECURITY_MANAGER_SUCCESS && uninstall) {
432             Api::uninstall(request);
433         }
434     };
435
436     TemporaryTestUser users[] = {
437         {"sm_test_09_user_name_0", GUM_USERTYPE_NORMAL, false},
438         {"sm_test_09_user_name_1", GUM_USERTYPE_NORMAL, false}
439     };
440
441     for (auto& gu : users)
442         gu.create();
443
444     const char *const pkgId[] =   {"sm_test_09_pkg_id_0",  "sm_test_09_pkg_id_1"};
445     const char *const appId[] =   {"sm_test_09_app_id_0",  "sm_test_09_app_id_1"};
446     const char *const version[] = {"sm_test_09_version_0", "sm_test_09_version_1"};
447     const char *const author[] =  {"sm_test_09_author_0",  "sm_test_09_author_1"};
448     bool hybrid[] = {false, true};
449
450     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid
451     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS, false);
452     // uid_1, pkg_0, app_0, version_0, author_0, not hybrid -> ok (different uid)
453     install(users[1], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS);
454     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> ok for update (different hybrid setting)
455     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_ERROR_INPUT_PARAM);
456     update(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_SUCCESS, false);
457     // uid_0, pkg_0, app_1, version_0, author_0, hybrid -> ok (new app id)
458     install(users[0], pkgId[0], appId[1], version[0], author[0], hybrid[1], SECURITY_MANAGER_SUCCESS, false);
459     // uid_1, pkg_0, app_0, version_0, author_0, hybrid -> ok (different hybrid setting)
460     install(users[1], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_SUCCESS, false);
461     // uid_1, pkg_0, app_0, version_0, author_1, not hybrid -> fail (author of app_0 must be the same)
462     install(users[1], pkgId[0], appId[0], version[0], author[1], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
463     // uid_1, pkg_0, app_0, version_1, author_0, not hybrid -> ok (version upgrade and different hybrid setting)
464     install(users[1], pkgId[0], appId[0], version[1], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
465     update(users[1], pkgId[0], appId[0], version[1], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS);
466     // uid_1, pkg_1, app_0, version_0, author_0, not hybrid -> fail (pkg of app_0 must be the same)
467     install(users[1], pkgId[1], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
468     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> ok (the same app again)
469     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS, false);
470     // uid_0, pkg_1, app_0, version_0, author_0, not hybrid -> fail (app_name + uid must be unique)
471     install(users[0], pkgId[1], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
472     // uid_0, pkg_0, app_0, version_0, author_1, not hybrid -> fail (app_name + uid must be unique)
473     install(users[0], pkgId[0], appId[0], version[0], author[1], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
474 }
475
476 RUNNER_TEST(security_manager_09a_install_many_apps_in_single_request)
477 {
478     constexpr char pkgIdPrefix[] = "sm_test_09a";
479     const AppInstallHelperExt apps[] = {{"sm_test_09a_0", pkgIdPrefix},
480                                         {"sm_test_09a_1", pkgIdPrefix},
481                                         {"sm_test_09a_2", pkgIdPrefix}};
482     static_assert(sizeof(apps) > 0);
483
484     std::vector<std::string> appIds;
485     for (auto &app : apps)
486         appIds.push_back(app.getAppId());
487
488     {
489         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
490         // Installing many applications in single request
491         for (auto &app : apps) {
492             app.checkAfterInstall();
493         }
494     }
495
496     for (auto &app : apps) {
497         app.checkAfterUninstall();
498     }
499 }
500
501 RUNNER_TEST(security_manager_09b_install_many_apps_in_single_request_duplicated_ids)
502 {
503     AppInstallHelperExt app("sm_test_09b");
504     {
505         ScopedInstaller appsInstall({app.getAppId(), app.getAppId()}, app.getPkgId());
506         app.checkAfterInstall();
507     }
508
509     app.checkAfterUninstall();
510 }
511
512 RUNNER_TEST(security_manager_09c_update_many_apps_in_single_request_hybrid_package)
513 {
514     constexpr char pkgIdPrefix[] = "sm_test_09c";
515     AppInstallHelperExt apps[] = {{"sm_test_09c_0", pkgIdPrefix},
516                                   {"sm_test_09c_1", pkgIdPrefix},
517                                   {"sm_test_09c_2", pkgIdPrefix}};
518     static_assert(sizeof(apps) > 0);
519
520     std::vector<std::string> appIds;
521     for (const auto &app : apps)
522         appIds.push_back(app.getAppId());
523
524     {
525         ScopedInstaller appsInstall(appIds, apps[0].getPkgId());
526         // Package is not hybrid, every app has same policy.
527         for (const auto &app : apps) {
528             app.checkAfterInstall();
529         }
530
531         // Updating package -- changing set of apps in package and setting hybrid mode
532         InstallRequest updateRequest;
533         updateRequest.setPkgId(apps[0].getPkgId());
534         updateRequest.setAppId(appIds[0]);
535         updateRequest.nextApp();
536         updateRequest.setAppId(appIds[1]);
537         updateRequest.setHybrid();
538
539         Api::update(updateRequest);
540
541         // Package became hybrid, so every app has its own Smack label
542         for (auto &app : apps) {
543             app.setHybrid();
544         }
545         apps[0].checkAfterInstall();
546         apps[1].checkAfterInstall();
547
548         // Package became hybrid properly,
549         // so app not included in updated version of package was uninstalled.
550         apps[2].checkAfterUninstall(false);
551     }
552
553     for (const auto &app : apps) {
554         app.checkAfterUninstall();
555     }
556 }
557
558 RUNNER_TEST(security_manager_09d_uninstall_app_from_hybrid_package)
559 {
560     constexpr char pkgIdPrefix[] = "sm_test_09d";
561     AppInstallHelperExt apps[] = {{"sm_test_09d_0", pkgIdPrefix},
562                                   {"sm_test_09d_1", pkgIdPrefix},
563                                   {"sm_test_09d_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
573         InstallRequest updateRequest;
574         updateRequest.setPkgId(apps[0].getPkgId());
575         for (unsigned int i = 0; i < appIds.size(); i++) {
576             if (i > 0) {
577                 updateRequest.nextApp();
578             }
579             updateRequest.setAppId(appIds[i]);
580         }
581         updateRequest.setHybrid();
582         Api::update(updateRequest);
583
584         InstallRequest uninstRequest;
585         uninstRequest.setPkgId(apps[0].getPkgId());
586         uninstRequest.setAppId(appIds[0]);
587         Api::uninstall(uninstRequest);
588
589         for (auto &app : apps) {
590             app.setHybrid();
591         }
592         apps[0].checkAfterUninstall(false);
593     }
594     for (const auto &app : apps) {
595         app.checkAfterUninstall();
596     }
597 }
598
599 RUNNER_CHILD_TEST(security_manager_10_app_has_privilege)
600 {
601     const PrivilegeVector allowedPrivs = {PRIV_WIFIDIRECT, PRIV_TELEPHONY};
602     const PrivilegeVector someDeniedPrivs = {PRIV_VPNSERVICE, PRIV_NOTIFICATION};
603
604     AppInstallHelperExt app("sm_test_10");
605     app.addPrivileges(allowedPrivs);
606     ScopedInstaller appInstall(app);
607
608     app.checkAfterInstall();
609     app.checkDeniedPrivileges(someDeniedPrivs);
610     // FIXME - all other existing privileges should be checked
611 }
612
613 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_POLICY)
614
615 RUNNER_TEST(security_manager_20_user_cynara_policy)
616 {
617     // FIXME - whitebox - cynara
618     const char *const MAIN_BUCKET = "MAIN";
619     const char *const MANIFESTS_GLOBAL_BUCKET = "MANIFESTS_GLOBAL";
620     const char *const MANIFESTS_LOCAL_BUCKET = "MANIFESTS_LOCAL";
621     const char *const ADMIN_BUCKET = "ADMIN";
622     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
623     CynaraTestAdmin::Admin admin;
624
625     TemporaryTestUser user("sm_test_20_user_name", GUM_USERTYPE_NORMAL, false);
626     user.create();
627     std::string uid_string = user.getUidString();
628
629     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
630     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
631     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
632
633     user.remove();
634     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
635
636     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
637     admin.listPolicies(MANIFESTS_GLOBAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
638     admin.listPolicies(MANIFESTS_LOCAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
639     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
640     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
641 }
642
643 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
644 {
645     const PrivilegeVector adminRequiredPrivs = {PRIV_NOTEXIST, PRIV_INTERNAL_USERMANAGEMENT};
646     const PrivilegeVector manifestPrivs = {PRIV_INTERNET, PRIV_DATASHARING};
647     const PrivilegeVector allowedPrivsAfterChange = {PRIV_DATASHARING};
648     const PrivilegeVector deniedPrivsAfterChange = {PRIV_INTERNET};
649
650     TemporaryTestUser adminUser("sm_test_21_admin_user_name", GUM_USERTYPE_ADMIN, false);
651     TemporaryTestUser normalUser("sm_test_21_normal_user_name", GUM_USERTYPE_NORMAL, false);
652
653     adminUser.create();
654     normalUser.create();
655
656     AppInstallHelper adminApp("sm_test_21_admin", adminUser.getUid());
657     adminApp.addPrivileges(adminRequiredPrivs);
658     ScopedInstaller adminAppInstall(adminApp);
659
660     AppInstallHelperExt normalApp("sm_test_21_normal", normalUser.getUid());
661     normalApp.addPrivileges(manifestPrivs);
662     ScopedInstaller normalAppInstall(normalApp);
663     normalApp.checkAfterInstall();
664
665     pid_t pid = fork();
666     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
667     if (pid != 0) { //parent process
668         waitPid(pid);
669         normalApp.checkPrivileges(allowedPrivsAfterChange, deniedPrivsAfterChange);
670     } else {
671         Api::setProcessLabel(adminApp.getAppId());
672         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(),adminUser.getGid()) == 0,
673                                 "drop_root_privileges failed");
674
675         PolicyRequest addPolicyReq;
676         for (auto &deniedPriv : deniedPrivsAfterChange) {
677             PolicyEntry entry(SECURITY_MANAGER_ANY, normalUser.getUidString(), deniedPriv);
678             entry.setMaxLevel(PolicyEntry::LEVEL_DENY);
679             addPolicyReq.addEntry(entry);
680         }
681         Api::sendPolicy(addPolicyReq);
682         exit(0);
683     }
684 }
685
686 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CMD)
687
688 RUNNER_TEST(security_manager_22_security_manager_cmd_install)
689 {
690     int ret;
691     const int SUCCESS = 0;
692     const int FAILURE = 256;
693     const std::string app_id = "sm_test_22_app_id";
694     const std::string pkg_id = "sm_test_22_pkg_id";
695     const std::string username("sm_test_22_user_name");
696
697     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL);
698     user.create();
699
700     const std::string path1 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p1";
701     const std::string path2 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p2";
702     const std::string pkgopt = " --pkg=" + pkg_id;
703     const std::string appopt = " --app=" + app_id;
704     const std::string uidopt = " --uid=" + user.getUidString();
705
706     mktreeSafe(path1.c_str(), 0);
707     mktreeSafe(path2.c_str(), 0);
708
709     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
710
711     struct operation {
712         std::string command;
713         int expected_result;
714     };
715     std::vector<struct operation> operations = {
716             {"security-manager-cmd", FAILURE},//no option
717             {"security-manager-cmd --blah", FAILURE},//blah option is not known
718             {"security-manager-cmd --help", SUCCESS},
719             {"security-manager-cmd --install", FAILURE},//no params
720             {"security-manager-cmd -i", FAILURE},//no params
721             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
722             {installcmd, SUCCESS},
723             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
724             {installcmd + " --path " + path1 + " rw", SUCCESS},
725             {installcmd + " --path " + path1, FAILURE},//no path type
726             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
727             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
728             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
729     };
730
731     for (auto &op : operations) {
732         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
733         RUNNER_ASSERT_MSG(ret == op.expected_result,
734                 "Unexpected result for command '" << op.command <<"': "
735                 << ret << " Expected was: "<< op.expected_result);
736     }
737 }
738
739 RUNNER_TEST(security_manager_23_security_manager_cmd_users)
740 {
741     const int SUCCESS = 0;
742     const int FAILURE = 256;
743     TemporaryTestUser user("sm_test_23_user_name", GUM_USERTYPE_NORMAL, false);
744     user.create();
745     const std::string uidopt = " --uid=" + user.getUidString();
746
747     struct operation {
748         std::string command;
749         int expected_result;
750     };
751     std::vector<struct operation> operations = {
752             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
753             {"security-manager-cmd -m", FAILURE},//no params
754             {"security-manager-cmd -mr", FAILURE},//no uid
755             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
756             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
757             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
758             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
759             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
760             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
761             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
762             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
763     };
764
765     for (auto &op : operations) {
766         int ret = system((op.command + " 1>/dev/null 2>&1").c_str());
767         RUNNER_ASSERT_MSG(ret == op.expected_result,
768                 "Unexpected result for command '" << op.command <<"': "
769                 << ret << " Expected was: "<< op.expected_result);
770     }
771 }
772
773 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_GROUPS)
774
775 RUNNER_TEST(security_manager_24_groups_get)
776 {
777     PolicyConfiguration pc;
778     gid_t * c_groups;
779     size_t count = 0;
780
781     Api::getSecurityManagerGroups(&c_groups, &count);
782     std::unique_ptr<gid_t, decltype(free)*> groupsPtr(c_groups, free);
783
784     auto policyGroups = pc.getGid();
785     RUNNER_ASSERT_MSG(count == policyGroups.size(), "security_manager_groups_get should set count to: "
786                       << policyGroups.size() << " but count is: " << count);
787
788     for (const auto &group : policyGroups) {
789         bool found = false;
790         for (size_t i = 0; i < count; ++i) {
791             if (group == c_groups[i]) {
792                 found = true;
793                 break;
794             }
795         }
796         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
797     }
798 }
799
800 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
801
802 RUNNER_TEST(security_manager_25a_global_user_set_install_type_global)
803 {
804     AppInstallHelperExt app("sm_test_25a");
805     app.setInstallType(SM_APP_INSTALL_GLOBAL);
806     {
807         ScopedInstaller appInstall(app);
808
809         app.checkAfterInstall();
810     }
811
812     // Check records in the security-manager database
813     app.checkAfterUninstall();
814 }
815
816 RUNNER_TEST(security_manager_25b_global_user_set_install_type_local)
817 {
818     AppInstallHelper app("sm_test_25b");
819
820     InstallRequest requestInst;
821     requestInst.setAppId(app.getAppId());
822     requestInst.setPkgId(app.getPkgId());
823     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
824
825     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
826 }
827
828 RUNNER_TEST(security_manager_25c_global_user_set_install_type_preloaded)
829 {
830     AppInstallHelperExt app("sm_test_25c");
831     app.setInstallType(SM_APP_INSTALL_PRELOADED);
832     {
833         ScopedInstaller appInstall(app);
834         app.checkAfterInstall();
835     }
836     app.checkAfterUninstall();
837 }
838
839 RUNNER_TEST(security_manager_25d_local_user_set_install_type_invalid)
840 {
841     InstallRequest requestPrivateUser;
842     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
843     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
844 }
845
846 /*
847  * It is possible for local user to install global application but one needs app_install privileges
848  * By default only global user or root can install global apps (or "User", "System", "System::Privileged"...)
849  */
850 RUNNER_CHILD_TEST(security_manager_25e_unprivileged_install_type_global)
851 {
852     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
853
854     TemporaryTestUser testUser("sm_test_25e_user_name", GUM_USERTYPE_NORMAL);
855     testUser.create();
856
857     AppInstallHelper app("sm_test_25e");
858
859     ScopedProcessLabel spl("_", false);
860     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
861                             "drop_root_privileges failed");
862
863     InstallRequest invalidReq;
864     invalidReq.setAppId(app.getAppId());
865     invalidReq.setPkgId(app.getPkgId());
866     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
867
868     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
869 }
870
871 RUNNER_CHILD_TEST(security_manager_25f_unprivileged_install_type_preloaded)
872 {
873     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
874
875     TemporaryTestUser testUser("sm_test_25f_user_name", GUM_USERTYPE_NORMAL);
876     testUser.create();
877
878     AppInstallHelper app("sm_test_25f");
879
880     ScopedProcessLabel spl("_", false);
881     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
882                             "drop_root_privileges failed");
883     InstallRequest invalidReq;
884     invalidReq.setAppId(app.getAppId());
885     invalidReq.setPkgId(app.getPkgId());
886     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
887     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
888 }
889
890 RUNNER_CHILD_TEST(security_manager_25g_local_user_set_install_type_local)
891 {
892     const PrivilegeVector allowedPrivs = {PRIV_VOLUME_SET, PRIV_SYSTEMMONITOR, PRIV_INTERNET};
893     const PrivilegeVector someDeniedPrivs = {PRIV_PUSH, PRIV_POWER, PRIV_NOTIFICATION};
894
895     TemporaryTestUser testUser("sm_test_25g_user_name", GUM_USERTYPE_NORMAL);
896     testUser.create();
897
898     AppInstallHelperExt app("sm_test_25g", testUser.getUid());
899     app.createPrivateDir();
900     app.setInstallType(SM_APP_INSTALL_LOCAL);
901     app.addPrivileges(allowedPrivs);
902
903     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
904                             "drop_root_privileges failed");
905     {
906         ScopedInstaller appInstall(app);
907         app.checkAfterInstall();
908         app.checkDeniedPrivileges(someDeniedPrivs);
909     }
910     app.checkAfterUninstall();
911 }
912
913 RUNNER_CHILD_TEST(security_manager_25h_local_path_global_install)
914 {
915     TemporaryTestUser testUser("sm_test_25h_user_name", GUM_USERTYPE_NORMAL);
916     testUser.create();
917
918     AppInstallHelper app("sm_test_25h", testUser.getUid());
919     app.createPrivateDir();
920
921     InstallRequest invalidReq;
922     invalidReq.setAppId(app.getAppId());
923     invalidReq.setPkgId(app.getPkgId());
924     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
925     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
926     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
927 }
928
929 RUNNER_CHILD_TEST(security_manager_25i_local_path_preloaded_install)
930 {
931     TemporaryTestUser testUser("sm_test_25i_user_name", GUM_USERTYPE_NORMAL);
932     testUser.create();
933
934     AppInstallHelper app("sm_test_25i", testUser.getUid());
935     app.createPrivateDir();
936
937     InstallRequest invalidReq;
938     invalidReq.setAppId(app.getAppId());
939     invalidReq.setPkgId(app.getPkgId());
940     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
941     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
942     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
943 }
944
945 RUNNER_CHILD_TEST(security_manager_25j_global_path_local_install)
946 {
947     TemporaryTestUser testUser("sm_test_25j_user_name", GUM_USERTYPE_NORMAL);
948     testUser.create();
949
950     AppInstallHelper appLocal("sm_test_25j", testUser.getUid());
951
952     AppInstallHelper appGlobal("sm_test_25");
953     appGlobal.createPrivateDir();
954
955     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
956                             "drop_root_privileges failed");
957
958     InstallRequest invalidReq;
959     invalidReq.setAppId(appLocal.getAppId());
960     invalidReq.setPkgId(appLocal.getPkgId());
961     invalidReq.addPath(appGlobal.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
962     invalidReq.setInstallType(SM_APP_INSTALL_LOCAL);
963
964     Api::install(invalidReq, SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
965 }
966
967 RUNNER_CHILD_TEST(security_manager_26_hybrid_pkg_uninstall_artifacts_check)
968 {
969     TemporaryTestUser testUser("sm_test_26_user_name", GUM_USERTYPE_NORMAL);
970     testUser.create();
971
972     const PrivilegeVector allowedPrivs = {PRIV_WIFIDIRECT, PRIV_TELEPHONY};
973
974     AppInstallHelperExt app1("sm_test_26_1", "sm_test_26", testUser.getUid());
975     app1.addPrivileges(allowedPrivs);
976     app1.setHybrid();
977
978     AppInstallHelperExt app2("sm_test_26_2", "sm_test_26", testUser.getUid());
979     app2.addPrivileges(allowedPrivs);
980     app2.setHybrid();
981
982     {
983         ScopedInstaller appInstall1(app1);
984         ScopedInstaller appInstall2(app2);
985         app1.checkAfterInstall();
986         app2.checkAfterInstall();
987
988     }
989     app1.checkAfterUninstall(false);
990     app2.checkAfterUninstall();
991 }