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);
143 // TODO - remove these function placeholders as they are implemented
144 // in the resource entity handler code.
145 // Note that because many SVRs do not have a rowner, in those cases we
146 // just return "OC_STACK_ERROR" which results in a "false" return by
147 // IsRequestFromResourceOwner().
148 // As these SVRs are revised to have a rowner, these functions should be
149 // replaced (see pstatresource.c for example of GetPstatRownerId).
151 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
154 return OC_STACK_ERROR;
157 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
160 return OC_STACK_ERROR;
163 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
166 return OC_STACK_ERROR;
169 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
183 * Compare the request's subject to resource.ROwner.
185 * @return true if context->subjectId equals SVR rowner id, else return false
187 bool IsRequestFromResourceOwner(PEContext_t *context)
190 OicUuid_t resourceOwner;
197 if((OIC_R_ACL_TYPE <= context->resourceType) && \
198 (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
200 if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
202 retVal = UuidCmp(&context->subject, &resourceOwner);
208 OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
212 OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
218 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
220 OicUuid_t emptySubject = {.id={0}};
227 return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
232 * Bitwise check to see if 'permission' contains 'request'.
234 * @param permission is the allowed CRUDN permission.
235 * @param request is the CRUDN permission being requested.
237 * @return true if 'permission' bits include all 'request' bits.
239 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
240 const uint16_t request)
242 if (request == (request & permission))
253 * Compare the passed subject to the wildcard (aka anonymous) subjectId.
255 * @return true if 'subject' is the wildcard, false if it is not.
257 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
264 // Because always comparing to string literal, use strcmp()
265 if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
276 * Copy the subject, resource and permission into the context fields.
278 static void CopyParamsToContext(PEContext_t *context,
279 const OicUuid_t *subjectId,
280 const char *resource,
281 const uint16_t requestedPermission)
285 if (NULL == context || NULL == subjectId || NULL == resource)
290 memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
292 // Copy the resource string into context.
293 length = strlen(resource) + 1;
296 strncpy(context->resource, resource, length);
297 context->resource[length - 1] = '\0';
300 // Assign the permission field.
301 context->permission = requestedPermission;
305 * Check whether 'resource' is getting accessed within the valid time period.
307 * @param acl is the ACL to check.
309 * @return true if access is within valid time period or if the period or recurrence is not present.
310 * false if period and recurrence present and the access is not within valid time period.
312 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
314 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
315 //lack of absolute time
316 if (NULL== ace || NULL == ace->validities)
321 //periods & recurrences rules are paired.
322 if (NULL == ace->validities->recurrences)
327 OicSecValidity_t* validity = NULL;
328 LL_FOREACH(ace->validities, validity)
330 for(size_t i = 0; i < validity->recurrenceLen; i++)
332 if (IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(validity->period,
333 validity->recurrences[i]))
335 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
340 OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
349 * Check whether 'resource' is in the passed ACE.
351 * @param resource is the resource being searched.
352 * @param ace is the ACE to check.
354 * @return true if 'resource' found, otherwise false.
356 static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
358 if (NULL== ace || NULL == resource)
363 OicSecRsrc_t* rsrc = NULL;
364 LL_FOREACH(ace->resources, rsrc)
366 if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
367 0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
377 * Find ACLs containing context->subject.
378 * Search each ACL for requested resource.
379 * If resource found, check for context->permission and period validity.
380 * If the ACL is not found locally and AMACL for the resource is found
381 * then sends the request to AMS service for the ACL.
382 * Set context->retVal to result from first ACL found which contains
383 * correct subject AND resource.
385 static void ProcessAccessRequest(PEContext_t *context)
387 OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
390 const OicSecAce_t *currentAce = NULL;
391 OicSecAce_t *savePtr = NULL;
393 // Start out assuming subject not found.
394 context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
396 // Loop through all ACLs with a matching Subject searching for the right
397 // ACL for this request.
400 OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
401 currentAce = GetACLResourceData(&context->subject, &savePtr);
403 if (NULL != currentAce)
405 // Found the subject, so how about resource?
406 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
408 // Subject was found, so err changes to Rsrc not found for now.
409 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
410 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
411 if (IsResourceInAce(context->resource, currentAce))
413 OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
414 context->matchingAclFound = true;
416 // Found the resource, so it's down to valid period & permission.
417 context->retVal = ACCESS_DENIED_INVALID_PERIOD;
418 if (IsAccessWithinValidTime(currentAce))
420 context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
421 if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
423 context->retVal = ACCESS_GRANTED;
430 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
432 } while ((NULL != currentAce) && (false == context->matchingAclFound));
434 if (IsAccessGranted(context->retVal))
436 OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
440 OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
445 OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
449 SRMAccessResponse_t CheckPermission(PEContext_t *context,
450 const OicUuid_t *subjectId,
451 const char *resource,
452 const uint16_t requestedPermission)
454 SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
456 VERIFY_NON_NULL(TAG, context, ERROR);
457 VERIFY_NON_NULL(TAG, subjectId, ERROR);
458 VERIFY_NON_NULL(TAG, resource, ERROR);
460 // Each state machine context can only be processing one request at a time.
461 // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
462 // state, return error. Otherwise, change to BUSY state and begin processing request.
463 if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
465 if (AWAITING_REQUEST == context->state)
467 SetPolicyEngineState(context, BUSY);
468 CopyParamsToContext(context, subjectId, resource, requestedPermission);
471 // Before doing any processing, check if request coming
472 // from DevOwner and if so, always GRANT.
473 if (IsRequestFromDevOwner(context))
475 context->retVal = ACCESS_GRANTED;
477 // Then check if request is for a SVR and coming from rowner
478 else if (IsRequestFromResourceOwner(context))
480 context->retVal = ACCESS_GRANTED;
482 // Else request is a "normal" request that must be tested against ACL
485 OicUuid_t saveSubject = {.id={0}};
486 bool isSubEmpty = IsRequestSubjectEmpty(context);
488 ProcessAccessRequest(context);
490 // If matching ACL not found, and subject != wildcard, try wildcard.
491 if ((false == context->matchingAclFound) && \
492 (false == IsWildCardSubject(&context->subject)))
494 //Saving subject for Amacl check
495 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
497 //Setting context subject to WILDCARD_SUBJECT_ID
498 //TODO: change ProcessAccessRequest method signature to
499 //ProcessAccessRequest(context, subject) so that context
500 //subject is not tempered.
501 memset(&context->subject, 0, sizeof(context->subject));
502 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
503 ProcessAccessRequest(context); // TODO anonymous subj can result
504 // in confusing err code return.
507 //No local ACE found for the request so checking Amacl resource
508 if (ACCESS_GRANTED != context->retVal)
510 //If subject is not empty then restore the original subject
511 //else keep the subject to WILDCARD_SUBJECT_ID
514 memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
517 //FoundAmaclForRequest method checks for Amacl and fills up
518 //context->amsMgrContext->amsDeviceId with the AMS deviceId
519 //if Amacl was found for the requested resource.
520 if(FoundAmaclForRequest(context))
522 ProcessAMSRequest(context);
529 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
532 // Capture retVal before resetting state for next request.
533 retVal = context->retVal;
535 if (!context->amsProcessing)
537 OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
538 SetPolicyEngineState(context, AWAITING_REQUEST);
545 OCStackResult InitPolicyEngine(PEContext_t *context)
549 return OC_STACK_ERROR;
552 context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
553 if(NULL == context->amsMgrContext)
555 return OC_STACK_ERROR;
558 SetPolicyEngineState(context, AWAITING_REQUEST);
562 void DeInitPolicyEngine(PEContext_t *context)
566 SetPolicyEngineState(context, STOPPED);
567 OICFree(context->amsMgrContext);