SM : Adjust to new path handling
[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     std::vector<TemporaryTestUser> users = {
450             {"sm_test_09_user_name_0", GUM_USERTYPE_NORMAL, false},
451             {"sm_test_09_user_name_1", GUM_USERTYPE_NORMAL, false}
452     };
453
454     for(auto& gu : users)
455         gu.create();
456
457     const char *const pkgId[] =   {"sm_test_09_pkg_id_0",  "sm_test_09_pkg_id_1"};
458     const char *const appId[] =   {"sm_test_09_app_id_0",  "sm_test_09_app_id_1"};
459     const char *const version[] = {"sm_test_09_version_0", "sm_test_09_version_1"};
460     const char *const author[] =  {"sm_test_09_author_0",  "sm_test_09_author_1"};
461     bool hybrid[] = {false, true};
462
463     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid
464     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS, false);
465     // uid_1, pkg_0, app_0, version_0, author_0, not hybrid -> ok (different uid)
466     install(users[1], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS);
467     // uid_0, pkg_0, app_0, version_0, author_0, hybrid -> fail (different hybrid setting)
468     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_ERROR_INPUT_PARAM);
469     // uid_0, pkg_0, app_1, version_0, author_0, hybrid -> fail (different hybrid setting)
470     install(users[0], pkgId[0], appId[1], version[0], author[0], hybrid[1],  SECURITY_MANAGER_ERROR_INPUT_PARAM);
471     // uid_1, pkg_0, app_0, version_0, author_0, hybrid -> fail (different hybrid setting)
472     install(users[1], pkgId[0], appId[0], version[0], author[0], hybrid[1], SECURITY_MANAGER_ERROR_INPUT_PARAM);
473     // uid_1, pkg_0, app_0, version_0, author_1, not hybrid -> fail (author of app_0 must be the same)
474     install(users[1], pkgId[0], appId[0], version[0], author[1], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
475     // uid_1, pkg_0, app_0, version_1, author_0, not hybrid -> ok (version upgrade)
476     install(users[1], pkgId[0], appId[0], version[1], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS);
477     // uid_1, pkg_1, app_0, version_0, author_0, not hybrid -> fail (pkg of app_0 must be the same)
478     install(users[1], pkgId[1], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
479     // uid_0, pkg_0, app_0, version_0, author_0, not hybrid -> ok (the same app again)
480     install(users[0], pkgId[0], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_SUCCESS, false);
481     // uid_0, pkg_1, app_0, version_0, author_0, not hybrid -> fail (app_name + uid must be unique)
482     install(users[0], pkgId[1], appId[0], version[0], author[0], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
483     // uid_0, pkg_0, app_0, version_0, author_1, not hybrid -> fail (app_name + uid must be unique)
484     install(users[0], pkgId[0], appId[0], version[0], author[1], hybrid[0], SECURITY_MANAGER_ERROR_INPUT_PARAM);
485 }
486
487 RUNNER_CHILD_TEST(security_manager_10_app_has_privilege)
488 {
489     const std::vector<std::string> allowedPrivs = {
490         "http://tizen.org/privilege/wifidirect",
491         "http://tizen.org/privilege/telephony"
492     };
493     const std::vector<std::string> someDeniedPrivs = {
494         "http://tizen.org/privilege/vpnservice",
495         "http://tizen.org/privilege/notification"
496     };
497     AppInstallHelper app("sm_test_10");
498     app.addPrivileges(allowedPrivs);
499     ScopedInstaller appInstall(app);
500
501     sm_app_has_privileges(app, allowedPrivs, 1);
502     // FIXME - all other existing privileges should be checked
503     sm_app_has_privileges(app, someDeniedPrivs, 0);
504 }
505
506 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_POLICY)
507
508 RUNNER_TEST(security_manager_20_user_cynara_policy)
509 {
510     // FIXME - whitebox - cynara
511     const char *const MAIN_BUCKET = "MAIN";
512     const char *const MANIFESTS_GLOBAL_BUCKET = "MANIFESTS_GLOBAL";
513     const char *const MANIFESTS_LOCAL_BUCKET = "MANIFESTS_LOCAL";
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_GLOBAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
531     admin.listPolicies(MANIFESTS_LOCAL_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
532     admin.listPolicies(CYNARA_ADMIN_DEFAULT_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
533     admin.listPolicies(ADMIN_BUCKET, CYNARA_ADMIN_WILDCARD, uid_string.c_str(), CYNARA_ADMIN_WILDCARD, emptyContainer, CYNARA_API_SUCCESS);
534 }
535
536 RUNNER_CHILD_TEST(security_manager_21_security_manager_admin_deny_user_priv)
537 {
538     const privileges_t adminRequiredPrivs = {
539         "http://tizen.org/privilege/notexist",
540         "http://tizen.org/privilege/internal/usermanagement"
541     };
542     const privileges_t manifestPrivs = {
543          "http://tizen.org/privilege/internet",
544          "http://tizen.org/privilege/datasharing"
545     };
546     const privileges_t allowedPrivsAfterChange = {"http://tizen.org/privilege/datasharing"};
547     const privileges_t deniedPrivsAfterChange = {"http://tizen.org/privilege/internet"};
548     TemporaryTestUser adminUser("sm_test_21_admin_user_name", GUM_USERTYPE_ADMIN, false);
549     TemporaryTestUser normalUser("sm_test_21_normal_user_name", GUM_USERTYPE_NORMAL, false);
550
551     adminUser.create();
552     normalUser.create();
553     std::string childUidStr = normalUser.getUidString();
554
555     AppInstallHelper adminApp("sm_test_21_admin", adminUser.getUid());
556     adminApp.addPrivileges(adminRequiredPrivs);
557     ScopedInstaller adminAppInstall(adminApp);
558
559     AppInstallHelper normalApp("sm_test_21_normal", normalUser.getUid());
560     normalApp.addPrivileges(manifestPrivs);
561     ScopedInstaller normalAppInstall(normalApp);
562
563     check_app_permissions(normalApp.getAppId(), normalApp.getPkgId(), childUidStr,
564                           manifestPrivs, {});
565
566     pid_t pid = fork();
567     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
568     if (pid != 0) { //parent process
569         waitPid(pid);
570         check_app_permissions(normalApp.getAppId(), normalApp.getPkgId(), childUidStr,
571                               allowedPrivsAfterChange, deniedPrivsAfterChange);
572     } else {
573         Api::setProcessLabel(adminApp.getAppId());
574         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(),adminUser.getGid()) == 0,
575                                 "drop_root_privileges failed");
576
577         PolicyRequest addPolicyReq;
578         for (auto &deniedPriv : deniedPrivsAfterChange) {
579             PolicyEntry entry(SECURITY_MANAGER_ANY, normalUser.getUidString(), deniedPriv);
580             entry.setMaxLevel("Deny");
581             addPolicyReq.addEntry(entry);
582         }
583         Api::sendPolicy(addPolicyReq);
584         exit(0);
585     }
586 }
587
588 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_CMD)
589
590 RUNNER_TEST(security_manager_22_security_manager_cmd_install)
591 {
592     int ret;
593     const int SUCCESS = 0;
594     const int FAILURE = 256;
595     const std::string app_id = "sm_test_22_app_id";
596     const std::string pkg_id = "sm_test_22_pkg_id";
597     const std::string username("sm_test_22_user_name");
598
599     TemporaryTestUser user(username, GUM_USERTYPE_NORMAL);
600     user.create();
601
602     const std::string path1 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p1";
603     const std::string path2 = TzPlatformConfig::appDirPath(user, app_id, pkg_id) + "/p2";
604     const std::string pkgopt = " --pkg=" + pkg_id;
605     const std::string appopt = " --app=" + app_id;
606     const std::string uidopt = " --uid=" + user.getUidString();
607
608     mktreeSafe(path1.c_str(), 0);
609     mktreeSafe(path2.c_str(), 0);
610
611     const std::string installcmd = "security-manager-cmd --install " + appopt + pkgopt + uidopt;
612
613     struct operation {
614         std::string command;
615         int expected_result;
616     };
617     std::vector<struct operation> operations = {
618             {"security-manager-cmd", FAILURE},//no option
619             {"security-manager-cmd --blah", FAILURE},//blah option is not known
620             {"security-manager-cmd --help", SUCCESS},
621             {"security-manager-cmd --install", FAILURE},//no params
622             {"security-manager-cmd -i", FAILURE},//no params
623             {"security-manager-cmd --i --app=app_id_10 --pkg=pkg_id_10", FAILURE},//no uid
624             {installcmd, SUCCESS},
625             {"security-manager-cmd -i -a" + app_id + " -g" + pkg_id + uidopt, SUCCESS},
626             {installcmd + " --path " + path1 + " rw", SUCCESS},
627             {installcmd + " --path " + path1, FAILURE},//no path type
628             {installcmd + " --path " + path1 + " rw" + " --path " + path2 + " ro", SUCCESS},
629             {installcmd + " --path " + path1 + " prie" + " --path " + path2 + " ro", FAILURE},//wrong path type
630             {installcmd + " --path " + path1 + " rw" + " --privilege somepriv --privilege somepriv2" , SUCCESS},
631     };
632
633     for (auto &op : operations) {
634         ret = system((op.command + " 1>/dev/null 2>&1").c_str());
635         RUNNER_ASSERT_MSG(ret == op.expected_result,
636                 "Unexpected result for command '" << op.command <<"': "
637                 << ret << " Expected was: "<< op.expected_result);
638     }
639 }
640
641 RUNNER_TEST(security_manager_23_security_manager_cmd_users)
642 {
643     const int SUCCESS = 0;
644     const int FAILURE = 256;
645     TemporaryTestUser user("sm_test_23_user_name", GUM_USERTYPE_NORMAL, false);
646     user.create();
647     const std::string uidopt = " --uid=" + user.getUidString();
648
649     struct operation {
650         std::string command;
651         int expected_result;
652     };
653     std::vector<struct operation> operations = {
654             {"security-manager-cmd --manage-users=remove", FAILURE},//no params
655             {"security-manager-cmd -m", FAILURE},//no params
656             {"security-manager-cmd -mr", FAILURE},//no uid
657             {"security-manager-cmd -mr --uid" + uidopt, FAILURE},//no uid
658             {"security-manager-cmd -mr --sdfj" + uidopt, FAILURE},//sdfj?
659             {"security-manager-cmd --msdf -u2004" , FAILURE},//sdf?
660             {"security-manager-cmd -mr" + uidopt, SUCCESS},//ok, removed
661             {"security-manager-cmd -mr --blah" + uidopt, FAILURE},//blah
662             {"security-manager-cmd -ma" + uidopt, SUCCESS},//ok, added
663             {"security-manager-cmd -ma --usertype=normal" + uidopt, SUCCESS},//ok, added
664             {"security-manager-cmd -ma --usertype=mal" + uidopt, FAILURE},//ok, added
665     };
666
667     for (auto &op : operations) {
668         int ret = system((op.command + " 1>/dev/null 2>&1").c_str());
669         RUNNER_ASSERT_MSG(ret == op.expected_result,
670                 "Unexpected result for command '" << op.command <<"': "
671                 << ret << " Expected was: "<< op.expected_result);
672     }
673 }
674
675 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_GROUPS)
676
677 RUNNER_TEST(security_manager_24_groups_get)
678 {
679     PolicyConfiguration pc;
680     gid_t * c_groups;
681     size_t count = 0;
682
683     Api::getSecurityManagerGroups(&c_groups, &count);
684     std::unique_ptr<gid_t, decltype(free)*> groupsPtr(c_groups, free);
685
686     auto policyGroups = pc.getGid();
687     RUNNER_ASSERT_MSG(count == policyGroups.size(), "security_manager_groups_get should set count to: "
688                       << policyGroups.size() << " but count is: " << count);
689
690     for (const auto &group : policyGroups) {
691         bool found = false;
692         for (size_t i = 0; i < count; ++i) {
693             if (group == c_groups[i]) {
694                 found = true;
695                 break;
696             }
697         }
698         RUNNER_ASSERT_MSG(found, "PrivilegeGroup: " << group << " was not found");
699     }
700 }
701
702 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_INSTALL_TYPE)
703
704 RUNNER_TEST(security_manager_25a_global_user_set_install_type_global)
705 {
706     AppInstallHelper app("sm_test_25a");
707     app.setInstallType(SM_APP_INSTALL_GLOBAL);
708     {
709         ScopedInstaller appInstall(app);
710
711         check_app_after_install(app.getAppId(), app.getPkgId());
712     }
713
714     // Check records in the security-manager database
715     check_app_after_uninstall(app.getAppId(), app.getPkgId());
716 }
717
718 RUNNER_TEST(security_manager_25b_global_user_set_install_type_local)
719 {
720     AppInstallHelper app("sm_test_25b");
721
722     InstallRequest requestInst;
723     requestInst.setAppId(app.getAppId());
724     requestInst.setPkgId(app.getPkgId());
725     requestInst.setInstallType(SM_APP_INSTALL_LOCAL);
726
727     Api::install(requestInst, (lib_retcode)SECURITY_MANAGER_ERROR_SERVER_ERROR);
728 }
729
730 RUNNER_TEST(security_manager_25c_global_user_set_install_type_preloaded)
731 {
732     AppInstallHelper app("sm_test_25c");
733     app.setInstallType(SM_APP_INSTALL_PRELOADED);
734     {
735         ScopedInstaller appInstall(app);
736         check_app_after_install(app.getAppId(), app.getPkgId());
737     }
738     check_app_after_uninstall(app.getAppId(), app.getPkgId());
739 }
740
741 RUNNER_TEST(security_manager_25d_local_user_set_install_type_invalid)
742 {
743     InstallRequest requestPrivateUser;
744     requestPrivateUser.setInstallType((app_install_type)0, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
745     requestPrivateUser.setInstallType((app_install_type)22, (lib_retcode)SECURITY_MANAGER_ERROR_INPUT_PARAM);
746 }
747
748 /*
749  * It is possible for local user to install global application but one needs app_install privileges
750  * By default only global user or root can install global apps (or "User", "System", "System::Privileged"...)
751  */
752 RUNNER_CHILD_TEST(security_manager_25e_unprivileged_install_type_global)
753 {
754     TemporaryTestUser testUser("sm_test_25e_user_name", GUM_USERTYPE_NORMAL);
755     testUser.create();
756
757     AppInstallHelper app("sm_test_25e");
758
759     change_label("_");
760     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
761                             "drop_root_privileges failed");
762
763     InstallRequest invalidReq;
764     invalidReq.setAppId(app.getAppId());
765     invalidReq.setPkgId(app.getPkgId());
766     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
767
768     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
769 }
770
771 RUNNER_CHILD_TEST(security_manager_25f_unprivileged_install_type_preloaded)
772 {
773     TemporaryTestUser testUser("sm_test_25f_user_name", GUM_USERTYPE_NORMAL);
774     testUser.create();
775
776     AppInstallHelper app("sm_test_25f");
777
778     change_label("_");
779     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
780                             "drop_root_privileges failed");
781     InstallRequest invalidReq;
782     invalidReq.setAppId(app.getAppId());
783     invalidReq.setPkgId(app.getPkgId());
784     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
785     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_AUTHENTICATION_FAILED);
786 }
787
788
789 RUNNER_CHILD_TEST(security_manager_25g_local_user_set_install_type_local)
790 {
791     std::vector<std::string> allowedPrivs = {
792         "http://tizen.org/privilege/volume.set",
793         "http://tizen.org/privilege/systemmonitor",
794         "http://tizen.org/privilege/internet"
795     };
796     std::vector<std::string> someDeniedPrivs = {
797         "http://tizen.org/privilege/push",
798         "http://tizen.org/privilege/power",
799         "http://tizen.org/privilege/notification"
800     };
801
802     TemporaryTestUser testUser("sm_test_25g_user_name", GUM_USERTYPE_NORMAL);
803     testUser.create();
804
805     AppInstallHelper app("sm_test_25g", testUser.getUid());
806     app.createPrivateDir();
807     app.setInstallType(SM_APP_INSTALL_LOCAL);
808     app.addPrivileges(allowedPrivs);
809
810     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
811                             "drop_root_privileges failed");
812     {
813         ScopedInstaller appInstall(app);
814         check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
815                               allowedPrivs, someDeniedPrivs);
816
817     }
818     check_app_permissions(app.getAppId(), app.getPkgId(), testUser.getUidString(),
819                           {}, merge(allowedPrivs, someDeniedPrivs));
820     // TODO - check if app is properly uninstalled
821 }
822
823 RUNNER_CHILD_TEST(security_manager_25h_local_path_global_install)
824 {
825     TemporaryTestUser testUser("sm_test_25h_user_name", GUM_USERTYPE_NORMAL);
826     testUser.create();
827
828     AppInstallHelper app("sm_test_25h", testUser.getUid());
829     app.createPrivateDir();
830
831     InstallRequest invalidReq;
832     invalidReq.setAppId(app.getAppId());
833     invalidReq.setPkgId(app.getPkgId());
834     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
835     invalidReq.setInstallType(SM_APP_INSTALL_GLOBAL);
836     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
837 }
838
839 RUNNER_CHILD_TEST(security_manager_25i_local_path_preloaded_install)
840 {
841     TemporaryTestUser testUser("sm_test_25i_user_name", GUM_USERTYPE_NORMAL);
842     testUser.create();
843
844     AppInstallHelper app("sm_test_25i", testUser.getUid());
845     app.createPrivateDir();
846
847     InstallRequest invalidReq;
848     invalidReq.setAppId(app.getAppId());
849     invalidReq.setPkgId(app.getPkgId());
850     invalidReq.addPath(app.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
851     invalidReq.setInstallType(SM_APP_INSTALL_PRELOADED);
852     Api::install(invalidReq, (lib_retcode)SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
853 }
854
855 RUNNER_CHILD_TEST(security_manager_25j_global_path_local_install)
856 {
857     TemporaryTestUser testUser("sm_test_25j_user_name", GUM_USERTYPE_NORMAL);
858     testUser.create();
859
860     AppInstallHelper appLocal("sm_test_25j", testUser.getUid());
861
862     AppInstallHelper appGlobal("sm_test_25");
863     appGlobal.createPrivateDir();
864
865     RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(testUser.getUid(), testUser.getGid()) == 0,
866                             "drop_root_privileges failed");
867
868     InstallRequest invalidReq;
869     invalidReq.setAppId(appLocal.getAppId());
870     invalidReq.setPkgId(appLocal.getPkgId());
871     invalidReq.addPath(appGlobal.getPrivateDir(), SECURITY_MANAGER_PATH_RW);
872     invalidReq.setInstallType(SM_APP_INSTALL_LOCAL);
873
874     Api::install(invalidReq, SECURITY_MANAGER_ERROR_NOT_PATH_OWNER);
875 }
876