Adding NULL checking input parameter in SRMRequestHandler
[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 #include "ocresourcehandler.h"
36
37 #if defined( __WITH_TLS__) || defined(__WITH_DTLS__)
38 #include "pkix_interface.h"
39 #endif //__WITH_TLS__ or __WITH_DTLS__
40 #define TAG  "OIC_SRM"
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 /**
60  * Function to register provisoning API's response callback.
61  * @param respHandler response handler callback.
62  */
63 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
64 {
65     gSPResponseHandler = respHandler;
66 }
67
68 void SetResourceRequestType(PEContext_t *context, const char *resourceUri)
69 {
70     context->resourceType = GetSvrTypeFromUri(resourceUri);
71 }
72
73 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
74 {
75     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
76
77     if (NULL == context ||
78        NULL == context->amsMgrContext->requestInfo)
79     {
80         OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
81         return;
82     }
83
84     memcpy(&responseInfo.info, &(context->amsMgrContext->requestInfo->info),
85             sizeof(responseInfo.info));
86     responseInfo.info.payload = NULL;
87     responseInfo.result = CA_UNAUTHORIZED_REQ;
88     responseInfo.info.dataType = CA_RESPONSE_DATA;
89
90     if (CA_STATUS_OK == CASendResponse(context->amsMgrContext->endpoint, &responseInfo))
91     {
92         OIC_LOG(DEBUG, TAG, "Succeed in sending response to a unauthorized request!");
93     }
94     else
95     {
96         OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
97     }
98 }
99
100 void SRMSendResponse(SRMAccessResponse_t responseVal)
101 {
102     OIC_LOG(DEBUG, TAG, "Sending response to remote device");
103
104     if (IsAccessGranted(responseVal) && gRequestHandler)
105     {
106         OIC_LOG_V(INFO, TAG, "%s : Access granted. Passing Request to RI layer", __func__);
107         if (!g_policyEngineContext.amsMgrContext->endpoint ||
108             !g_policyEngineContext.amsMgrContext->requestInfo)
109         {
110             OIC_LOG_V(ERROR, TAG, "%s : Invalid arguments", __func__);
111             SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
112             goto exit;
113         }
114         gRequestHandler(g_policyEngineContext.amsMgrContext->endpoint,
115                 g_policyEngineContext.amsMgrContext->requestInfo);
116     }
117     else
118     {
119         OIC_LOG_V(INFO, TAG, "%s : ACCESS_DENIED.", __func__);
120         SRMSendUnAuthorizedAccessresponse(&g_policyEngineContext);
121     }
122
123 exit:
124     //Resetting PE state to AWAITING_REQUEST
125     SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
126 }
127
128 /**
129  * Handle the request from the SRM.
130  *
131  * @param endPoint object from which the response is received.
132  * @param requestInfo contains information for the request.
133  */
134 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
135 {
136     OIC_LOG(DEBUG, TAG, "Received request from remote device");
137
138     bool isRequestOverSecureChannel = false;
139     if (!endPoint || !requestInfo)
140     {
141         OIC_LOG(ERROR, TAG, "Invalid arguments");
142         return;
143     }
144
145     // Copy the subjectID
146     OicUuid_t subjectId = {.id = {0}};
147     memcpy(subjectId.id, requestInfo->info.identity.id, sizeof(subjectId.id));
148     if (endPoint->flags & CA_SECURE)
149     {
150         OIC_LOG(INFO, TAG, "request over secure channel");
151         isRequestOverSecureChannel = true;
152     }
153
154     //Check the URI has the query and skip it before checking the permission
155     if (NULL == requestInfo->info.resourceUri)
156     {
157         OIC_LOG(ERROR, TAG, "Invalid resourceUri");
158         return;
159     }
160
161     char *uri = strstr(requestInfo->info.resourceUri, "?");
162     int position = 0;
163     if (uri)
164     {
165         //Skip query and pass the resource uri
166         position = uri - requestInfo->info.resourceUri;
167     }
168     else
169     {
170         position = strlen(requestInfo->info.resourceUri);
171     }
172     if (MAX_URI_LENGTH < position  || 0 > position)
173     {
174         OIC_LOG(ERROR, TAG, "Incorrect URI length");
175         return;
176     }
177     SRMAccessResponse_t response = ACCESS_DENIED;
178     char newUri[MAX_URI_LENGTH + 1];
179     OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
180
181     SetResourceRequestType(&g_policyEngineContext, newUri);
182
183      // Form a 'Error', 'slow response' or 'access deny' response and send to peer
184     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
185     memcpy(&responseInfo.info, &(requestInfo->info), sizeof(responseInfo.info));
186     responseInfo.info.payload = NULL;
187     responseInfo.info.dataType = CA_RESPONSE_DATA;
188
189     OCResource *resPtr = FindResourceByUri(newUri);
190     if (NULL != resPtr)
191     {
192         // All vertical secure resources and SVR resources other than DOXM & PSTAT should reject request
193         // over coap.
194         if ((((resPtr->resourceProperties) & OC_SECURE)
195                             && (g_policyEngineContext.resourceType == NOT_A_SVR_RESOURCE))
196                             || ((g_policyEngineContext.resourceType < OIC_SEC_SVR_TYPE_COUNT)
197                             &&  (g_policyEngineContext.resourceType != OIC_R_DOXM_TYPE)
198                             &&  (g_policyEngineContext.resourceType != OIC_R_PSTAT_TYPE)))
199         {
200            // if resource is secure and request is over insecure channel
201             if (!isRequestOverSecureChannel)
202             {
203                 // Reject all the requests over coap for secure resource.
204                 responseInfo.result = CA_FORBIDDEN_REQ;
205                 if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
206                 {
207                     OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
208                 }
209                 return;
210             }
211         }
212     }
213 #ifdef _ENABLE_MULTIPLE_OWNER_
214     /*
215      * In case of ACL and CRED, The payload required to verify the payload.
216      * Payload information will be used for subowner's permission verification.
217      */
218     g_policyEngineContext.payload = (uint8_t*)requestInfo->info.payload;
219     g_policyEngineContext.payloadSize = requestInfo->info.payloadSize;
220 #endif //_ENABLE_MULTIPLE_OWNER_
221
222     //New request are only processed if the policy engine state is AWAITING_REQUEST.
223     if (AWAITING_REQUEST == g_policyEngineContext.state)
224     {
225         OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
226                 requestInfo->info.resourceUri, requestInfo->method);
227         response = CheckPermission(&g_policyEngineContext, &subjectId, newUri,
228                 GetPermissionFromCAMethod_t(requestInfo->method));
229     }
230     else
231     {
232         OIC_LOG_V(INFO, TAG, "PE state %d. Ignoring request with uri, %s for method, %d",
233                 g_policyEngineContext.state, requestInfo->info.resourceUri, requestInfo->method);
234     }
235
236     if (IsAccessGranted(response) && gRequestHandler)
237     {
238         gRequestHandler(endPoint, requestInfo);
239         return;
240     }
241
242     VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
243
244     if (ACCESS_WAITING_FOR_AMS == response)
245     {
246         OIC_LOG(INFO, TAG, "Sending slow response");
247
248         UpdateAmsMgrContext(&g_policyEngineContext, endPoint, requestInfo);
249         responseInfo.result = CA_EMPTY;
250         responseInfo.info.type = CA_MSG_ACKNOWLEDGE;
251     }
252     else
253     {
254         /*
255          * TODO Enhance this logic more to decide between
256          * CA_UNAUTHORIZED_REQ or CA_FORBIDDEN_REQ depending
257          * upon SRMAccessResponseReasonCode_t
258          */
259         OIC_LOG(INFO, TAG, "Sending for regular response");
260         responseInfo.result = CA_UNAUTHORIZED_REQ;
261     }
262
263     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
264     {
265         OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
266     }
267     return;
268 exit:
269     responseInfo.result = CA_INTERNAL_SERVER_ERROR;
270     if (CA_STATUS_OK != CASendResponse(endPoint, &responseInfo))
271     {
272         OIC_LOG(ERROR, TAG, "Failed in sending response to a unauthorized request!");
273     }
274 }
275
276 /**
277  * Handle the response from the SRM.
278  *
279  * @param endPoint points to the remote endpoint.
280  * @param responseInfo contains response information from the endpoint.
281  */
282 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
283 {
284     OIC_LOG(DEBUG, TAG, "Received response from remote device");
285
286     // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
287     // When token sent by CA response matches with token generated by provisioning request,
288     // gSPResponseHandler returns true and response is not sent to RI layer. In case
289     // gSPResponseHandler is null and isProvResponse is false response then the response is for
290     // RI layer.
291     bool isProvResponse = false;
292
293     if (gSPResponseHandler)
294     {
295         isProvResponse = gSPResponseHandler(endPoint, responseInfo);
296     }
297     if (!isProvResponse && gResponseHandler)
298     {
299         gResponseHandler(endPoint, responseInfo);
300     }
301 }
302
303 /**
304  * Handle the error from the SRM.
305  *
306  * @param endPoint is the remote endpoint.
307  * @param errorInfo contains error information from the endpoint.
308  */
309 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
310 {
311     OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
312             errorInfo->result, errorInfo->info.resourceUri);
313     if (gErrorHandler)
314     {
315         gErrorHandler(endPoint, errorInfo);
316     }
317 }
318
319 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
320                                  CAResponseCallback respHandler,
321                                  CAErrorCallback errHandler)
322 {
323     OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
324     if( !reqHandler || !respHandler || !errHandler)
325     {
326         OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
327         return OC_STACK_INVALID_PARAM;
328     }
329     gRequestHandler = reqHandler;
330     gResponseHandler = respHandler;
331     gErrorHandler = errHandler;
332
333
334 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
335     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
336 #else
337     CARegisterHandler(reqHandler, respHandler, errHandler);
338 #endif /* __WITH_DTLS__ */
339     return OC_STACK_OK;
340 }
341
342 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
343 {
344     OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
345     if(!persistentStorageHandler)
346     {
347         OIC_LOG(ERROR, TAG, "The persistent storage handler is invalid");
348         return OC_STACK_INVALID_PARAM;
349     }
350     gPersistentStorageHandler = persistentStorageHandler;
351     return OC_STACK_OK;
352 }
353
354 OCPersistentStorage* SRMGetPersistentStorageHandler()
355 {
356     return gPersistentStorageHandler;
357 }
358
359 OCStackResult SRMInitSecureResources()
360 {
361     // TODO: temporarily returning OC_STACK_OK every time until default
362     // behavior (for when SVR DB is missing) is settled.
363     InitSecureResources();
364     OCStackResult ret = OC_STACK_OK;
365 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
366     if (CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
367     {
368         OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
369         ret = OC_STACK_ERROR;
370     }
371     CAregisterPkixInfoHandler(GetPkixInfo);
372     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
373 #endif // __WITH_DTLS__ or __WITH_TLS__
374     return ret;
375 }
376
377 void SRMDeInitSecureResources()
378 {
379     DestroySecureResources();
380 }
381
382 OCStackResult SRMInitPolicyEngine()
383 {
384     return InitPolicyEngine(&g_policyEngineContext);
385 }
386
387 void SRMDeInitPolicyEngine()
388 {
389     DeInitPolicyEngine(&g_policyEngineContext);
390 }
391
392 bool SRMIsSecurityResourceURI(const char* uri)
393 {
394     if (!uri)
395     {
396         return false;
397     }
398
399     const char *rsrcs[] = {
400         OIC_RSRC_SVC_URI,
401         OIC_RSRC_AMACL_URI,
402         OIC_RSRC_CRL_URI,
403         OIC_RSRC_CRED_URI,
404         OIC_RSRC_ACL_URI,
405         OIC_RSRC_DOXM_URI,
406         OIC_RSRC_PSTAT_URI,
407         OIC_RSRC_PCONF_URI,
408         OIC_RSRC_DPAIRING_URI,
409         OIC_RSRC_VER_URI,
410         OC_RSRVD_PROV_CRL_URL
411     };
412
413     // Remove query from Uri for resource string comparison
414     size_t uriLen = strlen(uri);
415     char *query = strchr (uri, '?');
416     if (query)
417     {
418         uriLen = query - uri;
419     }
420
421     for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
422     {
423         size_t svrLen = strlen(rsrcs[i]);
424
425         if ((uriLen == svrLen) &&
426             (strncmp(uri, rsrcs[i], svrLen) == 0))
427         {
428             return true;
429         }
430     }
431
432     return false;
433 }
434
435 /**
436  * Get the Secure Virtual Resource (SVR) type from the URI.
437  * @param   uri [IN] Pointer to URI in question.
438  * @return  The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
439             Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
440  */
441 static const char URI_QUERY_CHAR = '?';
442 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
443 {
444     if (!uri)
445     {
446         return NOT_A_SVR_RESOURCE;
447     }
448
449     // Remove query from Uri for resource string comparison
450     size_t uriLen = strlen(uri);
451     char *query = strchr (uri, URI_QUERY_CHAR);
452     if (query)
453     {
454         uriLen = query - uri;
455     }
456
457     size_t svrLen = 0;
458
459     svrLen = strlen(OIC_RSRC_ACL_URI);
460     if(uriLen == svrLen)
461     {
462         if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
463         {
464             return OIC_R_ACL_TYPE;
465         }
466     }
467
468     svrLen = strlen(OIC_RSRC_AMACL_URI);
469     if(uriLen == svrLen)
470     {
471         if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
472         {
473             return OIC_R_AMACL_TYPE;
474         }
475     }
476
477     svrLen = strlen(OIC_RSRC_CRED_URI);
478     if(uriLen == svrLen)
479     {
480         if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
481         {
482             return OIC_R_CRED_TYPE;
483         }
484     }
485
486     svrLen = strlen(OIC_RSRC_CRL_URI);
487     if(uriLen == svrLen)
488     {
489         if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
490         {
491             return OIC_R_CRL_TYPE;
492         }
493     }
494
495     svrLen = strlen(OIC_RSRC_DOXM_URI);
496     if(uriLen == svrLen)
497     {
498         if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
499         {
500             return OIC_R_DOXM_TYPE;
501         }
502     }
503
504     svrLen = strlen(OIC_RSRC_DPAIRING_URI);
505     if(uriLen == svrLen)
506     {
507         if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
508         {
509             return OIC_R_DPAIRING_TYPE;
510         }
511     }
512
513     svrLen = strlen(OIC_RSRC_PCONF_URI);
514     if(uriLen == svrLen)
515     {
516         if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
517         {
518             return OIC_R_PCONF_TYPE;
519         }
520     }
521
522     svrLen = strlen(OIC_RSRC_PSTAT_URI);
523     if(uriLen == svrLen)
524     {
525         if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
526         {
527             return OIC_R_PSTAT_TYPE;
528         }
529     }
530
531     svrLen = strlen(OIC_RSRC_SVC_URI);
532     if(uriLen == svrLen)
533     {
534         if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
535         {
536             return OIC_R_SVC_TYPE;
537         }
538     }
539
540     svrLen = strlen(OIC_RSRC_SACL_URI);
541     if(uriLen == svrLen)
542     {
543         if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
544         {
545             return OIC_R_SACL_TYPE;
546         }
547     }
548
549     return NOT_A_SVR_RESOURCE;
550 }