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