Security CBOR conversion
[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 <string.h>
22 #include "ocstack.h"
23 #include "logger.h"
24 #include "cainterface.h"
25 #include "resourcemanager.h"
26 #include "credresource.h"
27 #include "policyengine.h"
28 #include "srmutility.h"
29 #include "amsmgr.h"
30 #include "oic_string.h"
31 #include "oic_malloc.h"
32 #include "securevirtualresourcetypes.h"
33 #include "secureresourcemanager.h"
34 #include "srmresourcestrings.h"
35
36 #define TAG  "SRM"
37
38 #ifdef __WITH_X509__
39 #include "crlresource.h"
40 #endif // __WITH_X509__
41
42 //Request Callback handler
43 static CARequestCallback gRequestHandler = NULL;
44 //Response Callback handler
45 static CAResponseCallback gResponseHandler = NULL;
46 //Error Callback handler
47 static CAErrorCallback gErrorHandler = NULL;
48 //Persistent Storage callback handler for open/read/write/close/unlink
49 static OCPersistentStorage *gPersistentStorageHandler =  NULL;
50 //Provisioning response callback
51 static SPResponseCallback gSPResponseHandler = NULL;
52
53 /**
54  * A single global Policy Engine context will suffice as long
55  * as SRM is single-threaded.
56  */
57 PEContext_t g_policyEngineContext;
58
59 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
60 {
61     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
62
63     if (NULL == context ||
64        NULL == context->amsMgrContext->requestInfo)
65     {
66         OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
67         return;
68     }
69
70     memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
71             sizeof(responseInfo.info));
72     responseInfo.info.payload = NULL;
73     responseInfo.result = CA_UNAUTHORIZED_REQ;
74
75     if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
76     {
77         OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
78     }
79     else
80     {
81         OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
82     }
83 }
84
85 void SRMSendResponse(SRMAccessResponse_t responseVal)
86 {
87     OIC_LOG(DEBUG, TAG, "Sending response to remote device");
88
89     if (IsAccessGranted(responseVal) && gRequestHandler)
90     {
91         OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
92         if (!g_policyEngineContext.amsMgrContext->endpoint ||
93             !g_policyEngineContext.amsMgrContext->requestInfo)
94         {
95             OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
96             SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
97             goto exit;
98         }
99         gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
100                 g_policyEngineContext.amsMgrContext->requestInfo);
101     }
102     else
103     {
104         OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
105         SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
106     }
107
108 exit:
109     //Resetting PE state to AWAITING_REQUEST
110     SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
111 }
112
113 /**
114  * Handle the request from the SRM.
115  *
116  * @param endPoint object from which the response is received.
117  * @param requestInfo contains information for the request.
118  */
119 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
120 {
121     OIC_LOG(DEBUG, TAG, "Received request from remote device");
122
123     if (!endPoint || !requestInfo)
124     {
125         OIC_LOG(ERROR, TAG, "Invalid arguments");
126         return;
127     }
128
129     // Copy the subjectID
130     OicUuid_t subjectId = {.id = {0}};
131     memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
132
133     //Check the URI has the query and skip it before checking the permission
134     char *uri = strstr(requestInfo->info.resourceUri, "?");
135     int position = 0;
136     if (uri)
137     {
138         //Skip query and pass the resource uri
139         position = uri - requestInfo->info.resourceUri;
140     }
141     else
142     {
143         position = strlen(requestInfo->info.resourceUri);
144     }
145     if (MAX_URI_LENGTH < position  || 0 > position)
146     {
147         OIC_LOG(ERROR, TAG, "Incorrect URI length");
148         return;
149     }
150     SRMAccessResponse_t response = ACCESS_DENIED;
151     char newUri[MAX_URI_LENGTH + 1];
152     OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
153
154     //New request are only processed if the policy engine state is AWAITING_REQUEST.
155     if (AWAITING_REQUEST == g_policyEngineContext.state)
156     {
157         OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
158                 requestInfo->info.resourceUri, requestInfo->method);
159         response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
160                 GetPermissionFromCAMethod_t(requestInfo->method));
161     }
162     else
163     {
164         OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
165                 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
166     }
167
168     if (IsAccessGranted(response) && gRequestHandler)
169     {
170         return (gRequestHandler(endPoint, requestInfo));
171     }
172
173     // Form a 'Error', 'slow response' or 'access deny' response and send to peer
174     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
175     memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
176     responseInfo.info.payload = NULL;
177
178     VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
179
180     if (ACCESS_WAITING_FOR_AMS == response)
181     {
182         OIC_LOG(INFO, TAG, "Sending slow response");
183
184         UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
185         responseInfo.result = CA_EMPTY;
186         responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
187     }
188     else
189     {
190         /*
191          * TODO Enhance this logic more to decide between
192          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
193          * upon SRMAccessResponseReasonCode_t
194          */
195         OIC_LOG(INFO, TAG, "Sending for regular response");
196         responseInfo.result = CA_UNAUTHORIZED_REQ;
197     }
198
199     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
200     {
201         OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
202     }
203     return;
204 exit:
205     responseInfo.result = CA_INTERNAL_SERVER_ERROR;
206     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
207     {
208         OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
209     }
210 }
211
212 /**
213  * Handle the response from the SRM.
214  *
215  * @param endPoint points to the remote endpoint.
216  * @param responseInfo contains response information from the endpoint.
217  */
218 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
219 {
220     OIC_LOG(DEBUG, TAG, "Received response from remote device");
221
222     // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
223     // When token sent by CA response matches with token generated by provisioning request,
224     // gSPResponseHandler returns true and response is not sent to RI layer. In case
225     // gSPResponseHandler is null and isProvResponse is false response then the response is for
226     // RI layer.
227     bool isProvResponse = false;
228
229     if (gSPResponseHandler)
230     {
231         isProvResponse = gSPResponseHandler(endPoint, responseInfo);
232     }
233     if (!isProvResponse && gResponseHandler)
234     {
235         gResponseHandler(endPoint, responseInfo);
236     }
237 }
238
239 /**
240  * Handle the error from the SRM.
241  *
242  * @param endPoint is the remote endpoint.
243  * @param errorInfo contains error information from the endpoint.
244  */
245 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
246 {
247     OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
248             errorInfo->result, errorInfo->info.resourceUri);
249     if (gErrorHandler)
250     {
251         gErrorHandler(endPoint, errorInfo);
252     }
253 }
254
255 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
256                                  CAResponseCallback respHandler,
257                                  CAErrorCallback errHandler)
258 {
259     OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
260     if( !reqHandler || !respHandler || !errHandler)
261     {
262         OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
263         return OC_STACK_INVALID_PARAM;
264     }
265     gRequestHandler = reqHandler;
266     gResponseHandler = respHandler;
267     gErrorHandler = errHandler;
268
269
270 #if defined(__WITH_DTLS__)
271     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
272 #else
273     CARegisterHandler(reqHandler, respHandler, errHandler);
274 #endif /* __WITH_DTLS__ */
275     return OC_STACK_OK;
276 }
277
278 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
279 {
280     OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
281     if(!persistentStorageHandler)
282     {
283         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
284         return OC_STACK_INVALID_PARAM;
285     }
286     gPersistentStorageHandler = persistentStorageHandler;
287     return OC_STACK_OK;
288 }
289
290 OCPersistentStorage* SRMGetPersistentStorageHandler()
291 {
292     return gPersistentStorageHandler;
293 }
294
295 OCStackResult SRMInitSecureResources()
296 {
297     // TODO: temporarily returning OC_STACK_OK every time until default
298     // behavior (for when SVR DB is missing) is settled.
299     InitSecureResources();
300     OCStackResult ret = OC_STACK_OK;
301 #if defined(__WITH_DTLS__)
302     if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
303     {
304         OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
305         ret = OC_STACK_ERROR;
306     }
307
308 #endif // (__WITH_DTLS__)
309 #if defined(__WITH_X509__)
310     CARegisterDTLSX509CredentialsHandler(GetDtlsX509Credentials);
311     CARegisterDTLSCrlHandler(GetDerCrl);
312 #endif // (__WITH_X509__)
313
314     return ret;
315 }
316
317 void SRMDeInitSecureResources()
318 {
319     DestroySecureResources();
320 }
321
322 OCStackResult SRMInitPolicyEngine()
323 {
324     return InitPolicyEngine(&g_policyEngineContext);
325 }
326
327 void SRMDeInitPolicyEngine()
328 {
329     return DeInitPolicyEngine(&g_policyEngineContext);
330 }
331
332 bool SRMIsSecurityResourceURI(const char* uri)
333 {
334     if (!uri)
335     {
336         return false;
337     }
338
339     const char *rsrcs[] = {
340         OIC_RSRC_SVC_URI,
341         OIC_RSRC_AMACL_URI,
342         OIC_RSRC_CRL_URI,
343         OIC_RSRC_CRED_URI,
344         OIC_RSRC_ACL_URI,
345         OIC_RSRC_DOXM_URI,
346         OIC_RSRC_PSTAT_URI,
347         OIC_RSRC_PCONF_URI,
348         OIC_RSRC_DPAIRING_URI,
349     };
350
351     // Remove query from Uri for resource string comparison
352     size_t uriLen = strlen(uri);
353     char *query = strchr (uri, '?');
354     if (query)
355     {
356         uriLen = query - uri;
357     }
358
359     for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
360     {
361         size_t svrLen = strlen(rsrcs[i]);
362
363         if ((uriLen == svrLen) &&
364             (strncmp(uri, rsrcs[i], svrLen) == 0))
365         {
366             return true;
367         }
368     }
369
370     return false;
371 }