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