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