Handle check request with agent usage
[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
28 #include <log/log.h>
29 #include <common.h>
30 #include <log/log.h>
31 #include <exceptions/BucketNotExistsException.h>
32 #include <exceptions/DatabaseException.h>
33 #include <exceptions/DefaultBucketDeletionException.h>
34 #include <exceptions/DefaultBucketSetNoneException.h>
35 #include <exceptions/InvalidBucketIdException.h>
36 #include <exceptions/PluginErrorException.h>
37 #include <exceptions/PluginNotFoundException.h>
38 #include <exceptions/UnexpectedErrorException.h>
39 #include <request/AdminCheckRequest.h>
40 #include <request/AgentRegisterRequest.h>
41 #include <request/CancelRequest.h>
42 #include <request/CheckRequest.h>
43 #include <request/InsertOrUpdateBucketRequest.h>
44 #include <request/RemoveBucketRequest.h>
45 #include <request/RequestContext.h>
46 #include <request/SetPoliciesRequest.h>
47 #include <request/SignalRequest.h>
48 #include <response/AgentRegisterResponse.h>
49 #include <response/CancelResponse.h>
50 #include <response/CheckResponse.h>
51 #include <response/CodeResponse.h>
52
53 #include <main/Cynara.h>
54 #include <agent/AgentManager.h>
55 #include <sockets/SocketManager.h>
56 #include <storage/Storage.h>
57
58 #include <cynara-plugin.h>
59
60 #include "Logic.h"
61
62 namespace Cynara {
63 Logic::Logic() {
64 }
65
66 Logic::~Logic() {
67 }
68
69 void Logic::execute(RequestContextPtr context UNUSED, SignalRequestPtr request) {
70     LOGD("Processing signal: [%d]", request->signalNumber());
71
72     switch (request->signalNumber()) {
73     case SIGTERM:
74         LOGI("SIGTERM received!");
75         m_socketManager->mainLoopStop();
76         break;
77     }
78 }
79
80 void Logic::execute(RequestContextPtr context, AdminCheckRequestPtr request) {
81     PolicyResult result = m_storage->checkPolicy(request->key(), request->startBucket(),
82                                                  request->recursive());
83
84     context->returnResponse(context, std::make_shared<CheckResponse>(result,
85                             request->sequenceNumber()));
86 }
87
88 void Logic::execute(RequestContextPtr context, AgentRegisterRequestPtr request) {
89     auto result = m_agentManager->registerAgent(request->agentType(), context->responseQueue());
90     context->returnResponse(context, std::make_shared<AgentRegisterResponse>(
91                             result, request->sequenceNumber()));
92 }
93
94 void Logic::execute(RequestContextPtr context, CancelRequestPtr request) {
95     // MOCKUP
96     context->returnResponse(context, std::make_shared<CancelResponse>(request->sequenceNumber()));
97 }
98
99 void Logic::execute(RequestContextPtr context, CheckRequestPtr request) {
100     PolicyResult result(PredefinedPolicyType::DENY);
101     if (check(context, request->key(), request->sequenceNumber(), result)) {
102         context->returnResponse(context, std::make_shared<CheckResponse>(result,
103                                 request->sequenceNumber()));
104     }
105 }
106
107 bool Logic::check(const RequestContextPtr &context, const PolicyKey &key,
108                   ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
109
110     if (m_checkRequestManager.getContext(context->responseQueue(), checkId)) {
111         LOGE("Check request for checkId: [%" PRIu16 "] is already processing", checkId);
112         return false;
113     }
114
115     result = m_storage->checkPolicy(key);
116
117     switch (result.policyType()) {
118         case PredefinedPolicyType::ALLOW :
119             LOGD("check of policy key <%s> returned ALLOW", key.toString().c_str());
120             return true;
121         case PredefinedPolicyType::DENY :
122             LOGD("check of policy key <%s> returned DENY", key.toString().c_str());
123             return true;
124     }
125
126     return pluginCheck(context, key, checkId, result);
127 }
128
129 bool Logic::pluginCheck(const RequestContextPtr &context, const PolicyKey &key,
130                         ProtocolFrameSequenceNumber checkId, PolicyResult &result) {
131
132     LOGD("Trying to check policy: <%s> in plugin.", key.toString().c_str());
133
134     ExternalPluginPtr plugin = m_pluginManager->getPlugin(result.policyType());
135     if (!plugin) {
136         LOGE("Plugin not found for policy: [0x%x]", result.policyType());
137         result = PolicyResult(PredefinedPolicyType::DENY);
138         return true;
139     }
140
141     ServicePluginInterfacePtr servicePlugin =
142             std::dynamic_pointer_cast<ServicePluginInterface>(plugin);
143     if (!plugin) {
144         throw PluginNotFoundException(result);
145     }
146
147     AgentType requiredAgent;
148     PluginData pluginData;
149
150     auto ret = servicePlugin->check(key.client().toString(), key.user().toString(),
151                                     key.privilege().toString(), result, requiredAgent, pluginData);
152
153     switch (ret) {
154         case ServicePluginInterface::PluginStatus::ANSWER_READY:
155             return true;
156         case ServicePluginInterface::PluginStatus::ANSWER_NOTREADY: {
157                 result = PolicyResult(PredefinedPolicyType::DENY);
158                 AgentTalkerPtr agentTalker = m_agentManager->createTalker(requiredAgent);
159                 if (!agentTalker) {
160                     LOGE("Required agent talker for: <%s> could not be created.",
161                          requiredAgent.c_str());
162                     return true;
163                 }
164
165                 if (!m_checkRequestManager.createContext(key, context, checkId, servicePlugin,
166                                                          agentTalker)) {
167                     LOGE("Check context for checkId: [%" PRIu16 "] could not be created.",
168                          checkId);
169                     m_agentManager->removeTalker(agentTalker);
170                     return true;
171                 }
172                 agentTalker->send(pluginData);
173             }
174             return false;
175         default:
176             throw PluginErrorException(key); // This 'throw' should be removed or handled properly.
177     }
178 }
179
180 void Logic::execute(RequestContextPtr context, InsertOrUpdateBucketRequestPtr request) {
181     auto code = CodeResponse::Code::OK;
182
183     try {
184         m_storage->addOrUpdateBucket(request->bucketId(), request->result());
185         onPoliciesChanged();
186     } catch (const DatabaseException &ex) {
187         code = CodeResponse::Code::FAILED;
188     } catch (const DefaultBucketSetNoneException &ex) {
189         code = CodeResponse::Code::NOT_ALLOWED;
190     } catch (const InvalidBucketIdException &ex) {
191         code = CodeResponse::Code::NOT_ALLOWED;
192     }
193
194     context->returnResponse(context, std::make_shared<CodeResponse>(code,
195                             request->sequenceNumber()));
196 }
197
198 void Logic::execute(RequestContextPtr context, RemoveBucketRequestPtr request) {
199     auto code = CodeResponse::Code::OK;
200     try {
201         m_storage->deleteBucket(request->bucketId());
202         onPoliciesChanged();
203     } catch (const DatabaseException &ex) {
204         code = CodeResponse::Code::FAILED;
205     } catch (const BucketNotExistsException &ex) {
206         code = CodeResponse::Code::NO_BUCKET;
207     } catch (const DefaultBucketDeletionException &ex) {
208         code = CodeResponse::Code::NOT_ALLOWED;
209     }
210     context->returnResponse(context, std::make_shared<CodeResponse>(code,
211                             request->sequenceNumber()));
212 }
213
214 void Logic::execute(RequestContextPtr context, SetPoliciesRequestPtr request) {
215     auto code = CodeResponse::Code::OK;
216     try {
217         m_storage->insertPolicies(request->policiesToBeInsertedOrUpdated());
218         m_storage->deletePolicies(request->policiesToBeRemoved());
219         onPoliciesChanged();
220     } catch (const DatabaseException &ex) {
221         code = CodeResponse::Code::FAILED;
222     } catch (const BucketNotExistsException &ex) {
223         code = CodeResponse::Code::NO_BUCKET;
224     }
225     context->returnResponse(context, std::make_shared<CodeResponse>(code,
226                             request->sequenceNumber()));
227 }
228
229 void Logic::contextClosed(RequestContextPtr context UNUSED) {
230     //We don't care now, but we will
231 }
232
233 void Logic::onPoliciesChanged(void) {
234     m_storage->save();
235     m_socketManager->disconnectAllClients();
236     //todo remove all saved contexts (if there will be any saved contexts)
237 }
238
239 } // namespace Cynara