90fa13e7ff629a8ecaa4aee7f4d74548a3b9b0e6
[platform/core/test/security-tests.git] / src / security-manager-tests / test_cases.cpp
1 /*
2  * Copyright (c) 2016-2017 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 <scoped_label.h>
39 #include <service_manager.h>
40 #include <sm_api.h>
41 #include <sm_commons.h>
42 #include <sm_request.h>
43 #include <synchronization_pipe.h>
44 #include <temp_test_user.h>
45 #include <tests_common.h>
46 #include <tzplatform.h>
47 #include <uds.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     PolicyConfiguration policy;
148     PolicyConfiguration::PrivGroupMap privGroupMap = policy.getPrivGroupMap();
149
150     RUNNER_ASSERT_MSG(privGroupMap.size() >= 4, "Failed to get policy of a suitable size");
151
152     privileges_t allowedPrivs;
153     privileges_t someDeniedPrivs;
154
155     int counter = 0;
156     for (auto const &it: privGroupMap) {
157         if (counter < 2)
158             allowedPrivs.push_back(it.first);
159         else if (counter < 4)
160             someDeniedPrivs.push_back(it.first);
161         else
162             break;
163         ++counter;
164     }
165
166     AppInstallHelper app("sm_test_02");
167     app.createPrivateDir();
168     app.createPrivateRODir();
169     app.createPublicDir();
170     app.createSharedRODir();
171     app.addPrivileges(allowedPrivs);
172     {
173         ScopedInstaller appInstall(app);
174
175         check_app_after_install(app.getAppId(), app.getPkgId(),
176                                 app.getPrivilegesNames(), someDeniedPrivs);
177
178         check_path(app.getPrivateDir(), generatePathRWLabel(app.getPkgId()));
179         check_path(app.getPrivateRODir(), generatePathROLabel(app.getPkgId()), false);
180         check_path(app.getPublicDir(), getPublicPathLabel());
181         check_path(app.getSharedRODir(), generatePathSharedROLabel(app.getPkgId()));
182     }
183
184     check_app_after_uninstall(app.getAppId(), app.getPkgId(), app.getPrivilegesNames());
185 }
186
187 RUNNER_CHILD_TEST_SMACK(security_manager_03_set_label_from_appid)
188 {
189     std::string expectedSockLabel = "labelExpectedOnlyFromSocket";
190
191     AppInstallHelper app("sm_test_03a");
192     std::string expectedProcLabel = generateProcessLabel(app.getAppId(), app.getPkgId());
193
194     const auto sockaddr = UDSHelpers::makeAbstractAddress("sm_test_03a.socket");
195     int sock = UDSHelpers::createServer(&sockaddr);
196     SockUniquePtr sockPtr(&sock);
197
198     //Set socket label to something different than expeced process label
199     int result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPIN, expectedSockLabel.c_str());
200     RUNNER_ASSERT_ERRNO_MSG(result == 0,
201         "Can't set socket label. Result: " << result);
202     result = smack_set_label_for_file(*sockPtr, XATTR_NAME_SMACKIPOUT, expectedSockLabel.c_str());
203     RUNNER_ASSERT_ERRNO_MSG(result == 0,
204         "Can't set socket label. Result: " << result);
205
206     ScopedInstaller appInstall(app);
207
208     pid_t pid = fork();
209     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "Fork failed");
210     if (pid == 0) { // child
211         Api::setProcessLabel(app.getAppId());
212
213         char *label = nullptr;
214         CStringPtr labelPtr;
215         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPIN, &label);
216         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
217         labelPtr.reset(label);
218         result = expectedSockLabel.compare(label);
219         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
220             expectedProcLabel << " Actual: " << label);
221
222         result = smack_new_label_from_file(*sockPtr, XATTR_NAME_SMACKIPOUT, &label);
223         RUNNER_ASSERT_ERRNO_MSG(result != -1, "smack_new_label_from_file failed: " << label);
224         labelPtr.reset(label);
225         result = expectedSockLabel.compare(label);
226         RUNNER_ASSERT_MSG(result == 0, "Socket label is incorrect. Expected: " <<
227             expectedProcLabel << " Actual: " << label);
228
229         result = smack_new_label_from_self(&label);
230         RUNNER_ASSERT_MSG(result >= 0,
231                 " Error getting current process label");
232         RUNNER_ASSERT_MSG(label != nullptr,
233                 " Process label is not set");
234         labelPtr.reset(label);
235
236         result = expectedProcLabel.compare(label);
237         RUNNER_ASSERT_MSG(result == 0,
238                 " Process label is incorrect. Expected: \"" << expectedProcLabel <<
239                 "\" Actual: \"" << label << "\"");
240     } else { // parent
241         waitPid(pid);
242     }
243 }
244
245 RUNNER_CHILD_TEST(security_manager_04a_app_install_uninstall_by_app_user_for_self)
246 {
247     const std::vector<std::string> allowedPrivs = {
248         "http://tizen.org/privilege/bluetooth",
249         "http://tizen.org/privilege/power"
250     };
251     const std::vector<std::string> someDeniedPrivs = {
252         "http://tizen.org/privilege/display",
253         "http://tizen.org/privilege/nfc"
254     };
255
256     TemporaryTestUser testUser("sm_test_04a_user_name", GUM_USERTYPE_NORMAL);
257     testUser.create();
258
259     AppInstallHelper app("sm_test_04a", testUser.getUid());
260     app.addPrivileges(allowedPrivs);
261
262     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
263                             "drop_root_privileges failed");
264     {
265         ScopedInstaller appInstall(app, false);
266         check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
267                               allowedPrivs, someDeniedPrivs);
268     }
269     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
270                           {}, merge(allowedPrivs, someDeniedPrivs));
271 }
272
273 RUNNER_CHILD_TEST(security_manager_04b_app_install_by_root_for_app_user) {
274     const std::vector<std::string> allowedPrivs = {
275         "http://tizen.org/privilege/internet",
276         "http://tizen.org/privilege/led"
277     };
278     const std::vector<std::string> someDeniedPrivs = {
279         "http://tizen.org/privilege/location",
280         "http://tizen.org/privilege/notification"
281     };
282
283     TemporaryTestUser testUser("sm_test_04b_user_name", GUM_USERTYPE_NORMAL);
284     testUser.create();
285
286     AppInstallHelper app("sm_test_04b", testUser.getUid());
287     app.addPrivileges(allowedPrivs);
288
289     {
290         ScopedInstaller appInstall(app);
291         check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
292                               allowedPrivs, someDeniedPrivs);
293
294         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
295                                 "drop_root_privileges failed");
296     }
297     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
298                           {}, merge(allowedPrivs, someDeniedPrivs));
299 }
300
301 RUNNER_CHILD_TEST(security_manager_05_drop_process_capabilities)
302 {
303     int result;
304     CapsSetsUniquePtr caps_empty(cap_init());
305     auto caps = setCaps("all=eip");
306     Api::dropProcessPrivileges();
307
308     caps.reset(cap_get_proc());
309     RUNNER_ASSERT_MSG(caps, "can't get proc capabilities");
310
311     result = cap_compare(caps.get(), caps_empty.get());
312     RUNNER_ASSERT_MSG(result == 0,
313         "capabilities not dropped. Current: " << cap_to_text(caps.get(), NULL));
314 }
315
316 RUNNER_TEST(security_manager_06_install_app_offline)
317 {
318     ServiceManager("security-manager.service").stopService();
319
320     ServiceManager serviceManager("security-manager.socket");
321     serviceManager.stopService();
322
323     AppInstallHelper app("sm_test_06");
324     ScopedInstaller appInstall(app);
325     // TODO - check if app is installed properly
326     // start service before uninstall, offline mode doesn't support uninstall
327     serviceManager.startService();
328     appInstall.uninstallApp();
329     // TODO - check if app is uninstalled properly
330 }
331
332 RUNNER_TEST(security_manager_07a_user_add_app_install)
333 {
334     const std::vector<std::string> allowedPrivs = {
335         "http://tizen.org/privilege/internet",
336         "http://tizen.org/privilege/led"
337     };
338     const std::vector<std::string> someDeniedPrivs = {
339         "http://tizen.org/privilege/location",
340         "http://tizen.org/privilege/notification"
341     };
342
343     TemporaryTestUser testUser("sm_test_07a_user_name", GUM_USERTYPE_NORMAL);
344     testUser.create();
345
346     AppInstallHelper app("sm_test_07a", testUser.getUid());
347     app.addPrivileges(allowedPrivs);
348
349     InstallRequest req;
350     req.setAppId(app.getAppId());
351     req.setPkgId(app.getPkgId());
352     req.setUid(app.getUID());
353     for (const auto &priv: app.getPrivileges()) {
354         req.addPrivilege(priv);
355     }
356     Api::install(req);
357
358     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
359                           allowedPrivs, someDeniedPrivs);
360
361     testUser.remove();
362
363     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
364                           {}, merge(allowedPrivs, someDeniedPrivs));
365
366     // TODO - check if app is uninstalled
367 }
368
369 RUNNER_TEST(security_manager_07b_user_add_offline)
370 {
371     ServiceManager("security-manager.service").stopService();
372
373     ServiceManager serviceManager("security-manager.socket");
374     serviceManager.stopService();
375
376     TemporaryTestUser testUser("sm_test_07b_user_name", GUM_USERTYPE_NORMAL, true);
377     testUser.create();
378
379     AppInstallHelper app("sm_test_07b", testUser.getUid());
380     ScopedInstaller appInstall(app);
381
382     serviceManager.startService();
383     check_app_after_install(app.getAppId(), app.getPkgId());
384
385     testUser.remove();
386     check_app_after_uninstall(app.getAppId(), app.getPkgId());
387 }
388
389 RUNNER_TEST(security_manager_08_user_double_add_double_remove)
390 {
391     std::vector<std::string> somePrivs = {
392         "http://tizen.org/privilege/internet", "http://tizen.org/privilege/led",
393         "http://tizen.org/privilege/location", "http://tizen.org/privilege/notification"
394     };
395     // gumd
396     TemporaryTestUser testUser("sm_test_08_user_name", GUM_USERTYPE_NORMAL);
397     testUser.create();
398
399     // security-manager
400     UserRequest addUserRequest;
401     addUserRequest.setUid(testUser.getUid());
402     addUserRequest.setUserType(SM_USER_TYPE_NORMAL);
403     Api::addUser(addUserRequest);
404
405     AppInstallHelper app("sm_test_08", testUser.getUid());
406     ScopedInstaller appInstall(app);
407
408     check_app_after_install(app.getAppId(), app.getPkgId());
409     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(), {}, somePrivs);
410
411     // gumd
412     testUser.remove();
413
414     check_app_after_uninstall(app.getAppId(), app.getPkgId());
415     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(), {}, somePrivs);
416
417     // security-manager
418     UserRequest deleteUserRequest;
419     deleteUserRequest.setUid(testUser.getUid());
420     Api::deleteUser(deleteUserRequest);
421 }
422
423 RUNNER_TEST(security_manager_09_app_install_constraint_check)
424 {
425     auto install = [](const TemporaryTestUser& user,
426                       const char *pkgId,
427                       const char *appId,
428                       const char *version,
429                       const char *author,
430                       bool isHybrid,
431                       enum lib_retcode expected,
432                       bool uninstall = true)
433     {
434         InstallRequest request;
435         request.setAppId(appId);
436         request.setPkgId(pkgId);
437         request.setAppTizenVersion(version);
438         request.setAuthorId(author);
439         request.setUid(user.getUid());
440         if (isHybrid)
441             request.setHybrid();
442         Api::install(request, expected);
443
444         if(expected == SECURITY_MANAGER_SUCCESS && uninstall) {
445             Api::uninstall(request);
446         }
447     };
448
449     auto update = [](const TemporaryTestUser& user,
450                      const char *pkgId,
451                      const char *appId,
452                      const char *version,
453                      const char *author,
454                      bool isHybrid,
455                      enum lib_retcode expected,
456                      bool uninstall = true)
457     {
458         InstallRequest request;
459         request.setAppId(appId);
460         request.setPkgId(pkgId);
461         request.setAppTizenVersion(version);
462         request.setAuthorId(author);
463         request.setUid(user.getUid());
464         if (isHybrid)
465             request.setHybrid();
466         Api::update(request, expected);
467
468         if(expected == SECURITY_MANAGER_SUCCESS && uninstall) {
469             Api::uninstall(request);
470         }
471     };
472
473     std::array<TemporaryTestUser, 2> users{
474         TemporaryTestUser{"sm_test_09_user_name_0", GUM_USERTYPE_NORMAL, false},
475         TemporaryTestUser{"sm_test_09_user_name_1", GUM_USERTYPE_NORMAL, false}
476     };
477
478     for(auto& gu : users)
479         gu.create();
480
481     const char *const pkgId[] =   {"sm_test_09_pkg_id_0",  "sm_test_09_pkg_id_1"};
482     const char *const appId[] =   {"sm_test_09_app_id_0",  "sm_test_09_app_id_1"};
483     const char *const version[] = {"sm_test_09_version_0", "sm_test_09_version_1"};
484     const char *const author[] =  {"sm_test_09_author_0",  "sm_test_09_author_1"};
485     bool hybrid[] = {false, true};
486
487     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid
488     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS, false);
489     // uid_1, pkg_0, app_0, version_0, author_0, not hybrid -> ok (different uid)
490     install(users[1], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS);
491     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> ok for update (different hybrid setting)
492     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_ERROR_INPUT_PARAM);
493     update(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_SUCCESS, false);
494     // uid_0, pkg_0, app_1, version_0, author_0, hybrid -> ok (new app id)
495     install(users[0], pkgId[0], appId[1], version[0], author[0], hybrid[1], SECURITY_MANAGER_SUCCESS, false);
496     // uid_1, pkg_0, app_0, version_0, author_0, hybrid -> ok (different hybrid setting)
497     install(users[1], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_SUCCESS, false);
498     // uid_1, pkg_0, app_0, version_0, author_1, not hybrid -> fail (author of app_0 must be the same)
499     install(users[1], pkgId[0], appId[0], version[0], author[1], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
500     // uid_1, pkg_0, app_0, version_1, author_0, not hybrid -> ok (version upgrade and different hybrid setting)
501     install(users[1], pkgId[0], appId[0], version[1], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
502     update(users[1], pkgId[0], appId[0], version[1], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS);
503     // uid_1, pkg_1, app_0, version_0, author_0, not hybrid -> fail (pkg of app_0 must be the same)
504     install(users[1], pkgId[1], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
505     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> ok (the same app again)
506     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS, false);
507     // uid_0, pkg_1, app_0, version_0, author_0, not hybrid -> fail (app_name + uid must be unique)
508     install(users[0], pkgId[1], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
509     // uid_0, pkg_0, app_0, version_0, author_1, not hybrid -> fail (app_name + uid must be unique)
510     install(users[0], pkgId[0], appId[0], version[0], author[1], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
511 }
512
513 RUNNER_CHILD_TEST(security_manager_10_app_has_privilege)
514 {
515     const std::vector<std::string> allowedPrivs = {
516         "http://tizen.org/privilege/wifidirect",
517         "http://tizen.org/privilege/telephony"
518     };
519     const std::vector<std::string> someDeniedPrivs = {
520         "http://tizen.org/privilege/vpnservice",
521         "http://tizen.org/privilege/notification"
522     };
523     AppInstallHelper app("sm_test_10");
524     app.addPrivileges(allowedPrivs);
525     ScopedInstaller appInstall(app);
526
527     sm_app_has_privileges(app, allowedPrivs, 1);
528     // FIXME - all other existing privileges should be checked
529     sm_app_has_privileges(app, someDeniedPrivs, 0);
530 }
531
532 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_POLICY)
533
534 RUNNER_TEST(security_manager_20_user_cynara_policy)
535 {
536     // FIXME - whitebox - cynara
537     const char *const MAIN_BUCKET = "MAIN";
538     const char *const MANIFESTS_GLOBAL_BUCKET = "MANIFESTS_GLOBAL";
539     const char *const MANIFESTS_LOCAL_BUCKET = "MANIFESTS_LOCAL";
540     const char *const ADMIN_BUCKET = "ADMIN";
541     const char *const USER_TYPE_NORMAL_BUCKET = "USER_TYPE_NORMAL";
542     CynaraTestAdmin::Admin admin;
543
544     TemporaryTestUser user("sm_test_20_user_name", GUM_USERTYPE_NORMAL, false);
545     user.create();
546     std::string uid_string = user.getUidString();
547
548     CynaraTestAdmin::CynaraPoliciesContainer nonemptyContainer;
549     nonemptyContainer.add(MAIN_BUCKET,CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, CYNARA_ADMIN_BUCKET, USER_TYPE_NORMAL_BUCKET);
550     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, nonemptyContainer,CYNARA_API_SUCCESS);
551
552     user.remove();
553     CynaraTestAdmin::CynaraPoliciesContainer emptyContainer;
554
555     admin.listPolicies(MAIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
556     admin.listPolicies(MANIFESTS_GLOBAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
557     admin.listPolicies(MANIFESTS_LOCAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
558     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
559     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
560 }
561
562 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
563 {
564     const privileges_t adminRequiredPrivs = {
565         "http://tizen.org/privilege/notexist",
566         "http://tizen.org/privilege/internal/usermanagement"
567     };
568     const privileges_t manifestPrivs = {
569          "http://tizen.org/privilege/internet",
570          "http://tizen.org/privilege/datasharing"
571     };
572     const privileges_t allowedPrivsAfterChange = {"http://tizen.org/privilege/datasharing"};
573     const privileges_t deniedPrivsAfterChange = {"http://tizen.org/privilege/internet"};
574     TemporaryTestUser adminUser("sm_test_21_admin_user_name", GUM_USERTYPE_ADMIN, false);
575     TemporaryTestUser normalUser("sm_test_21_normal_user_name", GUM_USERTYPE_NORMAL, false);
576
577     adminUser.create();
578     normalUser.create();
579     std::string childUidStr = normalUser.getUidString();
580
581     AppInstallHelper adminApp("sm_test_21_admin", adminUser.getUid());
582     adminApp.addPrivileges(adminRequiredPrivs);
583     ScopedInstaller adminAppInstall(adminApp);
584
585     AppInstallHelper normalApp("sm_test_21_normal", normalUser.getUid());
586     normalApp.addPrivileges(manifestPrivs);
587     ScopedInstaller normalAppInstall(normalApp);
588
589     check_app_permissions(normalApp.getAppId(), normalApp.getPkgId(), childUidStr,
590                           manifestPrivs, {});
591
592     pid_t pid = fork();
593     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
594     if (pid != 0) { //parent process
595         waitPid(pid);
596         check_app_permissions(normalApp.getAppId(), normalApp.getPkgId(), childUidStr,
597                               allowedPrivsAfterChange, deniedPrivsAfterChange);
598     } else {
599         Api::setProcessLabel(adminApp.getAppId());
600         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(),adminUser.getGid()) == 0,
601                                 "drop_root_privileges failed");
602
603         PolicyRequest addPolicyReq;
604         for (auto &deniedPriv : deniedPrivsAfterChange) {
605             PolicyEntry entry(SECURITY_MANAGER_ANY, normalUser.getUidString(), deniedPriv);
606             entry.setMaxLevel("Deny");
607             addPolicyReq.addEntry(entry);
608         }
609         Api::sendPolicy(addPolicyReq);
610         exit(0);
611     }
612 }
613
614 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CMD)
615
616 RUNNER_TEST(security_manager_22_security_manager_cmd_install)
617 {
618     int ret;
619     const int SUCCESS = 0;
620     const int FAILURE = 256;
621     const std::string app_id = "sm_test_22_app_id";
622     const std::string pkg_id = "sm_test_22_pkg_id";
623     const std::string username("sm_test_22_user_name");
624
625     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL);
626     user.create();
627
628     const std::string path1 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p1";
629     const std::string path2 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p2";
630     const std::string pkgopt = " --pkg=" + pkg_id;
631     const std::string appopt = " --app=" + app_id;
632     const std::string uidopt = " --uid=" + user.getUidString();
633
634     mktreeSafe(path1.c_str(), 0);
635     mktreeSafe(path2.c_str(), 0);
636
637     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
638
639     struct operation {
640         std::string command;
641         int expected_result;
642     };
643     std::vector<struct operation> operations = {
644             {"security-manager-cmd", FAILURE},//no option
645             {"security-manager-cmd --blah", FAILURE},//blah option is not known
646             {"security-manager-cmd --help", SUCCESS},
647             {"security-manager-cmd --install", FAILURE},//no params
648             {"security-manager-cmd -i", FAILURE},//no params
649             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
650             {installcmd, SUCCESS},
651             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
652             {installcmd + " --path " + path1 + " rw", SUCCESS},
653             {installcmd + " --path " + path1, FAILURE},//no path type
654             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
655             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
656             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
657     };
658
659     for (auto &op : operations) {
660         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
661         RUNNER_ASSERT_MSG(ret == op.expected_result,
662                 "Unexpected result for command '" << op.command <<"': "
663                 << ret << " Expected was: "<< op.expected_result);
664     }
665 }
666
667 RUNNER_TEST(security_manager_23_security_manager_cmd_users)
668 {
669     const int SUCCESS = 0;
670     const int FAILURE = 256;
671     TemporaryTestUser user("sm_test_23_user_name", GUM_USERTYPE_NORMAL, false);
672     user.create();
673     const std::string uidopt = " --uid=" + user.getUidString();
674
675     struct operation {
676         std::string command;
677         int expected_result;
678     };
679     std::vector<struct operation> operations = {
680             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
681             {"security-manager-cmd -m", FAILURE},//no params
682             {"security-manager-cmd -mr", FAILURE},//no uid
683             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
684             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
685             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
686             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
687             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
688             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
689             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
690             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
691     };
692
693     for (auto &op : operations) {
694         int ret = system((op.command + " 1>/dev/null 2>&1").c_str());
695         RUNNER_ASSERT_MSG(ret == op.expected_result,
696                 "Unexpected result for command '" << op.command <<"': "
697                 << ret << " Expected was: "<< op.expected_result);
698     }
699 }
700
701 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_GROUPS)
702
703 RUNNER_TEST(security_manager_24_groups_get)
704 {
705     PolicyConfiguration pc;
706     gid_t * c_groups;
707     size_t count = 0;
708
709     Api::getSecurityManagerGroups(&c_groups, &count);
710     std::unique_ptr<gid_t, decltype(free)*> groupsPtr(c_groups, free);
711
712     auto policyGroups = pc.getGid();
713     RUNNER_ASSERT_MSG(count == policyGroups.size(), "security_manager_groups_get should set count to: "
714                       << policyGroups.size() << " but count is: " << count);
715
716     for (const auto &group : policyGroups) {
717         bool found = false;
718         for (size_t i = 0; i < count; ++i) {
719             if (group == c_groups[i]) {
720                 found = true;
721                 break;
722             }
723         }
724         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
725     }
726 }
727
728 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
729
730 RUNNER_TEST(security_manager_25a_global_user_set_install_type_global)
731 {
732     AppInstallHelper app("sm_test_25a");
733     app.setInstallType(SM_APP_INSTALL_GLOBAL);
734     {
735         ScopedInstaller appInstall(app);
736
737         check_app_after_install(app.getAppId(), app.getPkgId());
738     }
739
740     // Check records in the security-manager database
741     check_app_after_uninstall(app.getAppId(), app.getPkgId());
742 }
743
744 RUNNER_TEST(security_manager_25b_global_user_set_install_type_local)
745 {
746     AppInstallHelper app("sm_test_25b");
747
748     InstallRequest requestInst;
749     requestInst.setAppId(app.getAppId());
750     requestInst.setPkgId(app.getPkgId());
751     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
752
753     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
754 }
755
756 RUNNER_TEST(security_manager_25c_global_user_set_install_type_preloaded)
757 {
758     AppInstallHelper app("sm_test_25c");
759     app.setInstallType(SM_APP_INSTALL_PRELOADED);
760     {
761         ScopedInstaller appInstall(app);
762         check_app_after_install(app.getAppId(), app.getPkgId());
763     }
764     check_app_after_uninstall(app.getAppId(), app.getPkgId());
765 }
766
767 RUNNER_TEST(security_manager_25d_local_user_set_install_type_invalid)
768 {
769     InstallRequest requestPrivateUser;
770     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
771     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
772 }
773
774 /*
775  * It is possible for local user to install global application but one needs app_install privileges
776  * By default only global user or root can install global apps (or "User", "System", "System::Privileged"...)
777  */
778 RUNNER_CHILD_TEST(security_manager_25e_unprivileged_install_type_global)
779 {
780     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
781
782     TemporaryTestUser testUser("sm_test_25e_user_name", GUM_USERTYPE_NORMAL);
783     testUser.create();
784
785     AppInstallHelper app("sm_test_25e");
786
787     change_label("_");
788     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
789                             "drop_root_privileges failed");
790
791     InstallRequest invalidReq;
792     invalidReq.setAppId(app.getAppId());
793     invalidReq.setPkgId(app.getPkgId());
794     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
795
796     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
797 }
798
799 RUNNER_CHILD_TEST(security_manager_25f_unprivileged_install_type_preloaded)
800 {
801     RUNNER_IGNORED_MSG("This test is turned off because multiuser feature is not supported by platform correctly");
802
803     TemporaryTestUser testUser("sm_test_25f_user_name", GUM_USERTYPE_NORMAL);
804     testUser.create();
805
806     AppInstallHelper app("sm_test_25f");
807
808     change_label("_");
809     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
810                             "drop_root_privileges failed");
811     InstallRequest invalidReq;
812     invalidReq.setAppId(app.getAppId());
813     invalidReq.setPkgId(app.getPkgId());
814     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
815     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
816 }
817
818 RUNNER_CHILD_TEST(security_manager_25g_local_user_set_install_type_local)
819 {
820     std::vector<std::string> allowedPrivs = {
821         "http://tizen.org/privilege/volume.set",
822         "http://tizen.org/privilege/systemmonitor",
823         "http://tizen.org/privilege/internet"
824     };
825     std::vector<std::string> someDeniedPrivs = {
826         "http://tizen.org/privilege/push",
827         "http://tizen.org/privilege/power",
828         "http://tizen.org/privilege/notification"
829     };
830
831     TemporaryTestUser testUser("sm_test_25g_user_name", GUM_USERTYPE_NORMAL);
832     testUser.create();
833
834     AppInstallHelper app("sm_test_25g", testUser.getUid());
835     app.createPrivateDir();
836     app.setInstallType(SM_APP_INSTALL_LOCAL);
837     app.addPrivileges(allowedPrivs);
838
839     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
840                             "drop_root_privileges failed");
841     {
842         ScopedInstaller appInstall(app);
843         check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
844                               allowedPrivs, someDeniedPrivs);
845
846     }
847     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
848                           {}, merge(allowedPrivs, someDeniedPrivs));
849     // TODO - check if app is properly uninstalled
850 }
851
852 RUNNER_CHILD_TEST(security_manager_25h_local_path_global_install)
853 {
854     TemporaryTestUser testUser("sm_test_25h_user_name", GUM_USERTYPE_NORMAL);
855     testUser.create();
856
857     AppInstallHelper app("sm_test_25h", testUser.getUid());
858     app.createPrivateDir();
859
860     InstallRequest invalidReq;
861     invalidReq.setAppId(app.getAppId());
862     invalidReq.setPkgId(app.getPkgId());
863     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
864     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
865     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
866 }
867
868 RUNNER_CHILD_TEST(security_manager_25i_local_path_preloaded_install)
869 {
870     TemporaryTestUser testUser("sm_test_25i_user_name", GUM_USERTYPE_NORMAL);
871     testUser.create();
872
873     AppInstallHelper app("sm_test_25i", testUser.getUid());
874     app.createPrivateDir();
875
876     InstallRequest invalidReq;
877     invalidReq.setAppId(app.getAppId());
878     invalidReq.setPkgId(app.getPkgId());
879     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
880     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
881     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
882 }
883
884 RUNNER_CHILD_TEST(security_manager_25j_global_path_local_install)
885 {
886     TemporaryTestUser testUser("sm_test_25j_user_name", GUM_USERTYPE_NORMAL);
887     testUser.create();
888
889     AppInstallHelper appLocal("sm_test_25j", testUser.getUid());
890
891     AppInstallHelper appGlobal("sm_test_25");
892     appGlobal.createPrivateDir();
893
894     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
895                             "drop_root_privileges failed");
896
897     InstallRequest invalidReq;
898     invalidReq.setAppId(appLocal.getAppId());
899     invalidReq.setPkgId(appLocal.getPkgId());
900     invalidReq.addPath(appGlobal.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
901     invalidReq.setInstallType(SM_APP_INSTALL_LOCAL);
902
903     Api::install(invalidReq, SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
904 }
905
906 RUNNER_CHILD_TEST(security_manager_26_hybrid_pkg_uninstall_artifacts_check)
907 {
908     TemporaryTestUser testUser("sm_test_26_user_name", GUM_USERTYPE_NORMAL);
909     testUser.create();
910
911     const std::vector<std::string> allowedPrivs = {
912         "http://tizen.org/privilege/wifidirect",
913         "http://tizen.org/privilege/telephony"
914     };
915
916     AppInstallHelper app1("sm_test_26_1", "sm_test_26", testUser.getUid());
917     app1.addPrivileges(allowedPrivs);
918     app1.setHybrid();
919
920     AppInstallHelper app2("sm_test_26_2", "sm_test_26", testUser.getUid());
921     app2.addPrivileges(allowedPrivs);
922     app2.setHybrid();
923
924     {
925         ScopedInstaller appInstall1(app1);
926         ScopedInstaller appInstall2(app2);
927         check_app_permissions(app1.getAppId(), app1.getPkgId(), testUser.getUidString(),
928                               allowedPrivs, {}, app1.getIsHybrid());
929         check_app_permissions(app2.getAppId(), app2.getPkgId(), testUser.getUidString(),
930                               allowedPrivs, {}, app2.getIsHybrid());
931
932     }
933     check_app_permissions(app1.getAppId(), app1.getPkgId(), testUser.getUidString(),
934                           {}, allowedPrivs, app1.getIsHybrid());
935     check_app_permissions(app2.getAppId(), app2.getPkgId(), testUser.getUidString(),
936                           {}, allowedPrivs, app2.getIsHybrid());
937 }