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