Merge branch 'tizen' into cynara
[platform/core/test/security-tests.git] / src / security-manager-tests / test_cases_privacy_manager.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 #include <algorithm>
18 #include <cstdlib>
19 #include <map>
20 #include <string>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <unordered_set>
24 #include <utility>
25 #include <vector>
26
27 #include <privilege_info.h>
28
29 #include <app_install_helper.h>
30 #include <cynara_test_admin.h>
31 #include <dpl/test/test_runner.h>
32 #include <dpl/test/test_runner_child.h>
33 #include <policy_configuration.h>
34 #include <scoped_installer.h>
35 #include <sm_api.h>
36 #include <sm_commons.h>
37 #include <sm_policy_request.h>
38 #include <sm_request.h>
39 #include <synchronization_pipe.h>
40 #include <temp_test_user.h>
41 #include <tests_common.h>
42
43 using namespace SecurityManagerTest;
44 namespace {
45 struct UserInfo {
46     std::string userName;
47     GumUserType userType;
48 };
49
50 // Privileges required for having permission to self/admin get/set policies.
51 const std::string SELF_PRIVILEGE = "http://tizen.org/privilege/notexist";
52 const std::string ADMIN_PRIVILEGE = "http://tizen.org/privilege/internal/usermanagement";
53
54 typedef std::vector<std::string> Privileges;
55 const std::vector<Privileges> TEST_PRIVILEGES = {
56     {
57         "http://tizen.org/privilege/internet",
58         "http://tizen.org/privilege/display"
59     },
60     {
61         "http://tizen.org/privilege/telephony",
62         "http://tizen.org/privilege/datasharing"
63     },
64     {
65         "http://tizen.org/privilege/content.write",
66         "http://tizen.org/privilege/led",
67         "http://tizen.org/privilege/email"
68     },
69     {
70         "http://tizen.org/privilege/led",
71         "http://tizen.org/privilege/email",
72         "http://tizen.org/privilege/telephony",
73         "http://tizen.org/privilege/datasharing"
74     },
75     {
76         "http://tizen.org/privilege/internet",
77         "http://tizen.org/privilege/display",
78         "http://tizen.org/privilege/led",
79         "http://tizen.org/privilege/email"
80     }
81 };
82
83 const std::vector<Privileges> TEST_PRIVACY_PRIVILEGES = {
84     {
85         "http://tizen.org/privilege/telephony",
86         "http://tizen.org/privilege/led",
87         "http://tizen.org/privilege/callhistory.read", // privacy-related privileges start here
88         "http://tizen.org/privilege/account.read",
89         "http://tizen.org/privilege/healthinfo"
90     },
91     {
92         "http://tizen.org/privilege/telephony",
93         "http://tizen.org/privilege/led",
94         "http://tizen.org/privilege/callhistory.read" // privacy-related privileges start here
95     }
96 };
97
98 bool isPrivilegePrivacy(const std::string &priv) {
99     return (1 == privilege_info_is_privacy(priv.c_str()));
100 }
101
102 int countPrivacyPrivileges(const Privileges &privs) {
103     return std::count_if(privs.begin(), privs.end(), isPrivilegePrivacy);
104 }
105
106 }
107
108 RUNNER_TEST_GROUP_INIT(SECURITY_MANAGER_PRIVACY_MANAGER)
109
110 RUNNER_CHILD_TEST(security_manager_10_privacy_manager_fetch_whole_policy_for_self)
111 {
112     TemporaryTestUser tmpUser("sm_test_10_user_name", GUM_USERTYPE_NORMAL, false);
113     tmpUser.create();
114
115     unsigned expectedPolicyCount = 0;
116     std::map<std::string, AppInstallHelper> appIdToAIH;
117     for (unsigned i = 0; i < TEST_PRIVILEGES.size(); i++) {
118         AppInstallHelper app("sm_test_10_" + std::to_string(i), tmpUser.getUid());
119         app.addPrivileges(TEST_PRIVILEGES[i]);
120         expectedPolicyCount += app.getPrivileges().size();
121         appIdToAIH.emplace(app.getAppId(), std::move(app));
122     }
123
124     AppInstallHelper privManager("sm_test_10_privilege_manager", tmpUser.getUid());
125     std::string privManagerAppId = privManager.getAppId();
126     privManager.addPrivilege(SELF_PRIVILEGE);
127     expectedPolicyCount += privManager.getPrivileges().size();
128     appIdToAIH.emplace(privManager.getAppId(), std::move(privManager));
129
130     std::vector<ScopedInstaller> scopedInstallations;
131     for (const auto &appIdAIH : appIdToAIH) {
132         scopedInstallations.emplace_back(ScopedInstaller(appIdAIH.second));
133     }
134
135     pid_t pid = fork();
136     RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
137     if (pid != 0) { //parent process
138         waitPid(pid);
139     } else { //child process
140         Api::setProcessLabel(privManagerAppId);
141         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(tmpUser.getUid(), tmpUser.getGid()) == 0,
142                                 "drop_root_privileges failed");
143
144         std::vector<PolicyEntry> policyEntries;
145         Api::getPolicy(PolicyEntry(), policyEntries);
146
147         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
148         RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
149                           "Number of policies doesn't match - should be: " << expectedPolicyCount
150                           << " and is " << policyEntries.size());
151
152         for (const auto &policyEntry : policyEntries) {
153             std::string user = policyEntry.getUser();
154             std::string app = policyEntry.getAppId();
155             std::string privilege = policyEntry.getPrivilege();
156
157             RUNNER_ASSERT_MSG(user == tmpUser.getUidString(), "Unexpected user: " << user);
158
159             auto appIt = appIdToAIH.find(app);
160             RUNNER_ASSERT_MSG(appIt != appIdToAIH.end(), "Policy returned unexpected app: " << app);
161
162             AppInstallHelper &aih = appIt->second;
163             auto appPrivileges = aih.getPrivileges();
164             auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
165             RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
166                               "Unexpected privilege " << privilege << " for app " << app);
167         }
168         exit(0);
169     }
170 }
171
172 RUNNER_CHILD_TEST(security_manager_11_privacy_manager_fetch_whole_policy_for_admin_unprivileged)
173 {
174     const std::string normalNameToSwitch = "sm_test_11_user_name_normal";
175     const std::vector<UserInfo> userInfos = {{normalNameToSwitch, GUM_USERTYPE_NORMAL},
176                                              {"sm_test_11_user_name_admin", GUM_USERTYPE_ADMIN}};
177
178     std::map<std::string, TemporaryTestUser> usernameToTTU;
179     // uid + app_id -> AppInstallHelper (different users can have same app_id installed)
180     std::map<std::pair<uid_t,std::string>, AppInstallHelper> userAppIdToAIH;
181     unsigned expectedPolicyCount = 0;
182
183     for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
184         TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
185         user.create();
186
187         for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
188             AppInstallHelper app("sm_test_11_" + std::to_string(p_i), user.getUid());
189             app.addPrivileges(TEST_PRIVILEGES[p_i]);
190             if (user.getUserName() == normalNameToSwitch) // Only entries for this user should be fetched
191                 expectedPolicyCount += app.getPrivileges().size();
192             userAppIdToAIH.emplace(std::make_pair(user.getUid(), app.getAppId()), std::move(app));
193         };
194
195         usernameToTTU.emplace(userInfos[u_i].userName, std::move(user));
196     };
197
198     TemporaryTestUser &normalUserToSwitch = usernameToTTU.at(normalNameToSwitch);
199
200     AppInstallHelper privManager("sm_test_11_priv_manager", normalUserToSwitch.getUid());
201     std::string privManagerAppId = privManager.getAppId();
202     privManager.addPrivilege(SELF_PRIVILEGE);
203     expectedPolicyCount += privManager.getPrivileges().size();
204     userAppIdToAIH.emplace(std::make_pair(normalUserToSwitch.getUid(), privManager.getAppId()),
205                            std::move(privManager));
206
207     std::vector<ScopedInstaller> scopedInstallations;
208     for (const auto &userAppIdAIH : userAppIdToAIH) {
209         scopedInstallations.emplace_back(ScopedInstaller(userAppIdAIH.second));
210     }
211
212     pid_t pid = fork();
213     RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
214     if (pid != 0) { //parent process
215         waitPid(pid);
216     } else { //child process
217         Api::setProcessLabel(privManagerAppId);
218         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(normalUserToSwitch.getUid(),
219                                                      normalUserToSwitch.getGid()) == 0,
220                                 "drop_root_privileges failed");
221
222         std::vector<PolicyEntry> policyEntries;
223         Api::getPolicy(PolicyEntry(), policyEntries);
224
225         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
226         RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
227                           "Number of policies doesn't match - should be: " << expectedPolicyCount
228                           << " and is " << policyEntries.size());
229
230         for (const auto &policyEntry : policyEntries) {
231             // Expect policy only for current process user
232             std::string user = policyEntry.getUser();
233             std::string app = policyEntry.getAppId();
234             std::string privilege = policyEntry.getPrivilege();
235
236             RUNNER_ASSERT_MSG(normalUserToSwitch.getUidString() == user, "Unexpected user: " << user);
237             auto userAppIdToAIHIt = userAppIdToAIH.find(std::make_pair(static_cast<uid_t>(std::stoi(user)), app));
238             RUNNER_ASSERT_MSG(userAppIdToAIHIt != userAppIdToAIH.end(),
239                               "Unknown app " << app << " for user " << user);
240
241             AppInstallHelper &aih = userAppIdToAIHIt->second;
242             auto privs = aih.getPrivileges();
243
244             auto appPrivileges = aih.getPrivileges();
245             auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
246             RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
247                               "Unexpected privilege " << privilege << " for app " << app);
248         }
249         exit(0);
250     }
251 }
252
253 RUNNER_CHILD_TEST(security_manager_12_privacy_manager_fetch_whole_policy_for_admin_privileged)
254 {
255     std::vector<PolicyEntry> oldPolicyVec;
256     Api::getPolicy(PolicyEntry(), oldPolicyVec);
257     std::unordered_set<PolicyEntry> oldPolicySet(oldPolicyVec.begin(), oldPolicyVec.end());
258
259     std::string adminNameToSwitch = "sm_test_12_user_name_admin";
260     const std::vector<UserInfo> userInfos = {{"sm_test_12_user_name_normal",GUM_USERTYPE_NORMAL},
261                                              {adminNameToSwitch, GUM_USERTYPE_ADMIN}};
262
263     std::map<std::string, TemporaryTestUser> usernameToTTU;
264     std::vector<std::string> uidStrings;
265     // uidstring + app_id -> AppInstallHelper
266     std::map<std::pair<uid_t, std::string>, AppInstallHelper> userAppIdToAIH;
267     unsigned expectedPolicyCount = oldPolicyVec.size();
268
269     for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
270         TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
271         user.create();
272         uidStrings.push_back(user.getUidString());
273
274         for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
275             AppInstallHelper app("sm_test_12_" + std::to_string(p_i), user.getUid());
276             // Shift privileges, so same app_id for different users doesn't have same privileges
277             app.addPrivileges(TEST_PRIVILEGES.at((p_i + u_i) % TEST_PRIVILEGES.size()));
278             expectedPolicyCount += app.getPrivileges().size();
279             userAppIdToAIH.emplace(std::make_pair(user.getUid(), app.getAppId()), std::move(app));
280         };
281         usernameToTTU.emplace(user.getUserName(), std::move(user));
282     };
283
284     TemporaryTestUser &adminUserToSwitch = usernameToTTU.at(adminNameToSwitch);
285
286     AppInstallHelper privManager("sm_test_12_priv_manager", adminUserToSwitch.getUid());
287     std::string privManagerAppId = privManager.getAppId();
288     privManager.addPrivilege(SELF_PRIVILEGE);
289     privManager.addPrivilege(ADMIN_PRIVILEGE);
290     expectedPolicyCount += privManager.getPrivileges().size();
291
292     userAppIdToAIH.emplace(std::make_pair(adminUserToSwitch.getUid(), privManager.getAppId()),
293                            std::move(privManager));
294
295     std::vector<ScopedInstaller> scopedInstallations;
296     for (const auto &userAppIdAIH : userAppIdToAIH) {
297         scopedInstallations.emplace_back(ScopedInstaller(userAppIdAIH.second));
298     }
299
300     pid_t pid = fork();
301     RUNNER_ASSERT_ERRNO_MSG(pid != -1, "Fork failed");
302     if (pid != 0) { //parent process
303         waitPid(pid);
304     } else { //child process
305         Api::setProcessLabel(privManagerAppId);
306         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUserToSwitch.getUid(),
307                                                      adminUserToSwitch.getGid()) == 0,
308                                 "drop_root_privileges failed");
309
310         std::vector<PolicyEntry> policyEntries;
311         Api::getPolicy(PolicyEntry(), policyEntries);
312         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
313         RUNNER_ASSERT_MSG(policyEntries.size() == expectedPolicyCount,
314                           "Number of policies doesn't match - should be: " << expectedPolicyCount
315                           << " and is " << policyEntries.size());
316
317         for (const auto &policyEntry : policyEntries) {
318             // Expect policy for all users to be returned
319             if (oldPolicySet.count(policyEntry))
320                 continue;
321             std::string user = policyEntry.getUser();
322             std::string app = policyEntry.getAppId();
323             std::string privilege = policyEntry.getPrivilege();
324
325             auto uidStringIt = std::find(uidStrings.begin(), uidStrings.end(), user);
326             RUNNER_ASSERT_MSG(uidStringIt != uidStrings.end(), "Unexpected user: " << user);
327
328             auto userAppIdToAIHIt = userAppIdToAIH.find(
329                     std::make_pair(static_cast<uid_t>(std::stoi(user)), app));
330             RUNNER_ASSERT_MSG(userAppIdToAIHIt != userAppIdToAIH.end(),
331                               "Unknown app " << app << " for user " << user);
332
333             AppInstallHelper &aih = userAppIdToAIHIt->second;
334             auto privs = aih.getPrivileges();
335
336             auto appPrivileges = aih.getPrivileges();
337             auto privIt = std::find(appPrivileges.begin(), appPrivileges.end(), privilege);
338             RUNNER_ASSERT_MSG(privIt != appPrivileges.end(),
339                               "Unexpected privilege " << privilege << " for app " << app);
340         };
341         exit(0);
342     };
343 }
344
345 RUNNER_CHILD_TEST(security_manager_13_privacy_manager_fetch_policy_after_update_unprivileged)
346 {
347     std::string normalName = "sm_test_13_user_name_normal";
348     std::string adminName = "sm_test_13_user_name_admin";
349     const std::vector<UserInfo> userInfos = {{normalName,GUM_USERTYPE_NORMAL},
350                                              {adminName, GUM_USERTYPE_ADMIN}};
351
352     std::map<std::string, TemporaryTestUser> usernameToTTU;
353     std::map<uid_t, std::vector<AppInstallHelper>> uidToAIHs;
354     unsigned expectedPolicyCount = 0;
355     std::string privManagerAppId;
356
357     for (unsigned int u_i = 0; u_i < userInfos.size(); u_i++) {
358         //Only entries for one of the users will be listed
359         TemporaryTestUser user(userInfos[u_i].userName, userInfos[u_i].userType);
360         user.create();
361
362         for (unsigned int p_i = 0; p_i < TEST_PRIVILEGES.size(); p_i++) {
363             AppInstallHelper app("sm_test_13_" + std::to_string(p_i), user.getUid());
364             // Shift privileges, so same app_id for different user doesn't have same privileges
365             app.addPrivileges(TEST_PRIVILEGES.at((p_i + u_i) % TEST_PRIVILEGES.size()));
366             expectedPolicyCount += app.getPrivileges().size();
367             uidToAIHs[user.getUid()].emplace_back(std::move(app));
368         };
369         AppInstallHelper privManager("sm_test_13_priv_manager", user.getUid());
370         privManagerAppId = privManager.getAppId();
371         privManager.addPrivilege(SELF_PRIVILEGE);
372         expectedPolicyCount += privManager.getPrivileges().size();
373         uidToAIHs[user.getUid()].emplace_back(std::move(privManager));
374
375         usernameToTTU.emplace(user.getUserName(), std::move(user));
376     };
377
378     std::vector<ScopedInstaller> scopedInstallations;
379     for (const auto &userAIHs : uidToAIHs) {
380         for (const auto &aih : userAIHs.second)
381         scopedInstallations.emplace_back(ScopedInstaller(aih));
382     }
383
384     TemporaryTestUser &adminUser = usernameToTTU.at(adminName);
385     TemporaryTestUser &normalUser = usernameToTTU.at(normalName);
386
387     pid_t pid = fork();
388     RUNNER_ASSERT_ERRNO_MSG(pid >=0, "Fork failed");
389     if (pid == 0) { //child #1 process
390         Api::setProcessLabel(privManagerAppId);
391         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(normalUser.getUid(), normalUser.getGid()) == 0,
392                                 "drop_root_privileges failed");
393         auto &app1 = uidToAIHs[normalUser.getUid()][0];
394         auto &app2 = uidToAIHs[normalUser.getUid()][0];
395         PolicyRequest policyRequest;
396         PolicyEntry policyEntry(
397                 app1.getAppId(),
398                 normalUser.getUidString(),
399                 app1.getPrivileges()[0]
400                 );
401         policyEntry.setLevel("Deny");
402
403         policyRequest.addEntry(policyEntry);
404         policyEntry = PolicyEntry(
405                 app2.getAppId(),
406                 normalUser.getUidString(),
407                 app1.getPrivileges()[1]
408                 );
409         policyEntry.setLevel("Deny");
410         policyRequest.addEntry(policyEntry);
411         Api::sendPolicy(policyRequest);
412
413         exit(0);
414     } else {
415         waitPid(pid);
416         pid = fork();
417         RUNNER_ASSERT_ERRNO_MSG(pid >=0, "Fork failed");
418         if (pid == 0) { //child #2 process
419             Api::setProcessLabel(privManagerAppId);
420             // Admin user, but in context of app, which doesn't have usermanagement privilege
421             RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
422                               "drop_root_privileges failed");
423
424             PolicyEntry filter = PolicyEntry(
425                         SECURITY_MANAGER_ANY,
426                         normalUser.getUidString(),
427                         SECURITY_MANAGER_ANY
428                         );
429             std::vector<PolicyEntry> policyEntries;
430             //U2 requests contents of U1 privacy manager - should fail
431             Api::getPolicyForSelf(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
432             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but has "
433                               << policyEntries.size() << " entries");
434
435             filter = PolicyEntry(
436                         SECURITY_MANAGER_ANY,
437                         SECURITY_MANAGER_ANY,
438                         SECURITY_MANAGER_ANY
439                         );
440
441             policyEntries.clear();
442
443             //U2 requests contents of ADMIN bucket - should fail
444             Api::getPolicyForAdmin(filter, policyEntries, SECURITY_MANAGER_ERROR_ACCESS_DENIED);
445             RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Policy is not empty, but has "
446                               << policyEntries.size() << " entries");
447             exit(0);
448         } else {
449             waitPid(pid);
450         }
451     }
452 }
453
454 RUNNER_CHILD_TEST(security_manager_14_privacy_manager_fetch_and_update_policy_for_admin)
455 {
456     TemporaryTestUser adminUserToSwitch("sm_test_14_user_name_admin", GUM_USERTYPE_ADMIN);
457     adminUserToSwitch.create();
458
459     AppInstallHelper privManager("sm_test_14_priv_manager", adminUserToSwitch.getUid());
460     privManager.addPrivilege(ADMIN_PRIVILEGE);
461
462     ScopedInstaller privManagerInstall(privManager);
463
464     pid_t pid = fork();
465     if (pid != 0) {
466         waitPid(pid);
467     } else { //child process
468         Api::setProcessLabel(privManager.getAppId());
469         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUserToSwitch.getUid(),
470                                                      adminUserToSwitch.getGid()) == 0,
471                                 "drop_root_privileges failed");
472
473         PolicyRequest setPolicyRequest;
474         std::vector<PolicyEntry> policyEntries;
475
476         const std::string internetPriv = "http://tizen.org/privilege/internet";
477         const std::string displayPriv = "http://tizen.org/privilege/display";
478
479         PolicyEntry internetPolicyEntry(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, internetPriv);
480         internetPolicyEntry.setMaxLevel("Deny");
481         setPolicyRequest.addEntry(internetPolicyEntry);
482
483         PolicyEntry displayPolicyEntry(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, displayPriv);
484         displayPolicyEntry.setMaxLevel("Deny");
485         setPolicyRequest.addEntry(displayPolicyEntry);
486
487         Api::sendPolicy(setPolicyRequest);
488
489         Api::getPolicyForAdmin(PolicyEntry(), policyEntries);
490         RUNNER_ASSERT_MSG(policyEntries.size() == 2, "Number of policies doesn't match - should be: 2"
491                                                      " and is " << policyEntries.size());
492
493         PolicyRequest delPolicyRequest;
494
495         internetPolicyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
496         delPolicyRequest.addEntry(internetPolicyEntry);
497
498         displayPolicyEntry.setMaxLevel(SECURITY_MANAGER_DELETE);
499         delPolicyRequest.addEntry(displayPolicyEntry);
500
501         Api::sendPolicy(delPolicyRequest);
502
503         policyEntries.clear();
504         Api::getPolicyForAdmin(PolicyEntry(), policyEntries);
505         RUNNER_ASSERT_MSG(policyEntries.size() == 0, "Number of policies doesn't match - should be: 0"
506                                                      " and is " << policyEntries.size());
507         exit(0);
508     };
509 }
510
511 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin)
512 {
513     const std::string updatePriv = "http://tizen.org/privilege/led";
514
515     TemporaryTestUser adminUser("sm_test_15_username", GUM_USERTYPE_ADMIN);
516     adminUser.create();
517
518     AppInstallHelper updatedApp("security_manager_15_update");
519     ScopedInstaller updatedAppInstall(updatedApp);
520
521     AppInstallHelper privManager("security_manager_15_priv_manager", adminUser.getUid());
522     privManager.addPrivilege(ADMIN_PRIVILEGE);
523     ScopedInstaller privManagerInstall(privManager);
524
525     pid_t pid = fork();
526     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
527     if (pid != 0) { //parent process
528         waitPid(pid);
529         CynaraTestAdmin::Admin admin;
530         admin.adminCheck("ADMIN", false, updatedApp.generateAppLabel().c_str(),
531                          adminUser.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_ALLOW,
532                          nullptr);
533     } else {
534         Api::setProcessLabel(privManager.getAppId());
535
536         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
537                                 "drop_root_privileges failed");
538
539         PolicyEntry entry(updatedApp.getAppId(), adminUser.getUidString(), updatePriv);
540         entry.setMaxLevel("Allow");
541         PolicyRequest addPolicyRequest;
542         addPolicyRequest.addEntry(entry);
543         Api::sendPolicy(addPolicyRequest);
544         exit(0);
545     }
546 }
547
548 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_admin_wildcard)
549 {
550     const std::string updatePriv = "http://tizen.org/privilege/led";
551
552     TemporaryTestUser adminUser("sm_test_15_username", GUM_USERTYPE_ADMIN);
553     adminUser.create();
554
555     AppInstallHelper app("security_manager_15");
556     ScopedInstaller appInstall(app);
557
558     AppInstallHelper privManager("security_manager_15_priv_manager", adminUser.getUid());
559     privManager.addPrivilege(ADMIN_PRIVILEGE);
560     ScopedInstaller privManagerInstall(privManager);
561
562     pid_t pid = fork();
563     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
564     if (pid != 0) {
565         waitPid(pid);
566         CynaraTestAdmin::Admin admin;
567         admin.adminCheck("ADMIN", false, app.generateAppLabel().c_str(),
568                          adminUser.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_ALLOW,
569                          nullptr);
570     } else {
571         Api::setProcessLabel(privManager.getAppId());
572         RUNNER_ASSERT_MSG(drop_root_privileges(adminUser.getUid(), adminUser.getGid()) == 0,
573                           "drop_root_privileges failed");
574
575         PolicyEntry entry(SECURITY_MANAGER_ANY, adminUser.getUidString(), updatePriv);
576         entry.setMaxLevel("Allow");
577
578         PolicyRequest addPolicyRequest;
579         addPolicyRequest.addEntry(entry);
580         Api::sendPolicy(addPolicyRequest);
581         exit(0);
582     }
583 }
584
585 RUNNER_CHILD_TEST(security_manager_15_privacy_manager_send_policy_update_for_self)
586 {
587     const std::string updatePriv = "http://tizen.org/privilege/led";
588
589     TemporaryTestUser user("sm_test_15_username", GUM_USERTYPE_NORMAL);
590     user.create();
591
592     AppInstallHelper app("security_manager_15");
593     ScopedInstaller appInstall(app);
594
595     AppInstallHelper privManager("security_manager_15_priv_manager", user.getUid());
596     privManager.addPrivilege(SELF_PRIVILEGE);
597     ScopedInstaller privManagerInstall(privManager);
598
599     pid_t pid = fork();
600     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
601     if (pid != 0) {
602         waitPid(pid);
603         CynaraTestAdmin::Admin admin;
604         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
605                          updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
606     } else {
607         Api::setProcessLabel(privManager.getAppId());
608         RUNNER_ASSERT_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
609                           "drop_root_privileges failed");
610
611         PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
612         entry.setLevel("Allow");
613
614         PolicyRequest addPolicyRequest;
615         addPolicyRequest.addEntry(entry);
616         Api::sendPolicy(addPolicyRequest);
617         exit(0);
618     }
619 }
620
621 RUNNER_CHILD_TEST(security_manager_16_policy_levels_get)
622 {
623     TemporaryTestUser user("sm_test_16_user_name", GUM_USERTYPE_NORMAL);
624     user.create();
625
626     pid_t pid = fork();
627     RUNNER_ASSERT_ERRNO_MSG(pid >= 0, "fork failed");
628     if (pid != 0) {
629         waitPid(pid);
630     } else {
631         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
632                           "drop_root_privileges failed");
633
634         char** levels;
635         size_t count;
636         int ret = security_manager_policy_levels_get(&levels, &count);
637         RUNNER_ASSERT_MSG((lib_retcode)ret == SECURITY_MANAGER_SUCCESS,
638                 "Invlid return code: " << ret);
639         std::unique_ptr<char *, std::function<void(char**)>> descriptionsPtr(levels,
640                 [count](char **levels) { security_manager_policy_levels_free(levels, count);});
641
642         RUNNER_ASSERT_MSG(count >= 2, "Invalid number of policy levels. Should be 3,"
643                                       " instead there is: " << count);
644
645         std::string denyPolicy = std::string(levels[0]);
646         std::string allowPolicy = std::string(levels[count-1]);
647
648         // first should always be Deny
649         RUNNER_ASSERT_MSG(denyPolicy.compare("Deny") == 0,
650                 "Invalid first policy level. Should be Deny, instead there is: " << levels[0]);
651
652         // last should always be Allow
653         RUNNER_ASSERT_MSG(allowPolicy.compare("Allow") == 0,
654                 "Invalid last policy level. Should be Allow, instead there is: " << levels[count-1]);
655         exit(0);
656     }
657 }
658
659 RUNNER_CHILD_TEST(security_manager_17a_privacy_manager_delete_policy_for_self)
660 {
661     const std::string updatePriv = "http://tizen.org/privilege/led";
662
663     TemporaryTestUser user("sm_test_17a_username", GUM_USERTYPE_NORMAL);
664     user.create();
665
666     AppInstallHelper app("security_manager_17a");
667     ScopedInstaller appInstall(app);
668
669     SynchronizationPipe synchPipe;
670     pid_t pid = fork();
671     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
672     if (pid != 0) {
673         synchPipe.claimParentEp();
674
675         synchPipe.wait();
676         CynaraTestAdmin::Admin admin;
677         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
678                          updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
679         synchPipe.post();
680
681         synchPipe.wait();
682         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
683                          updatePriv.c_str(), CYNARA_ADMIN_DENY, nullptr);
684         waitPid(pid);
685     } else {
686         synchPipe.claimChildEp();
687         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
688                                             "drop_root_privileges failed");
689
690         PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
691         entry.setLevel("Allow");
692         PolicyRequest addPolicyRequest;
693         addPolicyRequest.addEntry(entry);
694         Api::sendPolicy(addPolicyRequest);
695         synchPipe.post();
696
697         synchPipe.wait();
698         PolicyEntry deleteEntry(app.getAppId(), user.getUidString(), updatePriv);
699         deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
700         PolicyRequest deletePolicyRequest;
701         deletePolicyRequest.addEntry(deleteEntry);
702         Api::sendPolicy(deletePolicyRequest);
703         synchPipe.post();
704
705         exit(0);
706     }
707 }
708
709 RUNNER_CHILD_TEST(security_manager_17b_privacy_manager_delete_policy_for_self)
710 {
711     const std::string updatePriv = "http://tizen.org/privilege/led";
712
713     TemporaryTestUser user("sm_test_17b_username", GUM_USERTYPE_NORMAL);
714     user.create();
715
716     AppInstallHelper app("security_manager_17b");
717     ScopedInstaller appInstall(app);
718
719     AppInstallHelper privManager("security_manager_17b_priv_manager", user.getUid());
720     privManager.addPrivilege(SELF_PRIVILEGE);
721     ScopedInstaller privManagerInstall(privManager);
722
723     SynchronizationPipe synchPipe;
724     pid_t pid = fork();
725     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
726     if (pid != 0) {
727         synchPipe.claimParentEp();
728         synchPipe.wait();
729         CynaraTestAdmin::Admin admin;
730         admin.adminCheck("", false, app.generateAppLabel().c_str(), user.getUidString().c_str(),
731                          updatePriv.c_str(), CYNARA_ADMIN_ALLOW, nullptr);
732         synchPipe.post();
733
734         synchPipe.wait();
735         admin.adminCheck("", false, app.generateAppLabel().c_str(),
736                          user.getUidString().c_str(), updatePriv.c_str(), CYNARA_ADMIN_DENY, nullptr);
737         waitPid(pid);
738
739     } else {
740         synchPipe.claimChildEp();
741         Api::setProcessLabel(privManager.getAppId());
742         RUNNER_ASSERT_ERRNO_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
743                                 "drop_root_privileges failed");
744
745         PolicyEntry entry(app.getAppId(), user.getUidString(), updatePriv);
746         entry.setLevel("Allow");
747         PolicyRequest addPolicyRequest;
748         addPolicyRequest.addEntry(entry);
749         Api::sendPolicy(addPolicyRequest);
750         synchPipe.post();
751
752         synchPipe.wait();
753         PolicyRequest deletePolicyRequest;
754         PolicyEntry deleteEntry(app.getAppId(), user.getUidString(), updatePriv);
755         deleteEntry.setLevel(SECURITY_MANAGER_DELETE);
756         deletePolicyRequest.addEntry(deleteEntry);
757         Api::sendPolicy(deletePolicyRequest);
758         synchPipe.post();
759         exit(0);
760     }
761 }
762
763 RUNNER_CHILD_TEST(security_manager_17_privacy_manager_fetch_whole_policy_for_self_filtered)
764 {
765     const std::string username("sm_test_17_user_name");
766     std::vector<AppInstallHelper> appHelpers;
767     std::vector<ScopedInstaller> scopedInstallations;
768     std::map<std::string, unsigned> privToCount;
769     unsigned policyCount = 0;
770
771     TemporaryTestUser user(username, static_cast<GumUserType>(GUM_USERTYPE_NORMAL), false);
772     user.create();
773
774     for (unsigned int i = 0; i < TEST_PRIVILEGES.size(); i++) {
775         AppInstallHelper app("sm_test_17_" + std::to_string(i), user.getUid());
776         app.addPrivileges(TEST_PRIVILEGES[i]);
777         policyCount += app.getPrivileges().size();
778
779         appHelpers.emplace_back(std::move(app));
780         for (auto &priv: TEST_PRIVILEGES[i]) {
781             privToCount[priv]++;
782         }
783     }
784
785     AppInstallHelper privManager("sm_test_17_priv_manager", user.getUid());
786     std::string privManagerAppId = privManager.getAppId();
787     privManager.addPrivilege(SELF_PRIVILEGE);
788     privToCount[SELF_PRIVILEGE]++;
789     policyCount += privManager.getPrivileges().size();
790
791     appHelpers.emplace_back(std::move(privManager));
792     for (const auto &app : appHelpers)
793         scopedInstallations.emplace_back(std::move(ScopedInstaller(app)));
794
795     pid_t pid = fork();
796     RUNNER_ASSERT_MSG(pid >= 0, "fork failed");
797     if (pid != 0)//parent process
798     {
799         waitPid(pid);
800     } else {
801         Api::setProcessLabel(privManagerAppId);
802         RUNNER_ASSERT_MSG(drop_root_privileges(user.getUid(), user.getGid()) == 0,
803                           "drop_root_privileges failed");
804
805         for (const auto &privCount : privToCount) {
806             std::vector<PolicyEntry> policyEntries;
807             PolicyEntry filter(SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY, privCount.first);
808             Api::getPolicy(filter, policyEntries);
809             RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
810             RUNNER_ASSERT_MSG(policyEntries.size() == privCount.second,
811                               "Number of policies doesn't match - should be: " << privCount.second
812                                << " and is " << policyEntries.size());
813         }
814
815         for (const auto &app : appHelpers) {
816             std::vector<PolicyEntry> policyEntries;
817             PolicyEntry filter(app.getAppId(), SECURITY_MANAGER_ANY, SECURITY_MANAGER_ANY);
818             Api::getPolicy(filter, policyEntries);
819             RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
820             RUNNER_ASSERT_MSG(policyEntries.size() == app.getPrivileges().size(),
821                               "Number of policies doesn't match - should be: " << app.getPrivileges().size()
822                               << " and is " << policyEntries.size());
823         }
824
825         std::vector<PolicyEntry> policyEntries;
826         PolicyEntry filter(SECURITY_MANAGER_ANY, user.getUidString(), SECURITY_MANAGER_ANY);
827         Api::getPolicy(filter, policyEntries);
828         RUNNER_ASSERT_MSG(policyEntries.size() != 0, "Policy is empty");
829         RUNNER_ASSERT_MSG(policyEntries.size() == policyCount,
830                           "Number of policies doesn't match - should be: " << policyCount
831                           << " and is " << policyEntries.size());
832
833         exit(0);
834     }
835 }
836
837 RUNNER_CHILD_TEST(security_manager_18_privacy_manager_privacy_related_privileges_policy_install_remove)
838 {
839     const std::string askUserDescription = "Ask user";
840     TemporaryTestUser user("sm_test_18_username", GUM_USERTYPE_NORMAL);
841     user.create();
842
843     AppInstallHelper app("sm_test_18", user.getUid());
844     app.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
845
846     PolicyEntry filter (app.getAppId(), user.getUidString(), SECURITY_MANAGER_ANY);
847     std::vector<PolicyEntry> policyEntries;
848     {
849         ScopedInstaller installer(app);
850         unsigned int privacyNum = countPrivacyPrivileges(app.getPrivileges());
851
852         Api::getPolicy(filter, policyEntries);
853
854         RUNNER_ASSERT_MSG(policyEntries.size() == app.getPrivileges().size(),
855             "Number of policy entries doesn't match; should be " << app.getPrivileges().size()
856             << " but is " << policyEntries.size());
857
858         if (PolicyConfiguration::getIsAskuserEnabled() ) {
859             unsigned int privacyActNum = 0;
860             for (auto &entry : policyEntries)
861                 if (isPrivilegePrivacy(entry.getPrivilege())) {
862                     RUNNER_ASSERT_MSG(entry.getCurrentLevel() == askUserDescription,
863                                       "Invalid policy setup; policy should be \"Ask user\" but is "
864                                       << entry.getCurrentLevel());
865                     ++privacyActNum;
866                 }
867             RUNNER_ASSERT_MSG(privacyActNum == privacyNum,
868                               "Should be " << privacyNum << " privacy privileges,"
869                               "but is " << privacyActNum);
870         }
871     }
872
873     policyEntries.clear();
874     Api::getPolicy(filter, policyEntries);
875     RUNNER_ASSERT_MSG(policyEntries.size() == 0,
876                       "After deinstallation, policy entries size should be 0,"
877                       "but is: "  << policyEntries.size());
878 }
879
880 void test_privacy_related_privileges(bool isHybrid) {
881     const std::string askUserDescription = "Ask user";
882     TemporaryTestUser user("sm_test_19_username", GUM_USERTYPE_NORMAL);
883     user.create();
884
885     const std::string pkgId = "sm_test_19_pkg_id";
886
887     AppInstallHelper app1("sm_test_19_app_id_1", pkgId, user.getUid());
888     if (isHybrid)
889         app1.setHybrid();
890     app1.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
891     ScopedInstaller installer1(app1);
892
893     AppInstallHelper app2("sm_test_19_app_id_2", pkgId, user.getUid());
894     if (isHybrid)
895         app2.setHybrid();
896     app2.addPrivileges(TEST_PRIVACY_PRIVILEGES[1]);
897     ScopedInstaller installer2(app2);
898
899     int privacyCount1, privacyCount2;
900     if (!PolicyConfiguration::getIsAskuserEnabled()) {
901         privacyCount1 = 0;
902         privacyCount2 = 0;
903     } else if (isHybrid) {
904         privacyCount1 = countPrivacyPrivileges(app1.getPrivileges());
905         privacyCount2 = countPrivacyPrivileges(app2.getPrivileges());
906     } else {
907         privacyCount1 = privacyCount2 = countPrivacyPrivileges(app2.getPrivileges());
908     }
909
910     std::vector<PolicyEntry> policyEntries;
911     PolicyEntry filter(SECURITY_MANAGER_ANY, user.getUidString(), SECURITY_MANAGER_ANY);
912     Api::getPolicy(filter, policyEntries);
913
914     int privacyAct1 = 0, privacyAct2 = 0;
915     for (auto &entry : policyEntries) {
916         RUNNER_ASSERT_MSG(entry.getAppId() == app1.getAppId() || entry.getAppId() == app2.getAppId(),
917                           "Invalid appId: should be either " << app1.getAppId() << " or "
918                           << app2.getAppId() << " but is " << entry.getAppId());
919         if (PolicyConfiguration::getIsAskuserEnabled() && isPrivilegePrivacy(entry.getPrivilege())) {
920             RUNNER_ASSERT_MSG(entry.getCurrentLevel() == askUserDescription,
921                               "Invalid policy setup; policy should be \"Ask user\" but is "
922                               << entry.getCurrentLevel());
923             if (entry.getAppId() == app1.getAppId())
924                 ++privacyAct1;
925             else
926                 ++privacyAct2;
927         }
928     }
929     RUNNER_ASSERT_MSG(privacyCount1 == privacyAct1, "Should be " << privacyCount1
930                       << " privacy privileges, but is " << privacyAct1);
931     RUNNER_ASSERT_MSG(privacyCount2 == privacyAct2, "Should be " << privacyCount2
932                       << " privacy privileges, but is " << privacyAct2);
933 }
934
935 RUNNER_CHILD_TEST(security_manager_19a_privacy_manager_privacy_related_privileges_policy_hybrid)
936 {
937     test_privacy_related_privileges(true);
938 }
939
940 RUNNER_CHILD_TEST(security_manager_19b_privacy_manager_privacy_related_privileges_policy_no_hybrid)
941 {
942     test_privacy_related_privileges(false);
943 }
944
945 RUNNER_CHILD_TEST(security_manager_20_privacy_manager_privacy_related_privileges_policy_admin_check)
946 {
947     const std::string askUserDescription = "Ask user";
948     TemporaryTestUser user("sm_test_20_username", GUM_USERTYPE_NORMAL);
949     user.create();
950
951     AppInstallHelper app("sm_test_20", user.getUid());
952     app.addPrivileges(TEST_PRIVACY_PRIVILEGES[0]);
953
954     ScopedInstaller installer(app);
955
956     CynaraTestAdmin::Admin admin;
957     int policyType = CYNARA_ADMIN_ALLOW;
958     int privacyPolicyType = -1;
959     if (PolicyConfiguration::getIsAskuserEnabled())
960         admin.getPolicyTypeForDescription(askUserDescription, privacyPolicyType);
961
962     for (auto &priv : app.getPrivileges()) {
963         if (PolicyConfiguration::getIsAskuserEnabled() && isPrivilegePrivacy(priv)) {
964             admin.adminCheck("", true, app.generateAppLabel().c_str(),
965                              user.getUidString().c_str(), priv.c_str(), privacyPolicyType,
966                              nullptr);
967         } else {
968             admin.adminCheck("", true, app.generateAppLabel().c_str(),
969                              user.getUidString().c_str(), priv.c_str(), policyType, nullptr);
970         }
971     }
972 }