Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / resource / csdk / security / src / secureresourcemanager.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include "ocstack.h"
22 #include "logger.h"
23 #include "cainterface.h"
24 #include "secureresourcemanager.h"
25 #include "resourcemanager.h"
26 #include "credresource.h"
27 #include "policyengine.h"
28 #include <string.h>
29
30 #define TAG  PCF("SRM")
31
32 //Request Callback handler
33 static CARequestCallback gRequestHandler = NULL;
34 //Response Callback handler
35 static CAResponseCallback gResponseHandler = NULL;
36 //Error Callback handler
37 static CAErrorCallback gErrorHandler = NULL;
38 //Persistent Storage callback handler for open/read/write/close/unlink
39 static OCPersistentStorage *gPersistentStorageHandler =  NULL;
40 //Provisioning response callback
41 static SPResponseCallback gSPResponseHandler = NULL;
42
43 /**
44  * A single global Policy Engine context will suffice as long
45  * as SRM is single-threaded.
46  */
47 PEContext_t g_policyEngineContext;
48
49 /**
50  * @brief function to register provisoning API's response callback.
51  * @param respHandler response handler callback.
52  */
53 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
54 {
55     gSPResponseHandler = respHandler;
56 }
57 /**
58  * @brief   Handle the request from the SRM.
59  * @param   endPoint       [IN] Endpoint object from which the response is received.
60  * @param   requestInfo    [IN] Information for the request.
61  * @return  NONE
62  */
63 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
64 {
65     OC_LOG(INFO, TAG, PCF("Received request from remote device"));
66
67     if (!endPoint || !requestInfo)
68     {
69         OC_LOG(ERROR, TAG, PCF("Invalid arguments"));
70         return;
71     }
72
73     // Copy the subjectID
74     OicUuid_t subjectId = {};
75     memcpy(subjectId.id, endPoint->identity.id, sizeof(subjectId.id));
76
77     //Check the URI has the query and skip it before checking the permission
78     char *uri = strstr(requestInfo->info.resourceUri, "?");
79     int position = 0;
80     if (uri)
81     {
82         position = uri - requestInfo->info.resourceUri;
83     }
84     if (position > MAX_URI_LENGTH)
85     {
86         OC_LOG(ERROR, TAG, PCF("URI length is too long"));
87         return;
88     }
89     SRMAccessResponse_t response = ACCESS_DENIED;
90     if (position > 0)
91     {
92         char newUri[MAX_URI_LENGTH + 1];
93         strncpy(newUri, requestInfo->info.resourceUri, (position));
94         newUri[position] = '\0';
95         //Skip query and pass the newUri.
96         response = CheckPermission(&g_policyEngineContext, &subjectId,
97                               newUri,
98                               GetPermissionFromCAMethod_t(requestInfo->method));
99     }
100     else
101     {
102         //Pass resourceUri if there is no query info.
103         response = CheckPermission(&g_policyEngineContext, &subjectId,
104                               requestInfo->info.resourceUri,
105                               GetPermissionFromCAMethod_t(requestInfo->method));
106     }
107     if (IsAccessGranted(response) && gRequestHandler)
108     {
109         return (gRequestHandler(endPoint, requestInfo));
110     }
111
112     // Form a 'access deny' or 'Error' response and send to peer
113     CAResponseInfo_t responseInfo = {};
114     memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
115     responseInfo.info.payload = NULL;
116     if (!gRequestHandler)
117     {
118         responseInfo.result = CA_INTERNAL_SERVER_ERROR;
119     }
120     else
121     {
122         /*
123          * TODO Enhance this logic more to decide between
124          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
125          * upon SRMAccessResponseReasonCode_t
126          */
127         responseInfo.result = CA_UNAUTHORIZED_REQ;
128     }
129
130     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
131     {
132         OC_LOG(ERROR, TAG, PCF("Failed in sending response to a unauthorized request!"));
133     }
134 }
135
136 /**
137  * @brief   Handle the response from the SRM.
138  * @param   endPoint     [IN] The remote endpoint.
139  * @param   responseInfo [IN] Response information from the endpoint.
140  * @return  NONE
141  */
142 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
143 {
144     OC_LOG(INFO, TAG, PCF("Received response from remote device"));
145
146     // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
147     // When token sent by CA response matches with token generated by provisioning request,
148     // gSPResponseHandler returns true and response is not sent to RI layer. In case
149     // gSPResponseHandler is null and isProvResponse is false response then the response is for
150     // RI layer.
151     bool isProvResponse = false;
152
153     if (gSPResponseHandler)
154     {
155         isProvResponse = gSPResponseHandler(endPoint, responseInfo);
156     }
157     if (!isProvResponse && gResponseHandler)
158     {
159         gResponseHandler(endPoint, responseInfo);
160     }
161 }
162
163
164 /**
165  * @brief   Handle the error from the SRM.
166  * @param   endPoint  [IN] The remote endpoint.
167  * @param   errorInfo [IN] Error information from the endpoint.
168  * @return  NONE
169  */
170 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
171 {
172     OC_LOG(INFO, TAG, PCF("Received error from remote device"));
173     if (gErrorHandler)
174     {
175         gErrorHandler(endPoint, errorInfo);
176     }
177 }
178
179
180 /**
181  * @brief   Register request and response callbacks.
182  *          Requests and responses are delivered in these callbacks.
183  * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
184  * @param   respHandler  [IN] Response handler callback.
185  * @return
186  *     OC_STACK_OK    - No errors; Success
187  *     OC_STACK_INVALID_PARAM - invalid parameter
188  */
189 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
190                                  CAResponseCallback respHandler,
191                                  CAErrorCallback errHandler)
192 {
193     OC_LOG(INFO, TAG, PCF("SRMRegisterHandler !!"));
194     if( !reqHandler || !respHandler || !errHandler)
195     {
196         OC_LOG(ERROR, TAG, PCF("Callback handlers are invalid"));
197         return OC_STACK_INVALID_PARAM;
198     }
199     gRequestHandler = reqHandler;
200     gResponseHandler = respHandler;
201     gErrorHandler = errHandler;
202
203
204 #if defined(__WITH_DTLS__)
205     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
206 #else
207     CARegisterHandler(reqHandler, respHandler, errHandler);
208 #endif /* __WITH_DTLS__ */
209     return OC_STACK_OK;
210 }
211
212 /**
213  * @brief   Register Persistent storage callback.
214  * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
215  * @return
216  *     OC_STACK_OK    - No errors; Success
217  *     OC_STACK_INVALID_PARAM - Invalid parameter
218  */
219 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
220 {
221     OC_LOG(INFO, TAG, PCF("SRMRegisterPersistentStorageHandler !!"));
222     if(!persistentStorageHandler)
223     {
224         OC_LOG(ERROR, TAG, PCF("The persistent storage handler is invalid"));
225         return OC_STACK_INVALID_PARAM;
226     }
227     gPersistentStorageHandler = persistentStorageHandler;
228     return OC_STACK_OK;
229 }
230
231 /**
232  * @brief   Get Persistent storage handler pointer.
233  * @return
234  *     The pointer to Persistent Storage callback handler
235  */
236
237 OCPersistentStorage* SRMGetPersistentStorageHandler()
238 {
239     OC_LOG(INFO, TAG, PCF("SRMGetPersistentStorageHandler !!"));
240     return gPersistentStorageHandler;
241 }
242
243
244 /**
245  * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
246  * @retval  OC_STACK_OK for Success, otherwise some error value
247  */
248 OCStackResult SRMInitSecureResources()
249 {
250     // TODO: temporarily returning OC_STACK_OK every time until default
251     // behavior (for when SVR DB is missing) is settled.
252     InitSecureResources();
253
254 #if defined(__WITH_DTLS__)
255     CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
256 #endif // (__WITH_DTLS__)
257
258     return OC_STACK_OK;
259 }
260
261 /**
262  * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
263  * @retval  none
264  */
265 void SRMDeInitSecureResources()
266 {
267     DestroySecureResources();
268 }
269
270 /**
271  * @brief   Initialize Policy Engine.
272  * @return  OC_STACK_OK for Success, otherwise some error value.
273  */
274 OCStackResult SRMInitPolicyEngine()
275 {
276     return InitPolicyEngine(&g_policyEngineContext);
277 }
278
279 /**
280  * @brief   Cleanup Policy Engine.
281  * @return  none
282  */
283 void SRMDeInitPolicyEngine()
284 {
285     return DeInitPolicyEngine(&g_policyEngineContext);
286 }