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