1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 #include "oic_malloc.h"
24 #include "policyengine.h"
26 #include "resourcemanager.h"
27 #include "securevirtualresourcetypes.h"
28 #include "srmresourcestrings.h"
30 #include "aclresource.h"
31 #include "srmutility.h"
32 #include "doxmresource.h"
33 #include "iotvticalendar.h"
34 #include "pstatresource.h"
35 #include "dpairingresource.h"
36 #include "pconfresource.h"
37 #include "amaclresource.h"
38 #include "credresource.h"
42 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
48 perm = (uint16_t)PERMISSION_READ;
50 case CA_POST: // For now we treat all PUT & POST as Write
51 case CA_PUT: // because we don't know if resource exists yet.
52 perm = (uint16_t)PERMISSION_WRITE;
55 perm = (uint16_t)PERMISSION_DELETE;
57 default: // if not recognized, must assume requesting full control
58 perm = (uint16_t)PERMISSION_FULL_CONTROL;
65 * Compares two OicUuid_t structs.
67 * @return true if the two OicUuid_t structs are equal, else false.
69 static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
71 // TODO use VERIFY macros to check for null when they are merged.
72 if(NULL == firstId || NULL == secondId)
76 // Check empty uuid string
77 if('\0' == firstId->id[0] || '\0' == secondId->id[0])
81 for(int i = 0; i < UUID_LENGTH; i++)
83 if(firstId->id[i] != secondId->id[i])
91 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
98 // Clear stateful context variables.
99 memset(&context->subject, 0, sizeof(context->subject));
100 memset(&context->resource, 0, sizeof(context->resource));
101 context->permission = 0x0;
102 context->matchingAclFound = false;
103 context->amsProcessing = false;
104 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
106 if (context->amsMgrContext)
108 if (context->amsMgrContext->requestInfo)
110 FreeCARequestInfo(context->amsMgrContext->requestInfo);
112 OICFree(context->amsMgrContext->endpoint);
113 memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
117 context->state = state;
121 * Compare the request's subject to DevOwner.
123 * @return true if context->subjectId == GetDoxmDevOwner(), else false.
125 static bool IsRequestFromDevOwner(PEContext_t *context)
135 if(OC_STACK_OK == GetDoxmDevOwnerId(&ownerid))
137 retVal = UuidCmp(&context->subject, &ownerid);
141 // TODO: Added as workaround for CTT
142 OicSecDoxm_t* doxm = (OicSecDoxm_t*) GetDoxmResourceData();
145 retVal = UuidCmp(&doxm->owner, &context->subject);
151 #ifdef _ENABLE_MULTIPLE_OWNER_
153 * Compare the request's subject to SubOwner.
155 * @return true if context->subjectId exist subowner list, else false.
157 static bool IsRequestFromSubOwner(PEContext_t *context)
166 if(IsSubOwner(&context->subject))
173 OIC_LOG(INFO, TAG, "PE.IsRequestFromSubOwner(): returning true");
177 OIC_LOG(INFO, TAG, "PE.IsRequestFromSubOwner(): returning false");
185 * Verify the SubOwner's request.
187 * @return true if request is valid, else false.
189 static bool IsValidRequestFromSubOwner(PEContext_t *context)
191 bool isValidRequest = false;
195 return isValidRequest;
198 switch(context->resourceType)
200 case OIC_R_DOXM_TYPE:
201 //SubOwner has READ permission only for DOXM
202 if(PERMISSION_READ == context->permission)
204 isValidRequest = true;
207 case OIC_R_PSTAT_TYPE:
208 //SubOwner has full permsion for PSTAT
209 isValidRequest = true;
211 case OIC_R_CRED_TYPE:
212 //SubOwner can only access the credential which is registered as the eowner.
213 isValidRequest = IsValidCredentialAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
216 //SubOwner can only access the ACL which is registered as the eowner.
217 isValidRequest = IsValidAclAccessForSubOwner(&context->subject, context->payload, context->payloadSize);
220 //SubOwner has full permission for all resource except the security resource
221 isValidRequest = true;
227 OIC_LOG(INFO, TAG, "PE.IsValidRequestFromSubOwner(): returning true");
231 OIC_LOG(INFO, TAG, "PE.IsValidRequestFromSubOwner(): returning false");
234 return isValidRequest;
236 #endif //_ENABLE_MULTIPLE_OWNER_
239 // TODO - remove these function placeholders as they are implemented
240 // in the resource entity handler code.
241 // Note that because many SVRs do not have a rowner, in those cases we
242 // just return "OC_STACK_ERROR" which results in a "false" return by
243 // IsRequestFromResourceOwner().
244 // As these SVRs are revised to have a rowner, these functions should be
245 // replaced (see pstatresource.c for example of GetPstatRownerId).
247 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
251 return OC_STACK_ERROR;
254 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
258 return OC_STACK_ERROR;
261 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
265 return OC_STACK_ERROR;
268 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
282 * Compare the request's subject to resource.ROwner.
284 * @return true if context->subjectId equals SVR rowner id, else return false
286 bool IsRequestFromResourceOwner(PEContext_t *context)
289 OicUuid_t resourceOwner;
296 if((OIC_R_ACL_TYPE <= context->resourceType) && \
297 (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
299 if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
301 retVal = UuidCmp(&context->subject, &resourceOwner);
307 OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
311 OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
317 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
319 OicUuid_t emptySubject = {.id={0}};
326 return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
331 * Bitwise check to see if 'permission' contains 'request'.
333 * @param permission is the allowed CRUDN permission.
334 * @param request is the CRUDN permission being requested.
336 * @return true if 'permission' bits include all 'request' bits.
338 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
339 const uint16_t request)
341 if (request == (request & permission))
352 * Compare the passed subject to the wildcard (aka anonymous) subjectId.
354 * @return true if 'subject' is the wildcard, false if it is not.
356 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
363 // Because always comparing to string literal, use strcmp()
364 if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
375 * Copy the subject, resource and permission into the context fields.
377 static void CopyParamsToContext(PEContext_t *context,
378 const OicUuid_t *subjectId,
379 const char *resource,
380 const uint16_t requestedPermission)
384 if (NULL == context || NULL == subjectId || NULL == resource)
389 memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
391 // Copy the resource string into context.
392 length = sizeof(context->resource) - 1;
393 strncpy(context->resource, resource, length);
394 context->resource[length] = '\0';
397 // Assign the permission field.
398 context->permission = requestedPermission;
402 * Check whether 'resource' is getting accessed within the valid time period.
404 * @param acl is the ACL to check.
406 * @return true if access is within valid time period or if the period or recurrence is not present.
407 * false if period and recurrence present and the access is not within valid time period.
409 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
411 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
412 //lack of absolute time
413 if (NULL== ace || NULL == ace->validities)
418 //periods & recurrences rules are paired.
419 if (NULL == ace->validities->recurrences)
424 OicSecValidity_t* validity = NULL;
425 LL_FOREACH(ace->validities, validity)
427 for(size_t i = 0; i < validity->recurrenceLen; i++)
429 if (IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(validity->period,
430 validity->recurrences[i]))
432 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
437 OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
446 * Check whether 'resource' is in the passed ACE.
448 * @param resource is the resource being searched.
449 * @param ace is the ACE to check.
451 * @return true if 'resource' found, otherwise false.
453 static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
455 if (NULL== ace || NULL == resource)
460 OicSecRsrc_t* rsrc = NULL;
461 LL_FOREACH(ace->resources, rsrc)
463 if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
464 0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
474 * Find ACLs containing context->subject.
475 * Search each ACL for requested resource.
476 * If resource found, check for context->permission and period validity.
477 * If the ACL is not found locally and AMACL for the resource is found
478 * then sends the request to AMS service for the ACL.
479 * Set context->retVal to result from first ACL found which contains
480 * correct subject AND resource.
482 static void ProcessAccessRequest(PEContext_t *context)
484 OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
487 const OicSecAce_t *currentAce = NULL;
488 OicSecAce_t *savePtr = NULL;
490 // Start out assuming subject not found.
491 context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
493 // Loop through all ACLs with a matching Subject searching for the right
494 // ACL for this request.
497 OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
498 currentAce = GetACLResourceData(&context->subject, &savePtr);
500 if (NULL != currentAce)
502 // Found the subject, so how about resource?
503 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
505 // Subject was found, so err changes to Rsrc not found for now.
506 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
507 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
508 if (IsResourceInAce(context->resource, currentAce))
510 OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
511 context->matchingAclFound = true;
513 // Found the resource, so it's down to valid period & permission.
514 context->retVal = ACCESS_DENIED_INVALID_PERIOD;
515 if (IsAccessWithinValidTime(currentAce))
517 context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
518 if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
520 context->retVal = ACCESS_GRANTED;
527 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
529 } while ((NULL != currentAce) && (false == context->matchingAclFound));
531 if (IsAccessGranted(context->retVal))
533 OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
537 OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
542 OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
546 SRMAccessResponse_t CheckPermission(PEContext_t *context,
547 const OicUuid_t *subjectId,
548 const char *resource,
549 const uint16_t requestedPermission)
551 SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
553 VERIFY_NON_NULL(TAG, context, ERROR);
554 VERIFY_NON_NULL(TAG, subjectId, ERROR);
555 VERIFY_NON_NULL(TAG, resource, ERROR);
557 // Each state machine context can only be processing one request at a time.
558 // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
559 // state, return error. Otherwise, change to BUSY state and begin processing request.
560 if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
562 if (AWAITING_REQUEST == context->state)
564 SetPolicyEngineState(context, BUSY);
565 CopyParamsToContext(context, subjectId, resource, requestedPermission);
568 // Before doing any ACL processing, check if request a) coming
569 // from DevOwner AND b) the device is in Ready for OTM or Reset state
570 // (which in IoTivity is equivalent to isOp == false && owned == false)
571 // AND c) the request is for a SVR resource.
572 // If all 3 conditions are met, grant request.
573 bool isDeviceOwned = true; // default to value that will not grant access
574 if (OC_STACK_OK != GetDoxmIsOwned(&isDeviceOwned)) // if runtime error, don't grant
576 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
578 // If we were able to get the value of doxm->isOwned, proceed with
579 // test for implicit access...
580 else if (IsRequestFromDevOwner(context) // if from DevOwner
581 && (GetPstatIsop() == false) // AND if pstat->isOp == false
582 && (isDeviceOwned == false) // AND if doxm->isOwned == false
583 && (context->resourceType != NOT_A_SVR_RESOURCE)) // AND if SVR type
585 context->retVal = ACCESS_GRANTED;
587 #ifdef _ENABLE_MULTIPLE_OWNER_
588 //Then check if request from SubOwner
589 else if(IsRequestFromSubOwner(context))
591 if(IsValidRequestFromSubOwner(context))
593 context->retVal = ACCESS_GRANTED;
596 #endif //_ENABLE_MULTIPLE_OWNER_
597 // If not granted via DevOwner status and not a subowner,
598 // then check if request is for a SVR and coming from rowner
599 else if (IsRequestFromResourceOwner(context))
601 context->retVal = ACCESS_GRANTED;
603 // Else request is a "normal" request that must be tested against ACL
606 OicUuid_t saveSubject = {.id={0}};
607 bool isSubEmpty = IsRequestSubjectEmpty(context);
609 ProcessAccessRequest(context);
611 // If matching ACL not found, and subject != wildcard, try wildcard.
612 if ((false == context->matchingAclFound) && \
613 (false == IsWildCardSubject(&context->subject)))
615 //Saving subject for Amacl check
616 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
618 //Setting context subject to WILDCARD_SUBJECT_ID
619 //TODO: change ProcessAccessRequest method signature to
620 //ProcessAccessRequest(context, subject) so that context
621 //subject is not tempered.
622 memset(&context->subject, 0, sizeof(context->subject));
623 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
624 ProcessAccessRequest(context); // TODO anonymous subj can result
625 // in confusing err code return.
628 //No local ACE found for the request so checking Amacl resource
629 if (ACCESS_GRANTED != context->retVal)
631 //If subject is not empty then restore the original subject
632 //else keep the subject to WILDCARD_SUBJECT_ID
635 memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
638 //FoundAmaclForRequest method checks for Amacl and fills up
639 //context->amsMgrContext->amsDeviceId with the AMS deviceId
640 //if Amacl was found for the requested resource.
641 if(FoundAmaclForRequest(context))
643 ProcessAMSRequest(context);
650 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
653 // Capture retVal before resetting state for next request.
654 retVal = context->retVal;
656 if (!context->amsProcessing)
658 OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
659 SetPolicyEngineState(context, AWAITING_REQUEST);
666 OCStackResult InitPolicyEngine(PEContext_t *context)
670 return OC_STACK_ERROR;
673 context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
674 if(NULL == context->amsMgrContext)
676 return OC_STACK_ERROR;
679 SetPolicyEngineState(context, AWAITING_REQUEST);
683 void DeInitPolicyEngine(PEContext_t *context)
687 SetPolicyEngineState(context, STOPPED);
688 OICFree(context->amsMgrContext);