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