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