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