Add SM tests covering many apps in single request
[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, generatePathSharedROLabel(pkgId));
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(), generatePathSharedROLabel(app.getPkgId()));
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, false);
569     }
570
571     for (const auto &appId : appIds) {
572         check_app_after_uninstall(appId, pkgId, true);
573     }
574 }
575
576 RUNNER_CHILD_TEST(security_manager_10_app_has_privilege)
577 {
578     const std::vector<std::string> allowedPrivs = {
579         "http://tizen.org/privilege/wifidirect",
580         "http://tizen.org/privilege/telephony"
581     };
582     const std::vector<std::string> someDeniedPrivs = {
583         "http://tizen.org/privilege/vpnservice",
584         "http://tizen.org/privilege/notification"
585     };
586     AppInstallHelper app("sm_test_10");
587     app.addPrivileges(allowedPrivs);
588     ScopedInstaller appInstall(app);
589
590     sm_app_has_privileges(app, allowedPrivs, 1);
591     // FIXME - all other existing privileges should be checked
592     sm_app_has_privileges(app, someDeniedPrivs, 0);
593 }
594
595 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_POLICY)
596
597 RUNNER_TEST(security_manager_20_user_cynara_policy)
598 {
599     // FIXME - whitebox - cynara
600     const char *const MAIN_BUCKET = "MAIN";
601     const char *const MANIFESTS_GLOBAL_BUCKET = "MANIFESTS_GLOBAL";
602     const char *const MANIFESTS_LOCAL_BUCKET = "MANIFESTS_LOCAL";
603     const char *const ADMIN_BUCKET = "ADMIN";
604     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
605     CynaraTestAdmin::Admin admin;
606
607     TemporaryTestUser user("sm_test_20_user_name", GUM_USERTYPE_NORMAL, false);
608     user.create();
609     std::string uid_string = user.getUidString();
610
611     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
612     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
613     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
614
615     user.remove();
616     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
617
618     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
619     admin.listPolicies(MANIFESTS_GLOBAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
620     admin.listPolicies(MANIFESTS_LOCAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
621     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
622     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
623 }
624
625 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
626 {
627     const privileges_t adminRequiredPrivs = {
628         "http://tizen.org/privilege/notexist",
629         "http://tizen.org/privilege/internal/usermanagement"
630     };
631     const privileges_t manifestPrivs = {
632          "http://tizen.org/privilege/internet",
633          "http://tizen.org/privilege/datasharing"
634     };
635     const privileges_t allowedPrivsAfterChange = {"http://tizen.org/privilege/datasharing"};
636     const privileges_t deniedPrivsAfterChange = {"http://tizen.org/privilege/internet"};
637     TemporaryTestUser adminUser("sm_test_21_admin_user_name", GUM_USERTYPE_ADMIN, false);
638     TemporaryTestUser normalUser("sm_test_21_normal_user_name", GUM_USERTYPE_NORMAL, false);
639
640     adminUser.create();
641     normalUser.create();
642     std::string childUidStr = normalUser.getUidString();
643
644     AppInstallHelper adminApp("sm_test_21_admin", adminUser.getUid());
645     adminApp.addPrivileges(adminRequiredPrivs);
646     ScopedInstaller adminAppInstall(adminApp);
647
648     AppInstallHelper normalApp("sm_test_21_normal", normalUser.getUid());
649     normalApp.addPrivileges(manifestPrivs);
650     ScopedInstaller normalAppInstall(normalApp);
651
652     check_app_permissions(normalApp.getAppId(), normalApp.getPkgId(), childUidStr,
653                           manifestPrivs, {});
654
655     pid_t pid = fork();
656     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
657     if (pid != 0) { //parent process
658         waitPid(pid);
659         check_app_permissions(normalApp.getAppId(), normalApp.getPkgId(), childUidStr,
660                               allowedPrivsAfterChange, deniedPrivsAfterChange);
661     } else {
662         Api::setProcessLabel(adminApp.getAppId());
663         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(),adminUser.getGid()) == 0,
664                                 "drop_root_privileges failed");
665
666         PolicyRequest addPolicyReq;
667         for (auto &deniedPriv : deniedPrivsAfterChange) {
668             PolicyEntry entry(SECURITY_MANAGER_ANY, normalUser.getUidString(), deniedPriv);
669             entry.setMaxLevel("Deny");
670             addPolicyReq.addEntry(entry);
671         }
672         Api::sendPolicy(addPolicyReq);
673         exit(0);
674     }
675 }
676
677 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CMD)
678
679 RUNNER_TEST(security_manager_22_security_manager_cmd_install)
680 {
681     int ret;
682     const int SUCCESS = 0;
683     const int FAILURE = 256;
684     const std::string app_id = "sm_test_22_app_id";
685     const std::string pkg_id = "sm_test_22_pkg_id";
686     const std::string username("sm_test_22_user_name");
687
688     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL);
689     user.create();
690
691     const std::string path1 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p1";
692     const std::string path2 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p2";
693     const std::string pkgopt = " --pkg=" + pkg_id;
694     const std::string appopt = " --app=" + app_id;
695     const std::string uidopt = " --uid=" + user.getUidString();
696
697     mktreeSafe(path1.c_str(), 0);
698     mktreeSafe(path2.c_str(), 0);
699
700     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
701
702     struct operation {
703         std::string command;
704         int expected_result;
705     };
706     std::vector<struct operation> operations = {
707             {"security-manager-cmd", FAILURE},//no option
708             {"security-manager-cmd --blah", FAILURE},//blah option is not known
709             {"security-manager-cmd --help", SUCCESS},
710             {"security-manager-cmd --install", FAILURE},//no params
711             {"security-manager-cmd -i", FAILURE},//no params
712             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
713             {installcmd, SUCCESS},
714             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
715             {installcmd + " --path " + path1 + " rw", SUCCESS},
716             {installcmd + " --path " + path1, FAILURE},//no path type
717             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
718             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
719             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
720     };
721
722     for (auto &op : operations) {
723         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
724         RUNNER_ASSERT_MSG(ret == op.expected_result,
725                 "Unexpected result for command '" << op.command <<"': "
726                 << ret << " Expected was: "<< op.expected_result);
727     }
728 }
729
730 RUNNER_TEST(security_manager_23_security_manager_cmd_users)
731 {
732     const int SUCCESS = 0;
733     const int FAILURE = 256;
734     TemporaryTestUser user("sm_test_23_user_name", GUM_USERTYPE_NORMAL, false);
735     user.create();
736     const std::string uidopt = " --uid=" + user.getUidString();
737
738     struct operation {
739         std::string command;
740         int expected_result;
741     };
742     std::vector<struct operation> operations = {
743             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
744             {"security-manager-cmd -m", FAILURE},//no params
745             {"security-manager-cmd -mr", FAILURE},//no uid
746             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
747             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
748             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
749             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
750             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
751             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
752             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
753             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
754     };
755
756     for (auto &op : operations) {
757         int ret = system((op.command + " 1>/dev/null 2>&1").c_str());
758         RUNNER_ASSERT_MSG(ret == op.expected_result,
759                 "Unexpected result for command '" << op.command <<"': "
760                 << ret << " Expected was: "<< op.expected_result);
761     }
762 }
763
764 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_GROUPS)
765
766 RUNNER_TEST(security_manager_24_groups_get)
767 {
768     PolicyConfiguration pc;
769     gid_t * c_groups;
770     size_t count = 0;
771
772     Api::getSecurityManagerGroups(&c_groups, &count);
773     std::unique_ptr<gid_t, decltype(free)*> groupsPtr(c_groups, free);
774
775     auto policyGroups = pc.getGid();
776     RUNNER_ASSERT_MSG(count == policyGroups.size(), "security_manager_groups_get should set count to: "
777                       << policyGroups.size() << " but count is: " << count);
778
779     for (const auto &group : policyGroups) {
780         bool found = false;
781         for (size_t i = 0; i < count; ++i) {
782             if (group == c_groups[i]) {
783                 found = true;
784                 break;
785             }
786         }
787         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
788     }
789 }
790
791 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
792
793 RUNNER_TEST(security_manager_25a_global_user_set_install_type_global)
794 {
795     AppInstallHelper app("sm_test_25a");
796     app.setInstallType(SM_APP_INSTALL_GLOBAL);
797     {
798         ScopedInstaller appInstall(app);
799
800         check_app_after_install(app.getAppId(), app.getPkgId());
801     }
802
803     // Check records in the security-manager database
804     check_app_after_uninstall(app.getAppId(), app.getPkgId());
805 }
806
807 RUNNER_TEST(security_manager_25b_global_user_set_install_type_local)
808 {
809     AppInstallHelper app("sm_test_25b");
810
811     InstallRequest requestInst;
812     requestInst.setAppId(app.getAppId());
813     requestInst.setPkgId(app.getPkgId());
814     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
815
816     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
817 }
818
819 RUNNER_TEST(security_manager_25c_global_user_set_install_type_preloaded)
820 {
821     AppInstallHelper app("sm_test_25c");
822     app.setInstallType(SM_APP_INSTALL_PRELOADED);
823     {
824         ScopedInstaller appInstall(app);
825         check_app_after_install(app.getAppId(), app.getPkgId());
826     }
827     check_app_after_uninstall(app.getAppId(), app.getPkgId());
828 }
829
830 RUNNER_TEST(security_manager_25d_local_user_set_install_type_invalid)
831 {
832     InstallRequest requestPrivateUser;
833     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
834     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
835 }
836
837 /*
838  * It is possible for local user to install global application but one needs app_install privileges
839  * By default only global user or root can install global apps (or "User", "System", "System::Privileged"...)
840  */
841 RUNNER_CHILD_TEST(security_manager_25e_unprivileged_install_type_global)
842 {
843     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
844
845     TemporaryTestUser testUser("sm_test_25e_user_name", GUM_USERTYPE_NORMAL);
846     testUser.create();
847
848     AppInstallHelper app("sm_test_25e");
849
850     ScopedProcessLabel spl("_", false);
851     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
852                             "drop_root_privileges failed");
853
854     InstallRequest invalidReq;
855     invalidReq.setAppId(app.getAppId());
856     invalidReq.setPkgId(app.getPkgId());
857     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
858
859     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
860 }
861
862 RUNNER_CHILD_TEST(security_manager_25f_unprivileged_install_type_preloaded)
863 {
864     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
865
866     TemporaryTestUser testUser("sm_test_25f_user_name", GUM_USERTYPE_NORMAL);
867     testUser.create();
868
869     AppInstallHelper app("sm_test_25f");
870
871     ScopedProcessLabel spl("_", false);
872     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
873                             "drop_root_privileges failed");
874     InstallRequest invalidReq;
875     invalidReq.setAppId(app.getAppId());
876     invalidReq.setPkgId(app.getPkgId());
877     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
878     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
879 }
880
881 RUNNER_CHILD_TEST(security_manager_25g_local_user_set_install_type_local)
882 {
883     std::vector<std::string> allowedPrivs = {
884         "http://tizen.org/privilege/volume.set",
885         "http://tizen.org/privilege/systemmonitor",
886         "http://tizen.org/privilege/internet"
887     };
888     std::vector<std::string> someDeniedPrivs = {
889         "http://tizen.org/privilege/push",
890         "http://tizen.org/privilege/power",
891         "http://tizen.org/privilege/notification"
892     };
893
894     TemporaryTestUser testUser("sm_test_25g_user_name", GUM_USERTYPE_NORMAL);
895     testUser.create();
896
897     AppInstallHelper app("sm_test_25g", testUser.getUid());
898     app.createPrivateDir();
899     app.setInstallType(SM_APP_INSTALL_LOCAL);
900     app.addPrivileges(allowedPrivs);
901
902     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
903                             "drop_root_privileges failed");
904     {
905         ScopedInstaller appInstall(app);
906         check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
907                               allowedPrivs, someDeniedPrivs);
908
909     }
910     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
911                           {}, merge(allowedPrivs, someDeniedPrivs));
912     // TODO - check if app is properly uninstalled
913 }
914
915 RUNNER_CHILD_TEST(security_manager_25h_local_path_global_install)
916 {
917     TemporaryTestUser testUser("sm_test_25h_user_name", GUM_USERTYPE_NORMAL);
918     testUser.create();
919
920     AppInstallHelper app("sm_test_25h", testUser.getUid());
921     app.createPrivateDir();
922
923     InstallRequest invalidReq;
924     invalidReq.setAppId(app.getAppId());
925     invalidReq.setPkgId(app.getPkgId());
926     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
927     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
928     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
929 }
930
931 RUNNER_CHILD_TEST(security_manager_25i_local_path_preloaded_install)
932 {
933     TemporaryTestUser testUser("sm_test_25i_user_name", GUM_USERTYPE_NORMAL);
934     testUser.create();
935
936     AppInstallHelper app("sm_test_25i", testUser.getUid());
937     app.createPrivateDir();
938
939     InstallRequest invalidReq;
940     invalidReq.setAppId(app.getAppId());
941     invalidReq.setPkgId(app.getPkgId());
942     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
943     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
944     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
945 }
946
947 RUNNER_CHILD_TEST(security_manager_25j_global_path_local_install)
948 {
949     TemporaryTestUser testUser("sm_test_25j_user_name", GUM_USERTYPE_NORMAL);
950     testUser.create();
951
952     AppInstallHelper appLocal("sm_test_25j", testUser.getUid());
953
954     AppInstallHelper appGlobal("sm_test_25");
955     appGlobal.createPrivateDir();
956
957     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
958                             "drop_root_privileges failed");
959
960     InstallRequest invalidReq;
961     invalidReq.setAppId(appLocal.getAppId());
962     invalidReq.setPkgId(appLocal.getPkgId());
963     invalidReq.addPath(appGlobal.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
964     invalidReq.setInstallType(SM_APP_INSTALL_LOCAL);
965
966     Api::install(invalidReq, SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
967 }
968
969 RUNNER_CHILD_TEST(security_manager_26_hybrid_pkg_uninstall_artifacts_check)
970 {
971     TemporaryTestUser testUser("sm_test_26_user_name", GUM_USERTYPE_NORMAL);
972     testUser.create();
973
974     const std::vector<std::string> allowedPrivs = {
975         "http://tizen.org/privilege/wifidirect",
976         "http://tizen.org/privilege/telephony"
977     };
978
979     AppInstallHelper app1("sm_test_26_1", "sm_test_26", testUser.getUid());
980     app1.addPrivileges(allowedPrivs);
981     app1.setHybrid();
982
983     AppInstallHelper app2("sm_test_26_2", "sm_test_26", testUser.getUid());
984     app2.addPrivileges(allowedPrivs);
985     app2.setHybrid();
986
987     {
988         ScopedInstaller appInstall1(app1);
989         ScopedInstaller appInstall2(app2);
990         check_app_permissions(app1.getAppId(), app1.getPkgId(), testUser.getUidString(),
991                               allowedPrivs, {}, app1.getIsHybrid());
992         check_app_permissions(app2.getAppId(), app2.getPkgId(), testUser.getUidString(),
993                               allowedPrivs, {}, app2.getIsHybrid());
994
995     }
996     check_app_permissions(app1.getAppId(), app1.getPkgId(), testUser.getUidString(),
997                           {}, allowedPrivs, app1.getIsHybrid());
998     check_app_permissions(app2.getAppId(), app2.getPkgId(), testUser.getUidString(),
999                           {}, allowedPrivs, app2.getIsHybrid());
1000 }