Policy update: server side implementation
[platform/core/security/security-manager.git] / src / common / cynara.cpp
1 /*
2  *  Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Contact: Rafal Krypa <r.krypa@samsung.com>
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License
17  */
18 /*
19  * @file        cynara.cpp
20  * @author      Rafal Krypa <r.krypa@samsung.com>
21  * @brief       Wrapper class for Cynara interface
22  */
23
24 #include <cstring>
25 #include "cynara.h"
26
27 #include <dpl/log/log.h>
28
29 namespace SecurityManager {
30
31 /**
32  * Rules for apps and users are organized into set of buckets stored in Cynara.
33  * Bucket is set of rules (app, uid, privilege) -> (DENY, ALLOW, BUCKET, ...).
34  *  |------------------------|
35  *  |      <<allow>>         |
36  *  |   PRIVACY_MANAGER      |
37  *  |------------------------|
38  *  |  A    U   P      policy|
39  *  |------------------------|
40  *  | app1 uid1 priv1  DENY  |
41  *  |  *   uid2 priv2  DENY  |
42  *  |  * * *      Bucket:MAIN|
43  *  |------------------------|
44  *
45  * For details about buckets see Cynara documentation.
46  *
47  * Security Manager currently defines 8 buckets:
48  * - PRIVACY_MANAGER - first bucket during search (which is actually default bucket
49  *   with empty string as id). If user specifies his preference then required rule
50  *   is created here.
51  * - MAIN            - holds rules denied by manufacturer, redirects to MANIFESTS
52  *   bucket and holds entries for each user pointing to User Type
53  *   specific buckets
54  * - MANIFESTS       - stores rules needed by installed apps (from package
55  *   manifest)
56  * - USER_TYPE_ADMIN
57  * - USER_TYPE_SYSTEM
58  * - USER_TYPE_NORMAL
59  * - USER_TYPE_GUEST - they store privileges from templates for apropriate
60  *   user type. ALLOW rules only.
61  * - ADMIN           - stores custom rules introduced by device administrator.
62  *   Ignored if no matching rule found.
63  *
64  * Below is basic layout of buckets:
65  *
66  *  |------------------------|
67  *  |      <<allow>>         |
68  *  |   PRIVACY_MANAGER      |
69  *  |                        |
70  *  |  * * *      Bucket:MAIN|                         |------------------|
71  *  |------------------------|                         |      <<deny>>    |
72  *             |                                    |->|     MANIFESTS    |
73  *             -----------------                    |  |                  |
74  *                             |                    |  |------------------|
75  *                             V                    |
76  *                     |------------------------|   |
77  *                     |       <<deny>>         |---|
78  *                     |         MAIN           |
79  * |---------------|   |                        |     |-------------------|
80  * |    <<deny>>   |<--| * * *  Bucket:MANIFESTS|---->|      <<deny>>     |
81  * | USER_TYPE_SYST|   |------------------------|     |  USER_TYPE_NORMAL |
82  * |               |        |              |          |                   |
83  * |---------------|        |              |          |-------------------|
84  *        |                 |              |                    |
85  *        |                 V              V                    |
86  *        |      |---------------|      |---------------|       |
87  *        |      |    <<deny>>   |      |    <<deny>>   |       |
88  *        |      |USER_TYPE_GUEST|      |USER_TYPE_ADMIN|       |
89  *        |      |               |      |               |       |
90  *        |      |---------------|      |---------------|       |
91  *        |              |                      |               |
92  *        |              |----             -----|               |
93  *        |                  |             |                    |
94  *        |                  V             V                    |
95  *        |                |------------------|                 |
96  *        |------------->  |     <<none>>     | <---------------|
97  *                         |       ADMIN      |
98  *                         |                  |
99  *                         |------------------|
100  *
101  */
102 CynaraAdmin::BucketsMap CynaraAdmin::Buckets =
103 {
104     { Bucket::PRIVACY_MANAGER, std::string(CYNARA_ADMIN_DEFAULT_BUCKET)},
105     { Bucket::MAIN, std::string("MAIN")},
106     { Bucket::USER_TYPE_ADMIN, std::string("USER_TYPE_ADMIN")},
107     { Bucket::USER_TYPE_NORMAL, std::string("USER_TYPE_NORMAL")},
108     { Bucket::USER_TYPE_GUEST, std::string("USER_TYPE_GUEST") },
109     { Bucket::USER_TYPE_SYSTEM, std::string("USER_TYPE_SYSTEM")},
110     { Bucket::ADMIN, std::string("ADMIN")},
111     { Bucket::MANIFESTS, std::string("MANIFESTS")},
112 };
113
114
115 CynaraAdminPolicy::CynaraAdminPolicy(const std::string &client, const std::string &user,
116         const std::string &privilege, int operation,
117         const std::string &bucket)
118 {
119     this->client = strdup(client.c_str());
120     this->user = strdup(user.c_str());
121     this->privilege = strdup(privilege.c_str());
122     this->bucket = strdup(bucket.c_str());
123
124     if (this->bucket == nullptr || this->client == nullptr ||
125         this->user == nullptr || this->privilege == nullptr) {
126         free(this->bucket);
127         free(this->client);
128         free(this->user);
129         free(this->privilege);
130         ThrowMsg(CynaraException::OutOfMemory,
131                 std::string("Error in CynaraAdminPolicy allocation."));
132     }
133
134     this->result = operation;
135     this->result_extra = nullptr;
136 }
137
138 CynaraAdminPolicy::CynaraAdminPolicy(const std::string &client, const std::string &user,
139     const std::string &privilege, const std::string &goToBucket,
140     const std::string &bucket)
141 {
142     this->bucket = strdup(bucket.c_str());
143     this->client = strdup(client.c_str());
144     this->user = strdup(user.c_str());
145     this->privilege = strdup(privilege.c_str());
146     this->result_extra = strdup(goToBucket.c_str());
147     this->result = CYNARA_ADMIN_BUCKET;
148
149     if (this->bucket == nullptr || this->client == nullptr ||
150         this->user == nullptr || this->privilege == nullptr ||
151         this->result_extra == nullptr) {
152         free(this->bucket);
153         free(this->client);
154         free(this->user);
155         free(this->privilege);
156         free(this->result_extra);
157         ThrowMsg(CynaraException::OutOfMemory,
158                 std::string("Error in CynaraAdminPolicy allocation."));
159     }
160 }
161
162 CynaraAdminPolicy::CynaraAdminPolicy(CynaraAdminPolicy &&that)
163 {
164     bucket = that.bucket;
165     client = that.client;
166     user = that.user;
167     privilege = that.privilege;
168     result_extra = that.result_extra;
169     result = that.result;
170
171     that.bucket = nullptr;
172     that.client = nullptr;
173     that.user = nullptr;
174     that.privilege = nullptr;
175     that.result_extra = nullptr;
176 }
177
178 CynaraAdminPolicy& CynaraAdminPolicy::operator=(CynaraAdminPolicy &&that)
179 {
180     if (this != &that) {
181         bucket = that.bucket;
182         client = that.client;
183         user = that.user;
184         privilege = that.privilege;
185         result_extra = that.result_extra;
186         result = that.result;
187
188         that.bucket = nullptr;
189         that.client = nullptr;
190         that.user = nullptr;
191         that.privilege = nullptr;
192         that.result_extra = nullptr;
193     };
194
195     return *this;
196 }
197
198 CynaraAdminPolicy::~CynaraAdminPolicy()
199 {
200     free(this->bucket);
201     free(this->client);
202     free(this->user);
203     free(this->privilege);
204     free(this->result_extra);
205 }
206
207 static bool checkCynaraError(int result, const std::string &msg)
208 {
209     switch (result) {
210         case CYNARA_API_SUCCESS:
211         case CYNARA_API_ACCESS_ALLOWED:
212             return true;
213         case CYNARA_API_ACCESS_DENIED:
214             return false;
215         case CYNARA_API_OUT_OF_MEMORY:
216             ThrowMsg(CynaraException::OutOfMemory, msg);
217         case CYNARA_API_INVALID_PARAM:
218             ThrowMsg(CynaraException::InvalidParam, msg);
219         case CYNARA_API_SERVICE_NOT_AVAILABLE:
220             ThrowMsg(CynaraException::ServiceNotAvailable, msg);
221         case CYNARA_API_BUCKET_NOT_FOUND:
222             ThrowMsg(CynaraException::BucketNotFound, msg);
223         default:
224             ThrowMsg(CynaraException::UnknownError, msg);
225     }
226 }
227
228 CynaraAdmin::TypeToDescriptionMap CynaraAdmin::TypeToDescription;
229 CynaraAdmin::DescriptionToTypeMap CynaraAdmin::DescriptionToType;
230
231 CynaraAdmin::CynaraAdmin()
232     : m_policyDescriptionsInitialized(false)
233 {
234     checkCynaraError(
235         cynara_admin_initialize(&m_CynaraAdmin),
236         "Cannot connect to Cynara administrative interface.");
237 }
238
239 CynaraAdmin::~CynaraAdmin()
240 {
241     cynara_admin_finish(m_CynaraAdmin);
242 }
243
244 CynaraAdmin &CynaraAdmin::getInstance()
245 {
246     static CynaraAdmin cynaraAdmin;
247     return cynaraAdmin;
248 }
249
250 void CynaraAdmin::SetPolicies(const std::vector<CynaraAdminPolicy> &policies)
251 {
252     std::vector<const struct cynara_admin_policy *> pp_policies(policies.size() + 1);
253
254     LogDebug("Sending " << policies.size() << " policies to Cynara");
255     for (std::size_t i = 0; i < policies.size(); ++i) {
256         pp_policies[i] = static_cast<const struct cynara_admin_policy *>(&policies[i]);
257         LogDebug("policies[" << i << "] = {" <<
258             ".bucket = " << pp_policies[i]->bucket << ", " <<
259             ".client = " << pp_policies[i]->client << ", " <<
260             ".user = " << pp_policies[i]->user << ", " <<
261             ".privilege = " << pp_policies[i]->privilege << ", " <<
262             ".result = " << pp_policies[i]->result << ", " <<
263             ".result_extra = " << pp_policies[i]->result_extra << "}");
264     }
265
266     pp_policies[policies.size()] = nullptr;
267
268     checkCynaraError(
269         cynara_admin_set_policies(m_CynaraAdmin, pp_policies.data()),
270         "Error while updating Cynara policy.");
271 }
272
273 void CynaraAdmin::UpdateAppPolicy(
274     const std::string &label,
275     const std::string &user,
276     const std::vector<std::string> &oldPrivileges,
277     const std::vector<std::string> &newPrivileges)
278 {
279     std::vector<CynaraAdminPolicy> policies;
280
281     // Perform sort-merge join on oldPrivileges and newPrivileges.
282     // Assume that they are already sorted and without duplicates.
283     auto oldIter = oldPrivileges.begin();
284     auto newIter = newPrivileges.begin();
285
286     while (oldIter != oldPrivileges.end() && newIter != newPrivileges.end()) {
287         int compare = oldIter->compare(*newIter);
288         if (compare == 0) {
289             LogDebug("(user = " << user << " label = " << label << ") " <<
290                 "keeping privilege " << *newIter);
291             ++oldIter;
292             ++newIter;
293             continue;
294         } else if (compare < 0) {
295             LogDebug("(user = " << user << " label = " << label << ") " <<
296                 "removing privilege " << *oldIter);
297             policies.push_back(CynaraAdminPolicy(label, user, *oldIter,
298                     static_cast<int>(CynaraAdminPolicy::Operation::Delete),
299                     Buckets.at(Bucket::MANIFESTS)));
300             ++oldIter;
301         } else {
302             LogDebug("(user = " << user << " label = " << label << ") " <<
303                 "adding privilege " << *newIter);
304             policies.push_back(CynaraAdminPolicy(label, user, *newIter,
305                     static_cast<int>(CynaraAdminPolicy::Operation::Allow),
306                     Buckets.at(Bucket::MANIFESTS)));
307             ++newIter;
308         }
309     }
310
311     for (; oldIter != oldPrivileges.end(); ++oldIter) {
312         LogDebug("(user = " << user << " label = " << label << ") " <<
313             "removing privilege " << *oldIter);
314         policies.push_back(CynaraAdminPolicy(label, user, *oldIter,
315                     static_cast<int>(CynaraAdminPolicy::Operation::Delete),
316                     Buckets.at(Bucket::MANIFESTS)));
317     }
318
319     for (; newIter != newPrivileges.end(); ++newIter) {
320         LogDebug("(user = " << user << " label = " << label << ") " <<
321             "adding privilege " << *newIter);
322         policies.push_back(CynaraAdminPolicy(label, user, *newIter,
323                     static_cast<int>(CynaraAdminPolicy::Operation::Allow),
324                     Buckets.at(Bucket::MANIFESTS)));
325     }
326
327     SetPolicies(policies);
328 }
329
330 void CynaraAdmin::UserInit(uid_t uid, security_manager_user_type userType)
331 {
332     Bucket bucket;
333     std::vector<CynaraAdminPolicy> policies;
334
335     switch (userType) {
336         case SM_USER_TYPE_SYSTEM:
337             bucket = Bucket::USER_TYPE_SYSTEM;
338             break;
339         case SM_USER_TYPE_ADMIN:
340             bucket = Bucket::USER_TYPE_ADMIN;
341             break;
342         case SM_USER_TYPE_GUEST:
343             bucket = Bucket::USER_TYPE_GUEST;
344             break;
345         case SM_USER_TYPE_NORMAL:
346             bucket = Bucket::USER_TYPE_NORMAL;
347             break;
348         case SM_USER_TYPE_ANY:
349         case SM_USER_TYPE_NONE:
350         case SM_USER_TYPE_END:
351         default:
352             ThrowMsg(CynaraException::InvalidParam, "User type incorrect");
353     }
354
355     policies.push_back(CynaraAdminPolicy(CYNARA_ADMIN_WILDCARD,
356                                             std::to_string(static_cast<unsigned int>(uid)),
357                                             CYNARA_ADMIN_WILDCARD,
358                                             Buckets.at(bucket),
359                                             Buckets.at(Bucket::MAIN)));
360
361     CynaraAdmin::getInstance().SetPolicies(policies);
362 }
363
364 void CynaraAdmin::UserRemove(uid_t uid)
365 {
366     std::vector<CynaraAdminPolicy> policies;
367     std::string user = std::to_string(static_cast<unsigned int>(uid));
368
369     EmptyBucket(Buckets.at(Bucket::PRIVACY_MANAGER),true,
370             CYNARA_ADMIN_ANY, user, CYNARA_ADMIN_ANY);
371 }
372
373 void CynaraAdmin::ListPolicies(
374     const std::string &bucketName,
375     const std::string &appId,
376     const std::string &user,
377     const std::string &privilege,
378     std::vector<CynaraAdminPolicy> &policies)
379 {
380     struct cynara_admin_policy ** pp_policies = nullptr;
381
382     checkCynaraError(
383         cynara_admin_list_policies(m_CynaraAdmin, bucketName.c_str(), appId.c_str(),
384             user.c_str(), privilege.c_str(), &pp_policies),
385         "Error while getting list of policies for bucket: " + bucketName);
386
387     for (std::size_t i = 0; pp_policies[i] != nullptr; i++) {
388         policies.push_back(std::move(*static_cast<CynaraAdminPolicy*>(pp_policies[i])));
389
390         free(pp_policies[i]);
391     }
392
393     free(pp_policies);
394
395 }
396
397 void CynaraAdmin::EmptyBucket(const std::string &bucketName, bool recursive, const std::string &client,
398     const std::string &user, const std::string &privilege)
399 {
400     checkCynaraError(
401         cynara_admin_erase(m_CynaraAdmin, bucketName.c_str(), static_cast<int>(recursive),
402             client.c_str(), user.c_str(), privilege.c_str()),
403         "Error while emptying bucket: " + bucketName + ", filter (C, U, P): " +
404             client + ", " + user + ", " + privilege);
405 }
406
407 void CynaraAdmin::FetchCynaraPolicyDescriptions(bool forceRefresh)
408 {
409     struct cynara_admin_policy_descr **descriptions = nullptr;
410
411     if (!forceRefresh && m_policyDescriptionsInitialized)
412         return;
413
414     // fetch
415     checkCynaraError(
416         cynara_admin_list_policies_descriptions(m_CynaraAdmin, &descriptions),
417         "Error while getting list of policies descriptions from Cynara.");
418
419     if (descriptions[0] == nullptr) {
420         LogError("Fetching policies levels descriptions from Cynara returned empty list. "
421                 "There should be at least 2 entries - Allow and Deny");
422         return;
423     }
424
425     // reset the state
426     m_policyDescriptionsInitialized = false;
427     DescriptionToType.clear();
428     TypeToDescription.clear();
429
430     // extract strings
431     for (int i = 0; descriptions[i] != nullptr; i++) {
432         std::string descriptionName(descriptions[i]->name);
433
434         DescriptionToType[descriptionName] = descriptions[i]->result;
435         TypeToDescription[descriptions[i]->result] = std::move(descriptionName);
436
437         free(descriptions[i]->name);
438         free(descriptions[i]);
439     }
440
441     free(descriptions);
442
443     m_policyDescriptionsInitialized = true;
444 }
445
446 void CynaraAdmin::ListPoliciesDescriptions(std::vector<std::string> &policiesDescriptions)
447 {
448     FetchCynaraPolicyDescriptions(false);
449
450     for (auto it = TypeToDescription.rbegin(); it != TypeToDescription.rend(); ++it)
451         policiesDescriptions.push_back(it->second);
452 }
453
454 std::string CynaraAdmin::convertToPolicyDescription(const int policyType, bool forceRefresh)
455 {
456     FetchCynaraPolicyDescriptions(forceRefresh);
457
458     return TypeToDescription.at(policyType);
459 }
460
461 int CynaraAdmin::convertToPolicyType(const std::string &policy, bool forceRefresh)
462 {
463     FetchCynaraPolicyDescriptions(forceRefresh);
464
465     return DescriptionToType.at(policy);
466 }
467
468 Cynara::Cynara()
469 {
470     checkCynaraError(
471         cynara_initialize(&m_Cynara, nullptr),
472         "Cannot connect to Cynara policy interface.");
473 }
474
475 Cynara::~Cynara()
476 {
477     cynara_finish(m_Cynara);
478 }
479
480 Cynara &Cynara::getInstance()
481 {
482     static Cynara cynara;
483     return cynara;
484 }
485
486 bool Cynara::check(const std::string &label, const std::string &privilege,
487         const std::string &user, const std::string &session)
488 {
489     return checkCynaraError(
490         cynara_check(m_Cynara,
491             label.c_str(), session.c_str(), user.c_str(), privilege.c_str()),
492         "Cannot check permission with Cynara.");
493 }
494
495 } // namespace SecurityManager