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