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