Prepare service for database corruption handling
[platform/core/security/cynara.git] / src / service / logic / Logic.cpp
1 /*
2  * Copyright (c) 2014-2015 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  * @file        src/service/logic/Logic.cpp
18  * @author      Lukasz Wojciechowski <l.wojciechow@partner.samsung.com>
19  * @author      Zofia Abramowska <z.abramowska@samsung.com>
20  * @author      Pawel Wieczorek <p.wieczorek2@samsung.com>
21  * @version     1.0
22  * @brief       This file implements main class of logic layer in cynara service
23  */
24
25 #include <csignal>
26 #include <cinttypes>
27 #include <functional>
28 #include <memory>
29 #include <vector>
30
31 #include <log/log.h>
32 #include <common.h>
33 #include <log/log.h>
34 #include <exceptions/BucketNotExistsException.h>
35 #include <exceptions/DatabaseException.h>
36 #include <exceptions/DefaultBucketDeletionException.h>
37 #include <exceptions/DefaultBucketSetNoneException.h>
38 #include <exceptions/InvalidBucketIdException.h>
39 #include <exceptions/PluginErrorException.h>
40 #include <exceptions/PluginNotFoundException.h>
41 #include <exceptions/UnexpectedErrorException.h>
42 #include <exceptions/UnknownPolicyTypeException.h>
43 #include <request/AdminCheckRequest.h>
44 #include <request/AgentActionRequest.h>
45 #include <request/AgentRegisterRequest.h>
46 #include <request/CancelRequest.h>
47 #include <request/CheckRequest.h>
48 #include <request/DescriptionListRequest.h>
49 #include <request/EraseRequest.h>
50 #include <request/InsertOrUpdateBucketRequest.h>
51 #include <request/ListRequest.h>
52 #include <request/RemoveBucketRequest.h>
53 #include <request/RequestContext.h>
54 #include <request/SetPoliciesRequest.h>
55 #include <request/SignalRequest.h>
56 #include <request/SimpleCheckRequest.h>
57 #include <response/AdminCheckResponse.h>
58 #include <response/AgentRegisterResponse.h>
59 #include <response/CancelResponse.h>
60 #include <response/CheckResponse.h>
61 #include <response/CodeResponse.h>
62 #include <response/DescriptionListResponse.h>
63 #include <response/ListResponse.h>
64 #include <response/SimpleCheckResponse.h>
65 #include <types/Policy.h>
66
67 #include <main/Cynara.h>
68 #include <agent/AgentManager.h>
69 #include <sockets/SocketManager.h>
70 #include <storage/Storage.h>
71
72 #include <cynara-plugin.h>
73
74 #include <cynara-agent.h>
75
76 #include "Logic.h"
77
78 namespace Cynara {
79
80 Logic::Logic() : m_dbCorrupted(false) {
81 }
82
83 Logic::~Logic() {
84 }
85
86 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
87     LOGD("Processing signal: [%d]", request->signalNumber());
88
89     switch (request->signalNumber()) {
90     case SIGTERM:
91         LOGI("SIGTERM received!");
92         m_socketManager->mainLoopStop();
93         break;
94     }
95 }
96
97 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
98     PolicyResult result;
99     bool bucketValid = true;
100
101     if (m_dbCorrupted) {
102         bucketValid = false;
103     } else {
104         try {
105             result = m_storage->checkPolicy(request->key(), request->startBucket(),
106                                             request->recursive());
107         } catch (const BucketNotExistsException &ex) {
108             bucketValid = false;
109         }
110     }
111
112     context->returnResponse(context, std::make_shared<AdminCheckResponse>(result, bucketValid,
113                             m_dbCorrupted, request->sequenceNumber()));
114 }
115
116 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
117     AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
118                                                          request->sequenceNumber());
119     if (!talkerPtr) {
120         LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
121              request->sequenceNumber());
122         return;
123     }
124
125     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
126     if (!checkContextPtr) {
127         LOGE("No matching check context for agent talker.");
128         m_agentManager->removeTalker(talkerPtr);
129         return;
130     }
131
132     if (!checkContextPtr->cancelled()) {
133         PluginData data(request->data().begin(), request->data().end());
134         if (request->type() == CYNARA_MSG_TYPE_CANCEL) {
135             // Nothing to do for now
136         } else if (request->type() == CYNARA_MSG_TYPE_ACTION) {
137             update(checkContextPtr->m_key, checkContextPtr->m_checkId, data,
138                    checkContextPtr->m_requestContext, checkContextPtr->m_plugin);
139         } else {
140             LOGE("Invalid response type [%d] in response from agent <%s>",
141                  static_cast<int>(request->type()), talkerPtr->agentType().c_str());
142             // TODO: disconnect agent
143         }
144     }
145
146     m_agentManager->removeTalker(talkerPtr);
147     m_checkRequestManager.removeRequest(checkContextPtr);
148 }
149
150 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
151     auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
152     context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
153                             result, request->sequenceNumber()));
154 }
155
156 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
157     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
158                                                                        request->sequenceNumber());
159     if (!checkContextPtr) {
160         LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
161              request->sequenceNumber());
162         return;
163     }
164
165     if (checkContextPtr->cancelled())
166         return;
167
168     checkContextPtr->cancel();
169     checkContextPtr->m_agentTalker->cancel();
170
171     LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
172     context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
173 }
174
175 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
176     PolicyResult result(PredefinedPolicyType::DENY);
177     if (check(context, request->key(), request->sequenceNumber(), result)) {
178         m_auditLog.log(request->key(), result);
179         context->returnResponse(context, std::make_shared<CheckResponse>(result,
180                                 request->sequenceNumber()));
181     }
182 }
183
184 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
185                   ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
186
187     if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
188         LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
189         return false;
190     }
191
192     result = (m_dbCorrupted ? PredefinedPolicyType::DENY : m_storage->checkPolicy(key));
193
194     switch (result.policyType()) {
195         case PredefinedPolicyType::ALLOW :
196             LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
197             return true;
198         case PredefinedPolicyType::DENY :
199             LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
200             return true;
201     }
202
203     return pluginCheck(context, key, checkId, result);
204 }
205
206 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
207                         ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
208
209     LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
210
211     ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
212     if (!plugin) {
213         LOGE("Plugin not found for policy: [0x%x]", result.policyType());
214         result = PolicyResult(PredefinedPolicyType::DENY);
215         return true;
216     }
217
218     ServicePluginInterfacePtr servicePlugin =
219             std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
220     if (!servicePlugin) {
221         result = PolicyResult(PredefinedPolicyType::DENY);
222         return true;
223     }
224
225     AgentType requiredAgent;
226     PluginData pluginData;
227
228     auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
229                                     key.privilege().toString(), result, requiredAgent, pluginData);
230
231     switch (ret) {
232         case ServicePluginInterface::PluginStatus::ANSWER_READY:
233             return true;
234         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
235                 result = PolicyResult(PredefinedPolicyType::DENY);
236                 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
237                 if (!agentTalker) {
238                     LOGE("Required agent talker for: <%s> could not be created.",
239                          requiredAgent.c_str());
240                     return true;
241                 }
242
243                 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
244                                                          agentTalker)) {
245                     LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
246                          checkId);
247                     m_agentManager->removeTalker(agentTalker);
248                     return true;
249                 }
250                 agentTalker->send(pluginData);
251             }
252             return false;
253         default:
254             result = PolicyResult(PredefinedPolicyType::DENY);
255             return true;
256     }
257 }
258
259 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
260                    const PluginData &agentData, const RequestContextPtr &context,
261                    const ServicePluginInterfacePtr &plugin) {
262
263     LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
264
265     PolicyResult result;
266     bool answerReady = false;
267     auto ret = plugin->update(key.client().toString(), key.user().toString(),
268                               key.privilege().toString(), agentData, result);
269     switch (ret) {
270         case ServicePluginInterface::PluginStatus::SUCCESS:
271             answerReady = true;
272             break;
273         case ServicePluginInterface::PluginStatus::ERROR:
274             result = PolicyResult(PredefinedPolicyType::DENY);
275             answerReady = true;
276             break;
277         default:
278             throw PluginErrorException(key);
279     }
280
281     if (answerReady && context->responseQueue()) {
282         m_auditLog.log(key, result);
283         context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
284         return true;
285     }
286
287     return false;
288 }
289
290 void Logic::execute(RequestContextPtr context, DescriptionListRequestPtr request) {
291     auto descriptions = m_pluginManager->getPolicyDescriptions();
292     descriptions.insert(descriptions.begin(), predefinedPolicyDescr.begin(),
293                         predefinedPolicyDescr.end());
294     context->returnResponse(context, std::make_shared<DescriptionListResponse>(descriptions,
295                             m_dbCorrupted, request->sequenceNumber()));
296 }
297
298 void Logic::execute(RequestContextPtr context, EraseRequestPtr request) {
299     auto code = CodeResponse::Code::OK;
300
301     if (m_dbCorrupted) {
302         code = CodeResponse::Code::DB_CORRUPTED;
303     } else {
304         try {
305             m_storage->erasePolicies(request->startBucket(), request->recursive(), request->filter());
306             onPoliciesChanged();
307         } catch (const DatabaseException &ex) {
308             code = CodeResponse::Code::FAILED;
309         } catch (const BucketNotExistsException &ex) {
310             code = CodeResponse::Code::NO_BUCKET;
311         }
312     }
313
314     context->returnResponse(context, std::make_shared<CodeResponse>(code,
315                             request->sequenceNumber()));
316 }
317
318 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
319     auto code = CodeResponse::Code::OK;
320
321     if (m_dbCorrupted) {
322         code = CodeResponse::Code::DB_CORRUPTED;
323     } else {
324         try {
325             checkSinglePolicyType(request->result().policyType(), true, true);
326             m_storage->addOrUpdateBucket(request->bucketId(), request->result());
327             onPoliciesChanged();
328         } catch (const DatabaseException &ex) {
329             code = CodeResponse::Code::FAILED;
330         } catch (const DefaultBucketSetNoneException &ex) {
331             code = CodeResponse::Code::NOT_ALLOWED;
332         } catch (const InvalidBucketIdException &ex) {
333             code = CodeResponse::Code::NOT_ALLOWED;
334         } catch (const UnknownPolicyTypeException &ex) {
335             code = CodeResponse::Code::NO_POLICY_TYPE;
336         }
337     }
338
339     context->returnResponse(context, std::make_shared<CodeResponse>(code,
340                             request->sequenceNumber()));
341 }
342
343 void Logic::execute(RequestContextPtr context, ListRequestPtr request) {
344     bool bucketValid = true;
345     std::vector<Policy> policies;
346
347     if (m_dbCorrupted) {
348         bucketValid = false;
349     } else {
350         try {
351             policies = m_storage->listPolicies(request->bucket(), request->filter());
352         } catch (const BucketNotExistsException &ex) {
353             bucketValid = false;
354         }
355     }
356
357     context->returnResponse(context, std::make_shared<ListResponse>(policies, bucketValid,
358                             m_dbCorrupted, request->sequenceNumber()));
359 }
360
361 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
362     auto code = CodeResponse::Code::OK;
363
364     if (m_dbCorrupted) {
365         code = CodeResponse::Code::DB_CORRUPTED;
366     } else {
367         try {
368             m_storage->deleteBucket(request->bucketId());
369             onPoliciesChanged();
370         } catch (const DatabaseException &ex) {
371             code = CodeResponse::Code::FAILED;
372         } catch (const BucketNotExistsException &ex) {
373             code = CodeResponse::Code::NO_BUCKET;
374         } catch (const DefaultBucketDeletionException &ex) {
375             code = CodeResponse::Code::NOT_ALLOWED;
376         }
377     }
378
379     context->returnResponse(context, std::make_shared<CodeResponse>(code,
380                             request->sequenceNumber()));
381 }
382
383 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
384     auto code = CodeResponse::Code::OK;
385
386     if (m_dbCorrupted) {
387         code = CodeResponse::Code::DB_CORRUPTED;
388     } else {
389         try {
390             checkPoliciesTypes(request->policiesToBeInsertedOrUpdated(), true, false);
391             m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
392             m_storage->deletePolicies(request->policiesToBeRemoved());
393             onPoliciesChanged();
394         } catch (const DatabaseException &ex) {
395             code = CodeResponse::Code::FAILED;
396         } catch (const BucketNotExistsException &ex) {
397             code = CodeResponse::Code::NO_BUCKET;
398         } catch (const UnknownPolicyTypeException &ex) {
399             code = CodeResponse::Code::NO_POLICY_TYPE;
400         }
401     }
402
403     context->returnResponse(context, std::make_shared<CodeResponse>(code,
404                             request->sequenceNumber()));
405 }
406
407 void Logic::execute(RequestContextPtr context, SimpleCheckRequestPtr request) {
408     int retValue = CYNARA_API_SUCCESS;
409     PolicyResult result;
410     PolicyKey key = request->key();
411     result = m_storage->checkPolicy(key);
412
413     switch (result.policyType()) {
414     case PredefinedPolicyType::ALLOW:
415         LOGD("simple check of policy key <%s> returned ALLOW", key.toString().c_str());
416         break;
417     case PredefinedPolicyType::DENY:
418         LOGD("simple check of policy key <%s> returned DENY", key.toString().c_str());
419         break;
420     default: {
421         ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
422         if (!plugin) {
423             LOGE("Plugin not found for policy: [0x%x]", result.policyType());
424             result = PolicyResult(PredefinedPolicyType::DENY);
425             retValue = CYNARA_API_SUCCESS;
426             break;
427         }
428
429         ServicePluginInterfacePtr servicePlugin =
430                 std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
431         if (!servicePlugin) {
432             LOGE("Couldn't cast plugin pointer to ServicePluginInterface");
433             result = PolicyResult(PredefinedPolicyType::DENY);
434             retValue = CYNARA_API_SUCCESS;
435             break;
436         }
437
438         AgentType requiredAgent;
439         PluginData pluginData;
440         auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
441                                         key.privilege().toString(), result, requiredAgent,
442                                         pluginData);
443         switch (ret) {
444         case ServicePluginInterface::PluginStatus::ANSWER_READY:
445             LOGD("simple check of policy key <%s> in plugin returned [" PRIu16 "]",
446                  key.toString().c_str(), result.policyType());
447             break;
448         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY:
449             retValue = CYNARA_API_ACCESS_NOT_RESOLVED;
450             break;
451         default:
452             result = PolicyResult(PredefinedPolicyType::DENY);
453             retValue = CYNARA_API_SUCCESS;
454         }
455     }
456     }
457     m_auditLog.log(request->key(), result);
458     context->returnResponse(context, std::make_shared<SimpleCheckResponse>(retValue, result,
459                                                                   request->sequenceNumber()));
460 }
461
462 void Logic::checkPoliciesTypes(const std::map<PolicyBucketId, std::vector<Policy>> &policies,
463                                bool allowBucket, bool allowNone) {
464     for (const auto &group : policies) {
465         for (const auto &policy : group.second) {
466             checkSinglePolicyType(policy.result().policyType(), allowBucket, allowNone);
467         }
468     }
469 }
470
471 void Logic::checkSinglePolicyType(const PolicyType &policyType, bool allowBucket, bool allowNone) {
472     if (allowBucket && policyType == PredefinedPolicyType::BUCKET)
473         return;
474     if (allowNone && policyType == PredefinedPolicyType::NONE)
475         return;
476     for (const auto &descr : predefinedPolicyDescr) {
477         if (descr.type == policyType)
478             return;
479     }
480     m_pluginManager->checkPolicyType(policyType);
481 }
482
483 void Logic::contextClosed(RequestContextPtr context) {
484     LOGD("context closed");
485
486     LinkId linkId = context->responseQueue();
487
488     m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
489                                  handleAgentTalkerDisconnection(talker); });
490
491     m_checkRequestManager.cancelRequests(linkId,
492                                          [&](const CheckContextPtr &checkContextPtr) -> void {
493                                          handleClientDisconnection(checkContextPtr); });
494 }
495
496 void Logic::onPoliciesChanged(void) {
497     m_storage->save();
498     m_socketManager->disconnectAllClients();
499     m_pluginManager->invalidateAll();
500     //todo remove all saved contexts (if there will be any saved contexts)
501 }
502
503 void Logic::handleAgentTalkerDisconnection(const AgentTalkerPtr &agentTalkerPtr) {
504     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(agentTalkerPtr);
505     if (checkContextPtr == nullptr) {
506         LOGE("No matching check context for agent talker.");
507         return;
508     }
509
510     if (!checkContextPtr->cancelled() && checkContextPtr->m_requestContext->responseQueue()) {
511         PolicyResult result(PredefinedPolicyType::DENY);
512         m_auditLog.log(checkContextPtr->m_key, result);
513         checkContextPtr->m_requestContext->returnResponse(checkContextPtr->m_requestContext,
514                 std::make_shared<CheckResponse>(result, checkContextPtr->m_checkId));
515     }
516
517     m_checkRequestManager.removeRequest(checkContextPtr);
518 }
519
520 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
521     LOGD("Handle client disconnection");
522
523     if (!checkContextPtr->cancelled()) {
524         checkContextPtr->cancel();
525         checkContextPtr->m_agentTalker->cancel();
526     }
527 }
528
529 } // namespace Cynara