[IOT-1831] Fix requested permission
[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 "oic_string.h"
30 #include "oic_malloc.h"
31 #include "securevirtualresourcetypes.h"
32 #include "secureresourcemanager.h"
33 #include "srmresourcestrings.h"
34 #include "ocresourcehandler.h"
35
36 #if defined( __WITH_TLS__) || defined(__WITH_DTLS__)
37 #include "pkix_interface.h"
38 #endif //__WITH_TLS__ or __WITH_DTLS__
39 #define TAG  "OIC_SRM"
40
41 //Request Callback handler
42 static CARequestCallback gRequestHandler = NULL;
43 //Response Callback handler
44 static CAResponseCallback gResponseHandler = NULL;
45 //Error Callback handler
46 static CAErrorCallback gErrorHandler = NULL;
47 //Provisioning response callback
48 static SPResponseCallback gSPResponseHandler = NULL;
49
50 /**
51  * A single global Request context will suffice as long
52  * as SRM is single-threaded.
53  */
54 SRMRequestContext_t g_requestContext;
55
56 /**
57  * Function to register provisoning API's response callback.
58  * @param respHandler response handler callback.
59  */
60 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
61 {
62     gSPResponseHandler = respHandler;
63 }
64
65 void SetRequestedResourceType(SRMRequestContext_t *context)
66 {
67     context->resourceType = GetSvrTypeFromUri(context->resourceUri);
68 }
69
70 // Send the response (context->responseInfo) to the requester
71 // (context->endPoint).
72 static void SRMSendResponse(SRMRequestContext_t *context)
73 {
74     if (NULL != context
75         && NULL != context->requestInfo
76         && NULL != context->endPoint)
77     {
78
79         if (CA_STATUS_OK == CASendResponse(context->endPoint,
80             &(context->responseInfo)))
81         {
82             OIC_LOG_V(DEBUG, TAG, "SRM response sent.");
83             context->responseSent = true;
84         }
85         else
86         {
87             OIC_LOG_V(ERROR, TAG, "SRM response failed.");
88         }
89     }
90     else
91     {
92         OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
93     }
94
95     return;
96 }
97
98 // Based on the context->responseVal, either call the entity handler for the
99 // request (which must send the response), or send an ACCESS_DENIED response.
100 void SRMGenerateResponse(SRMRequestContext_t *context)
101 {
102     OIC_LOG_V(INFO, TAG, "%s : entering function.", __func__);
103
104     // If Access Granted, validate parameters and then pass request
105     // on to resource endpoint.
106     if (IsAccessGranted(context->responseVal))
107     {
108         if(NULL != gRequestHandler
109             && NULL != context->endPoint
110             && NULL != context->requestInfo)
111         {
112             OIC_LOG_V(INFO, TAG, "%s : Access granted, passing req to endpoint.",
113              __func__);
114             gRequestHandler(context->endPoint, context->requestInfo);
115             context->responseSent = true; // SRM counts on the endpoint to send
116                                           // a response.
117         }
118         else // error condition; log relevant msg then send DENIED response
119         {
120             OIC_LOG_V(ERROR, TAG, "%s : Null values in context.", __func__);
121             context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
122             context->responseInfo.result = CA_INTERNAL_SERVER_ERROR;
123             SRMSendResponse(context);
124         }
125     }
126     else // Access Denied
127     {
128         OIC_LOG_V(INFO, TAG, "%s : Access Denied; sending CA_UNAUTHORIZED_REQ.",
129          __func__);
130         // TODO: in future version, differentiate between types of DENIED.
131         // See JIRA issue 1796 (https://jira.iotivity.org/browse/IOT-1796)
132         context->responseInfo.result = CA_UNAUTHORIZED_REQ;
133         SRMSendResponse(context);
134     }
135     return;
136 }
137
138 // Set the value of context->resourceUri, based on the context->requestInfo.
139 void SetResourceUriAndType(SRMRequestContext_t *context)
140 {
141     char *uri = strstr(context->requestInfo->info.resourceUri, "?");
142     size_t position = 0;
143
144     if (uri)
145     {
146         //Skip query and pass the resource uri
147         position = uri - context->requestInfo->info.resourceUri;
148     }
149     else
150     {
151         position = strlen(context->requestInfo->info.resourceUri);
152     }
153     if (MAX_URI_LENGTH < position  || 0 > position)
154     {
155         OIC_LOG_V(ERROR, TAG, "Incorrect URI length.");
156         return;
157     }
158     OICStrcpyPartial(context->resourceUri, MAX_URI_LENGTH + 1,
159         context->requestInfo->info.resourceUri, position);
160
161     // Set the resource type.
162     context->resourceType = GetSvrTypeFromUri(context->resourceUri);
163
164     return;
165 }
166
167 // Check if this request is asking to access a "sec" = true resource
168 // over an unsecure channel.  This type of request is forbidden with
169 // the exception of a few SVRs (see Security Specification).
170 void CheckRequestForSecResourceOverUnsecureChannel(SRMRequestContext_t *context)
171 {
172     // if request is over unsecure channel, check resource type
173     if(false == context->secureChannel)
174     {
175         OCResource *resPtr = FindResourceByUri(context->resourceUri);
176         if (NULL != resPtr)
177         {
178             // All vertical secure resources and SVR resources other than
179             // DOXM & PSTAT should reject requests over unsecure channel.
180             if ((((resPtr->resourceProperties) & OC_SECURE)
181                 && (context->resourceType == NOT_A_SVR_RESOURCE))
182                 || ((context->resourceType < OIC_SEC_SVR_TYPE_COUNT)
183                     && (context->resourceType != OIC_R_DOXM_TYPE)
184                     && (context->resourceType != OIC_R_PSTAT_TYPE)))
185             {
186                 // Reject all the requests over coap for secure resource.
187                 context->responseVal = ACCESS_DENIED_SEC_RESOURCE_OVER_UNSECURE_CHANNEL;
188                 context->responseInfo.result = CA_FORBIDDEN_REQ;
189                 SRMSendResponse(context);
190             }
191         }
192     }
193
194     return;
195 }
196
197 void ClearRequestContext(SRMRequestContext_t *context)
198 {
199     if (NULL == context)
200     {
201
202         OIC_LOG(ERROR, TAG, "Null context.");
203     }
204     else
205     {
206         // Clear context variables.
207         context->endPoint = NULL;
208         context->resourceType = OIC_RESOURCE_TYPE_ERROR;
209         memset(&context->resourceUri, 0, sizeof(context->resourceUri));
210         context->requestedPermission = PERMISSION_ERROR;
211         memset(&context->responseInfo, 0, sizeof(context->responseInfo));
212         context->responseSent = false;
213         context->responseVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
214         context->requestInfo = NULL;
215         context->secureChannel = false;
216         context->slowResponseSent = false;
217         context->subjectIdType = SUBJECT_ID_TYPE_ERROR;
218         memset(&context->subjectUuid, 0, sizeof(context->subjectUuid));
219 #ifdef MULTIPLE_OWNER
220         memset(&context->payload, 0, context->payloadSize); // TODO Samsung reviewer: please confirm
221         context->payloadSize = 0; // TODO Samsung reviewer: please confirm
222 #endif //MULTIPLE_OWNER
223     }
224
225     return;
226 }
227
228 // Returns true iff Request arrived over secure channel
229 bool isRequestOverSecureChannel(SRMRequestContext_t *context)
230 {
231     OicUuid_t nullSubjectId = {.id = {0}};
232
233     // if flag set, return true
234     if(context->endPoint->flags & CA_SECURE)
235     {
236         return true;
237     }
238     // a null subject ID indicates CoAP, so if non-null, also return true
239     else if(memcmp(context->requestInfo->info.identity.id,
240         nullSubjectId.id, sizeof(context->requestInfo->info.identity.id)) != 0)
241     {
242         return true;
243     }
244
245     return false;
246 }
247
248 /**
249  * Entry point into SRM, called by lower layer to determine whether an incoming
250  * request should be GRANTED or DENIED.
251  *
252  * @param endPoint object from which the response is received.
253  * @param requestInfo contains information for the request.
254  */
255 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
256 {
257     OIC_LOG(DEBUG, TAG, "Received request from remote device");
258
259     SRMRequestContext_t *ctx = &g_requestContext; // Always use our single ctx for now.
260
261     ClearRequestContext(ctx);
262
263     if (!endPoint || !requestInfo)
264     {
265         OIC_LOG(ERROR, TAG, "Invalid endPoint or requestInfo; can't process.");
266     }
267     else
268     {
269         ctx->endPoint = endPoint;
270         ctx->requestInfo = requestInfo;
271         ctx->requestedPermission = GetPermissionFromCAMethod_t(requestInfo->method);
272
273         // Copy the subjectID.
274         memcpy(ctx->subjectUuid.id,
275             requestInfo->info.identity.id, sizeof(ctx->subjectUuid.id));
276         ctx->subjectIdType = SUBJECT_ID_TYPE_UUID; // only supported type for now
277
278         // Set secure channel boolean.
279         ctx->secureChannel = isRequestOverSecureChannel(ctx);
280
281         // Set resource URI and type.
282         SetResourceUriAndType(ctx);
283
284         // Initialize responseInfo.
285         memcpy(&(ctx->responseInfo.info), &(requestInfo->info),
286             sizeof(ctx->responseInfo.info));
287         ctx->responseInfo.info.payload = NULL;
288         ctx->responseInfo.result = CA_INTERNAL_SERVER_ERROR;
289         ctx->responseInfo.info.dataType = CA_RESPONSE_DATA;
290
291         // Before consulting ACL, check if this is a forbidden request type.
292         CheckRequestForSecResourceOverUnsecureChannel(ctx);
293
294         // If DENIED response wasn't sent already, then it's time to check ACL.
295         if(false == ctx->responseSent)
296         {
297 #ifdef MULTIPLE_OWNER // TODO Samsung: please verify that these two calls belong
298                       // here inside this conditional statement.
299             // In case of ACL and CRED, The payload required to verify the payload.
300             // Payload information will be used for subowner's permission verification.
301             ctx->payload = (uint8_t*)requestInfo->info.payload;
302             ctx->payloadSize = requestInfo->info.payloadSize;
303 #endif //MULTIPLE_OWNER
304
305             OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method %d",
306                 ctx->requestInfo->info.resourceUri, ctx->requestInfo->method);
307             CheckPermission(ctx);
308             OIC_LOG_V(DEBUG, TAG, "Request for permission %d received responseVal %d.",
309                 ctx->requestedPermission, ctx->responseVal);
310
311             // Now that we have determined the correct response and set responseVal,
312             // we generate and send the response to the requester.
313             SRMGenerateResponse(ctx);
314         }
315     }
316
317     if(false == ctx->responseSent)
318     {
319         OIC_LOG(ERROR, TAG, "Exiting SRM without responding to requester!");
320     }
321
322     return;
323 }
324
325 /**
326  * Handle the response from the SRM.
327  *
328  * @param endPoint points to the remote endpoint.
329  * @param responseInfo contains response information from the endpoint.
330  */
331 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
332 {
333     OIC_LOG(DEBUG, TAG, "Received response from remote device");
334
335     // isProvResponse flag is to check whether response is catered by provisioning APIs or not.
336     // When token sent by CA response matches with token generated by provisioning request,
337     // gSPResponseHandler returns true and response is not sent to RI layer. In case
338     // gSPResponseHandler is null and isProvResponse is false response then the response is for
339     // RI layer.
340     bool isProvResponse = false;
341
342     if (gSPResponseHandler)
343     {
344         isProvResponse = gSPResponseHandler(endPoint, responseInfo);
345     }
346     if (!isProvResponse && gResponseHandler)
347     {
348         gResponseHandler(endPoint, responseInfo);
349     }
350 }
351
352 /**
353  * Handle the error from the SRM.
354  *
355  * @param endPoint is the remote endpoint.
356  * @param errorInfo contains error information from the endpoint.
357  */
358 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
359 {
360     OIC_LOG_V(INFO, TAG, "Received error from remote device with result, %d for request uri, %s",
361         errorInfo->result, errorInfo->info.resourceUri);
362     if (gErrorHandler)
363     {
364         gErrorHandler(endPoint, errorInfo);
365     }
366 }
367
368 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
369     CAResponseCallback respHandler, CAErrorCallback errHandler)
370 {
371     OIC_LOG(DEBUG, TAG, "SRMRegisterHandler !!");
372     if( !reqHandler || !respHandler || !errHandler)
373     {
374         OIC_LOG(ERROR, TAG, "Callback handlers are invalid");
375         return OC_STACK_INVALID_PARAM;
376     }
377     gRequestHandler = reqHandler;
378     gResponseHandler = respHandler;
379     gErrorHandler = errHandler;
380
381
382 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
383     CARegisterHandler(SRMRequestHandler, SRMResponseHandler, SRMErrorHandler);
384 #else
385     CARegisterHandler(reqHandler, respHandler, errHandler);
386 #endif /* __WITH_DTLS__ */
387     return OC_STACK_OK;
388 }
389
390 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
391 {
392     OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
393     return OCRegisterPersistentStorageHandler(persistentStorageHandler);
394 }
395
396 OCPersistentStorage* SRMGetPersistentStorageHandler()
397 {
398     return OCGetPersistentStorageHandler();
399 }
400
401 OCStackResult SRMInitSecureResources()
402 {
403     // TODO: temporarily returning OC_STACK_OK every time until default
404     // behavior (for when SVR DB is missing) is settled.
405     InitSecureResources();
406     OCStackResult ret = OC_STACK_OK;
407 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
408     if (CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
409     {
410         OIC_LOG(ERROR, TAG, "Failed to revert TLS credential handler.");
411         ret = OC_STACK_ERROR;
412     }
413     CAregisterPkixInfoHandler(GetPkixInfo);
414     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
415 #endif // __WITH_DTLS__ or __WITH_TLS__
416     return ret;
417 }
418
419 void SRMDeInitSecureResources()
420 {
421     DestroySecureResources();
422 }
423
424 bool SRMIsSecurityResourceURI(const char* uri)
425 {
426     if (!uri)
427     {
428         return false;
429     }
430
431     const char *rsrcs[] = {
432         OIC_RSRC_SVC_URI,
433         OIC_RSRC_AMACL_URI,
434         OIC_RSRC_CRL_URI,
435         OIC_RSRC_CRED_URI,
436         OIC_RSRC_ACL_URI,
437         OIC_RSRC_DOXM_URI,
438         OIC_RSRC_PSTAT_URI,
439         OIC_RSRC_PCONF_URI,
440         OIC_RSRC_DPAIRING_URI,
441         OIC_RSRC_VER_URI,
442         OC_RSRVD_PROV_CRL_URL
443     };
444
445     // Remove query from Uri for resource string comparison
446     size_t uriLen = strlen(uri);
447     char *query = strchr (uri, '?');
448     if (query)
449     {
450         uriLen = query - uri;
451     }
452
453     for (size_t i = 0; i < sizeof(rsrcs)/sizeof(rsrcs[0]); i++)
454     {
455         size_t svrLen = strlen(rsrcs[i]);
456
457         if ((uriLen == svrLen) &&
458             (strncmp(uri, rsrcs[i], svrLen) == 0))
459         {
460             return true;
461         }
462     }
463
464     return false;
465 }
466
467 /**
468  * Get the Secure Virtual Resource (SVR) type from the URI.
469  * @param   uri [IN] Pointer to URI in question.
470  * @return  The OicSecSvrType_t of the URI passed (note: if not a Secure Virtual
471             Resource, e.g. /a/light, will return "NOT_A_SVR_TYPE" enum value)
472  */
473 static const char URI_QUERY_CHAR = '?';
474 OicSecSvrType_t GetSvrTypeFromUri(const char* uri)
475 {
476     if (!uri)
477     {
478         return NOT_A_SVR_RESOURCE;
479     }
480
481     // Remove query from Uri for resource string comparison
482     size_t uriLen = strlen(uri);
483     char *query = strchr (uri, URI_QUERY_CHAR);
484     if (query)
485     {
486         uriLen = query - uri;
487     }
488
489     size_t svrLen = 0;
490
491     svrLen = strlen(OIC_RSRC_ACL_URI);
492     if(uriLen == svrLen)
493     {
494         if(0 == strncmp(uri, OIC_RSRC_ACL_URI, svrLen))
495         {
496             return OIC_R_ACL_TYPE;
497         }
498     }
499
500     svrLen = strlen(OIC_RSRC_AMACL_URI);
501     if(uriLen == svrLen)
502     {
503         if(0 == strncmp(uri, OIC_RSRC_AMACL_URI, svrLen))
504         {
505             return OIC_R_AMACL_TYPE;
506         }
507     }
508
509     svrLen = strlen(OIC_RSRC_CRED_URI);
510     if(uriLen == svrLen)
511     {
512         if(0 == strncmp(uri, OIC_RSRC_CRED_URI, svrLen))
513         {
514             return OIC_R_CRED_TYPE;
515         }
516     }
517
518     svrLen = strlen(OIC_RSRC_CRL_URI);
519     if(uriLen == svrLen)
520     {
521         if(0 == strncmp(uri, OIC_RSRC_CRL_URI, svrLen))
522         {
523             return OIC_R_CRL_TYPE;
524         }
525     }
526
527     svrLen = strlen(OIC_RSRC_DOXM_URI);
528     if(uriLen == svrLen)
529     {
530         if(0 == strncmp(uri, OIC_RSRC_DOXM_URI, svrLen))
531         {
532             return OIC_R_DOXM_TYPE;
533         }
534     }
535
536     svrLen = strlen(OIC_RSRC_DPAIRING_URI);
537     if(uriLen == svrLen)
538     {
539         if(0 == strncmp(uri, OIC_RSRC_DPAIRING_URI, svrLen))
540         {
541             return OIC_R_DPAIRING_TYPE;
542         }
543     }
544
545     svrLen = strlen(OIC_RSRC_PCONF_URI);
546     if(uriLen == svrLen)
547     {
548         if(0 == strncmp(uri, OIC_RSRC_PCONF_URI, svrLen))
549         {
550             return OIC_R_PCONF_TYPE;
551         }
552     }
553
554     svrLen = strlen(OIC_RSRC_PSTAT_URI);
555     if(uriLen == svrLen)
556     {
557         if(0 == strncmp(uri, OIC_RSRC_PSTAT_URI, svrLen))
558         {
559             return OIC_R_PSTAT_TYPE;
560         }
561     }
562
563     svrLen = strlen(OIC_RSRC_SVC_URI);
564     if(uriLen == svrLen)
565     {
566         if(0 == strncmp(uri, OIC_RSRC_SVC_URI, svrLen))
567         {
568             return OIC_R_SVC_TYPE;
569         }
570     }
571
572     svrLen = strlen(OIC_RSRC_SACL_URI);
573     if(uriLen == svrLen)
574     {
575         if(0 == strncmp(uri, OIC_RSRC_SACL_URI, svrLen))
576         {
577             return OIC_R_SACL_TYPE;
578         }
579     }
580
581     return NOT_A_SVR_RESOURCE;
582 }