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