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