Implement plugin description listing in service logic
[platform/core/security/cynara.git] / src / service / logic / Logic.cpp
1 /*
2  * Copyright (c) 2014 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  * @version     1.0
20  * @brief       This file implements main class of logic layer in cynara service
21  */
22
23 #include <csignal>
24 #include <cinttypes>
25 #include <functional>
26 #include <memory>
27 #include <vector>
28
29 #include <log/log.h>
30 #include <common.h>
31 #include <log/log.h>
32 #include <exceptions/BucketNotExistsException.h>
33 #include <exceptions/DatabaseException.h>
34 #include <exceptions/DefaultBucketDeletionException.h>
35 #include <exceptions/DefaultBucketSetNoneException.h>
36 #include <exceptions/InvalidBucketIdException.h>
37 #include <exceptions/PluginErrorException.h>
38 #include <exceptions/PluginNotFoundException.h>
39 #include <exceptions/UnexpectedErrorException.h>
40 #include <request/AdminCheckRequest.h>
41 #include <request/AgentActionRequest.h>
42 #include <request/AgentRegisterRequest.h>
43 #include <request/CancelRequest.h>
44 #include <request/CheckRequest.h>
45 #include <request/DescriptionListRequest.h>
46 #include <request/EraseRequest.h>
47 #include <request/InsertOrUpdateBucketRequest.h>
48 #include <request/ListRequest.h>
49 #include <request/RemoveBucketRequest.h>
50 #include <request/RequestContext.h>
51 #include <request/SetPoliciesRequest.h>
52 #include <request/SignalRequest.h>
53 #include <response/AdminCheckResponse.h>
54 #include <response/AgentRegisterResponse.h>
55 #include <response/CancelResponse.h>
56 #include <response/CheckResponse.h>
57 #include <response/CodeResponse.h>
58 #include <response/DescriptionListResponse.h>
59 #include <response/ListResponse.h>
60 #include <types/Policy.h>
61
62 #include <main/Cynara.h>
63 #include <agent/AgentManager.h>
64 #include <sockets/SocketManager.h>
65 #include <storage/Storage.h>
66
67 #include <cynara-plugin.h>
68
69 #include <cynara-agent.h>
70
71 #include "Logic.h"
72
73 namespace Cynara {
74
75 Logic::Logic() {
76 }
77
78 Logic::~Logic() {
79 }
80
81 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
82     LOGD("Processing signal: [%d]", request->signalNumber());
83
84     switch (request->signalNumber()) {
85     case SIGTERM:
86         LOGI("SIGTERM received!");
87         m_socketManager->mainLoopStop();
88         break;
89     }
90 }
91
92 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
93     PolicyResult result;
94     bool bucketValid = true;
95     try {
96         result = m_storage->checkPolicy(request->key(), request->startBucket(),
97                                         request->recursive());
98     } catch (const BucketNotExistsException &ex) {
99         bucketValid = false;
100     }
101
102     context->returnResponse(context, std::make_shared<AdminCheckResponse>(result, bucketValid,
103                             request->sequenceNumber()));
104 }
105
106 void Logic::execute(RequestContextPtr context, AgentActionRequestPtr request) {
107     AgentTalkerPtr talkerPtr = m_agentManager->getTalker(context->responseQueue(),
108                                                          request->sequenceNumber());
109     if (!talkerPtr) {
110         LOGD("Received response from agent with invalid request id: [%" PRIu16 "]",
111              request->sequenceNumber());
112         return;
113     }
114
115     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(talkerPtr);
116     if (!checkContextPtr) {
117         LOGE("No matching check context for agent talker.");
118         m_agentManager->removeTalker(talkerPtr);
119         return;
120     }
121
122     if (!checkContextPtr->cancelled()) {
123         PluginData data(request->data().begin(), request->data().end());
124         if (request->type() == CYNARA_MSG_TYPE_CANCEL) {
125             // Nothing to do for now
126         } else if (request->type() == CYNARA_MSG_TYPE_ACTION) {
127             update(checkContextPtr->m_key, checkContextPtr->m_checkId, data,
128                    checkContextPtr->m_requestContext, checkContextPtr->m_plugin);
129         } else {
130             LOGE("Invalid response type [%d] in response from agent <%s>",
131                  static_cast<int>(request->type()), talkerPtr->agentType().c_str());
132             // TODO: disconnect agent
133         }
134     }
135
136     m_agentManager->removeTalker(talkerPtr);
137     m_checkRequestManager.removeRequest(checkContextPtr);
138 }
139
140 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
141     auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
142     context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
143                             result, request->sequenceNumber()));
144 }
145
146 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
147     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(context->responseQueue(),
148                                                                        request->sequenceNumber());
149     if (!checkContextPtr) {
150         LOGD("Cancel request id: [%" PRIu16 "] with no matching request in progress.",
151              request->sequenceNumber());
152         return;
153     }
154
155     if (checkContextPtr->cancelled())
156         return;
157
158     checkContextPtr->cancel();
159     checkContextPtr->m_agentTalker->cancel();
160
161     LOGD("Returning response for cancel request id: [%" PRIu16 "].", request->sequenceNumber());
162     context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
163 }
164
165 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
166     PolicyResult result(PredefinedPolicyType::DENY);
167     if (check(context, request->key(), request->sequenceNumber(), result)) {
168         context->returnResponse(context, std::make_shared<CheckResponse>(result,
169                                 request->sequenceNumber()));
170     }
171 }
172
173 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
174                   ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
175
176     if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
177         LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
178         return false;
179     }
180
181     result = m_storage->checkPolicy(key);
182
183     switch (result.policyType()) {
184         case PredefinedPolicyType::ALLOW :
185             LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
186             return true;
187         case PredefinedPolicyType::DENY :
188             LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
189             return true;
190     }
191
192     return pluginCheck(context, key, checkId, result);
193 }
194
195 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
196                         ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
197
198     LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
199
200     ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
201     if (!plugin) {
202         LOGE("Plugin not found for policy: [0x%x]", result.policyType());
203         result = PolicyResult(PredefinedPolicyType::DENY);
204         return true;
205     }
206
207     ServicePluginInterfacePtr servicePlugin =
208             std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
209     if (!plugin) {
210         throw PluginNotFoundException(result);
211     }
212
213     AgentType requiredAgent;
214     PluginData pluginData;
215
216     auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
217                                     key.privilege().toString(), result, requiredAgent, pluginData);
218
219     switch (ret) {
220         case ServicePluginInterface::PluginStatus::ANSWER_READY:
221             return true;
222         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
223                 result = PolicyResult(PredefinedPolicyType::DENY);
224                 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
225                 if (!agentTalker) {
226                     LOGE("Required agent talker for: <%s> could not be created.",
227                          requiredAgent.c_str());
228                     return true;
229                 }
230
231                 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
232                                                          agentTalker)) {
233                     LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
234                          checkId);
235                     m_agentManager->removeTalker(agentTalker);
236                     return true;
237                 }
238                 agentTalker->send(pluginData);
239             }
240             return false;
241         default:
242             throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
243     }
244 }
245
246 bool Logic::update(const PolicyKey &key, ProtocolFrameSequenceNumber checkId,
247                    const PluginData &agentData, const RequestContextPtr &context,
248                    const ServicePluginInterfacePtr &plugin) {
249
250     LOGD("Check update: <%s>:[%" PRIu16 "]", key.toString().c_str(), checkId);
251
252     PolicyResult result;
253     bool answerReady = false;
254     auto ret = plugin->update(key.client().toString(), key.user().toString(),
255                               key.privilege().toString(), agentData, result);
256     switch (ret) {
257         case ServicePluginInterface::PluginStatus::SUCCESS:
258             answerReady = true;
259             break;
260         case ServicePluginInterface::PluginStatus::ERROR:
261             result = PolicyResult(PredefinedPolicyType::DENY);
262             answerReady = true;
263             break;
264         default:
265             throw PluginErrorException(key);
266     }
267
268     if (answerReady && context->responseQueue()) {
269         context->returnResponse(context, std::make_shared<CheckResponse>(result, checkId));
270         return true;
271     }
272
273     return false;
274 }
275
276 void Logic::execute(RequestContextPtr context, DescriptionListRequestPtr request) {
277     auto descriptions = m_pluginManager->getPolicyDescriptions();
278     descriptions.insert(descriptions.begin(), predefinedPolicyDescr.begin(),
279                         predefinedPolicyDescr.end());
280
281     context->returnResponse(context, std::make_shared<DescriptionListResponse>(descriptions,
282                             request->sequenceNumber()));
283 }
284
285 void Logic::execute(RequestContextPtr context, EraseRequestPtr request) {
286     auto code = CodeResponse::Code::OK;
287
288     try {
289         m_storage->erasePolicies(request->startBucket(), request->recursive(), request->filter());
290         onPoliciesChanged();
291     } catch (const DatabaseException &ex) {
292         code = CodeResponse::Code::FAILED;
293     } catch (const BucketNotExistsException &ex) {
294         code = CodeResponse::Code::NO_BUCKET;
295     }
296
297     context->returnResponse(context, std::make_shared<CodeResponse>(code,
298                             request->sequenceNumber()));
299 }
300
301 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
302     auto code = CodeResponse::Code::OK;
303
304     try {
305         m_storage->addOrUpdateBucket(request->bucketId(), request->result());
306         onPoliciesChanged();
307     } catch (const DatabaseException &ex) {
308         code = CodeResponse::Code::FAILED;
309     } catch (const DefaultBucketSetNoneException &ex) {
310         code = CodeResponse::Code::NOT_ALLOWED;
311     } catch (const InvalidBucketIdException &ex) {
312         code = CodeResponse::Code::NOT_ALLOWED;
313     }
314
315     context->returnResponse(context, std::make_shared<CodeResponse>(code,
316                             request->sequenceNumber()));
317 }
318
319 void Logic::execute(RequestContextPtr context, ListRequestPtr request) {
320     bool bucketValid = true;
321
322     std::vector<Policy> policies;
323     try {
324         policies = m_storage->listPolicies(request->bucket(), request->filter());
325     } catch (const BucketNotExistsException &ex) {
326         bucketValid = false;
327     }
328
329     context->returnResponse(context, std::make_shared<ListResponse>(policies, bucketValid,
330                             request->sequenceNumber()));
331 }
332
333 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
334     auto code = CodeResponse::Code::OK;
335     try {
336         m_storage->deleteBucket(request->bucketId());
337         onPoliciesChanged();
338     } catch (const DatabaseException &ex) {
339         code = CodeResponse::Code::FAILED;
340     } catch (const BucketNotExistsException &ex) {
341         code = CodeResponse::Code::NO_BUCKET;
342     } catch (const DefaultBucketDeletionException &ex) {
343         code = CodeResponse::Code::NOT_ALLOWED;
344     }
345     context->returnResponse(context, std::make_shared<CodeResponse>(code,
346                             request->sequenceNumber()));
347 }
348
349 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
350     auto code = CodeResponse::Code::OK;
351     try {
352         m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
353         m_storage->deletePolicies(request->policiesToBeRemoved());
354         onPoliciesChanged();
355     } catch (const DatabaseException &ex) {
356         code = CodeResponse::Code::FAILED;
357     } catch (const BucketNotExistsException &ex) {
358         code = CodeResponse::Code::NO_BUCKET;
359     }
360     context->returnResponse(context, std::make_shared<CodeResponse>(code,
361                             request->sequenceNumber()));
362 }
363
364 void Logic::contextClosed(RequestContextPtr context) {
365     LOGD("context closed");
366
367     LinkId linkId = context->responseQueue();
368
369     m_agentManager->cleanupAgent(linkId, [&](const AgentTalkerPtr &talker) -> void {
370                                  handleAgentTalkerDisconnection(talker); });
371
372     m_checkRequestManager.cancelRequests(linkId,
373                                          [&](const CheckContextPtr &checkContextPtr) -> void {
374                                          handleClientDisconnection(checkContextPtr); });
375 }
376
377 void Logic::onPoliciesChanged(void) {
378     m_storage->save();
379     m_socketManager->disconnectAllClients();
380     m_pluginManager->invalidateAll();
381     //todo remove all saved contexts (if there will be any saved contexts)
382 }
383
384 void Logic::handleAgentTalkerDisconnection(const AgentTalkerPtr &agentTalkerPtr) {
385     CheckContextPtr checkContextPtr = m_checkRequestManager.getContext(agentTalkerPtr);
386     if (checkContextPtr == nullptr) {
387         LOGE("No matching check context for agent talker.");
388         return;
389     }
390
391     if (!checkContextPtr->cancelled() && checkContextPtr->m_requestContext->responseQueue()) {
392         PolicyResult result(PredefinedPolicyType::DENY);
393         checkContextPtr->m_requestContext->returnResponse(checkContextPtr->m_requestContext,
394                 std::make_shared<CheckResponse>(result, checkContextPtr->m_checkId));
395     }
396
397     m_checkRequestManager.removeRequest(checkContextPtr);
398 }
399
400 void Logic::handleClientDisconnection(const CheckContextPtr &checkContextPtr) {
401     LOGD("Handle client disconnection");
402
403     if (!checkContextPtr->cancelled()) {
404         checkContextPtr->cancel();
405         checkContextPtr->m_agentTalker->cancel();
406     }
407 }
408
409 } // namespace Cynara