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);
150 // TODO - remove these function placeholders as they are implemented
151 // in the resource entity handler code.
152 // Note that because many SVRs do not have a rowner, in those cases we
153 // just return "OC_STACK_ERROR" which results in a "false" return by
154 // IsRequestFromResourceOwner().
155 // As these SVRs are revised to have a rowner, these functions should be
156 // replaced (see pstatresource.c for example of GetPstatRownerId).
158 OCStackResult GetCrlRownerId(OicUuid_t *rowner)
162 return OC_STACK_ERROR;
165 OCStackResult GetSaclRownerId(OicUuid_t *rowner)
169 return OC_STACK_ERROR;
172 OCStackResult GetSvcRownerId(OicUuid_t *rowner)
176 return OC_STACK_ERROR;
179 static GetSvrRownerId_t GetSvrRownerId[OIC_SEC_SVR_TYPE_COUNT] = {
193 * Compare the request's subject to resource.ROwner.
195 * @return true if context->subjectId equals SVR rowner id, else return false
197 bool IsRequestFromResourceOwner(PEContext_t *context)
200 OicUuid_t resourceOwner;
207 if((OIC_R_ACL_TYPE <= context->resourceType) && \
208 (OIC_SEC_SVR_TYPE_COUNT > context->resourceType))
210 if(OC_STACK_OK == GetSvrRownerId[(int)context->resourceType](&resourceOwner))
212 retVal = UuidCmp(&context->subject, &resourceOwner);
218 OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning true");
222 OIC_LOG(INFO, TAG, "PE.IsRequestFromResourceOwner(): returning false");
228 INLINE_API bool IsRequestSubjectEmpty(PEContext_t *context)
230 OicUuid_t emptySubject = {.id={0}};
237 return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
242 * Bitwise check to see if 'permission' contains 'request'.
244 * @param permission is the allowed CRUDN permission.
245 * @param request is the CRUDN permission being requested.
247 * @return true if 'permission' bits include all 'request' bits.
249 INLINE_API bool IsPermissionAllowingRequest(const uint16_t permission,
250 const uint16_t request)
252 if (request == (request & permission))
263 * Compare the passed subject to the wildcard (aka anonymous) subjectId.
265 * @return true if 'subject' is the wildcard, false if it is not.
267 INLINE_API bool IsWildCardSubject(OicUuid_t *subject)
274 // Because always comparing to string literal, use strcmp()
275 if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
286 * Copy the subject, resource and permission into the context fields.
288 static void CopyParamsToContext(PEContext_t *context,
289 const OicUuid_t *subjectId,
290 const char *resource,
291 const uint16_t requestedPermission)
295 if (NULL == context || NULL == subjectId || NULL == resource)
300 memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
302 // Copy the resource string into context.
303 length = sizeof(context->resource) - 1;
304 strncpy(context->resource, resource, length);
305 context->resource[length] = '\0';
308 // Assign the permission field.
309 context->permission = requestedPermission;
313 * Check whether 'resource' is getting accessed within the valid time period.
315 * @param acl is the ACL to check.
317 * @return true if access is within valid time period or if the period or recurrence is not present.
318 * false if period and recurrence present and the access is not within valid time period.
320 static bool IsAccessWithinValidTime(const OicSecAce_t *ace)
322 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
323 //lack of absolute time
324 if (NULL== ace || NULL == ace->validities)
329 //periods & recurrences rules are paired.
330 if (NULL == ace->validities->recurrences)
335 OicSecValidity_t* validity = NULL;
336 LL_FOREACH(ace->validities, validity)
338 for(size_t i = 0; i < validity->recurrenceLen; i++)
340 if (IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(validity->period,
341 validity->recurrences[i]))
343 OIC_LOG(INFO, TAG, "Access request is in allowed time period");
348 OIC_LOG(ERROR, TAG, "Access request is in invalid time period");
357 * Check whether 'resource' is in the passed ACE.
359 * @param resource is the resource being searched.
360 * @param ace is the ACE to check.
362 * @return true if 'resource' found, otherwise false.
364 static bool IsResourceInAce(const char *resource, const OicSecAce_t *ace)
366 if (NULL== ace || NULL == resource)
371 OicSecRsrc_t* rsrc = NULL;
372 LL_FOREACH(ace->resources, rsrc)
374 if (0 == strcmp(resource, rsrc->href) || // TODO null terms?
375 0 == strcmp(WILDCARD_RESOURCE_URI, rsrc->href))
385 * Find ACLs containing context->subject.
386 * Search each ACL for requested resource.
387 * If resource found, check for context->permission and period validity.
388 * If the ACL is not found locally and AMACL for the resource is found
389 * then sends the request to AMS service for the ACL.
390 * Set context->retVal to result from first ACL found which contains
391 * correct subject AND resource.
393 static void ProcessAccessRequest(PEContext_t *context)
395 OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
398 const OicSecAce_t *currentAce = NULL;
399 OicSecAce_t *savePtr = NULL;
401 // Start out assuming subject not found.
402 context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
404 // Loop through all ACLs with a matching Subject searching for the right
405 // ACL for this request.
408 OIC_LOG_V(DEBUG, TAG, "%s: getting ACE..." ,__func__);
409 currentAce = GetACLResourceData(&context->subject, &savePtr);
411 if (NULL != currentAce)
413 // Found the subject, so how about resource?
414 OIC_LOG_V(DEBUG, TAG, "%s:found ACE matching subject" ,__func__);
416 // Subject was found, so err changes to Rsrc not found for now.
417 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
418 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
419 if (IsResourceInAce(context->resource, currentAce))
421 OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACE" ,__func__);
422 context->matchingAclFound = true;
424 // Found the resource, so it's down to valid period & permission.
425 context->retVal = ACCESS_DENIED_INVALID_PERIOD;
426 if (IsAccessWithinValidTime(currentAce))
428 context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
429 if (IsPermissionAllowingRequest(currentAce->permission, context->permission))
431 context->retVal = ACCESS_GRANTED;
438 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
440 } while ((NULL != currentAce) && (false == context->matchingAclFound));
442 if (IsAccessGranted(context->retVal))
444 OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
448 OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
453 OIC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
457 SRMAccessResponse_t CheckPermission(PEContext_t *context,
458 const OicUuid_t *subjectId,
459 const char *resource,
460 const uint16_t requestedPermission)
462 SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
464 VERIFY_NON_NULL(TAG, context, ERROR);
465 VERIFY_NON_NULL(TAG, subjectId, ERROR);
466 VERIFY_NON_NULL(TAG, resource, ERROR);
468 // Each state machine context can only be processing one request at a time.
469 // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
470 // state, return error. Otherwise, change to BUSY state and begin processing request.
471 if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
473 if (AWAITING_REQUEST == context->state)
475 SetPolicyEngineState(context, BUSY);
476 CopyParamsToContext(context, subjectId, resource, requestedPermission);
479 // Before doing any processing, check if request coming
480 // from DevOwner and if so, always GRANT.
481 if (IsRequestFromDevOwner(context))
483 context->retVal = ACCESS_GRANTED;
485 // Then check if request is for a SVR and coming from rowner
486 else if (IsRequestFromResourceOwner(context))
488 context->retVal = ACCESS_GRANTED;
490 // Else request is a "normal" request that must be tested against ACL
493 OicUuid_t saveSubject = {.id={0}};
494 bool isSubEmpty = IsRequestSubjectEmpty(context);
496 ProcessAccessRequest(context);
498 // If matching ACL not found, and subject != wildcard, try wildcard.
499 if ((false == context->matchingAclFound) && \
500 (false == IsWildCardSubject(&context->subject)))
502 //Saving subject for Amacl check
503 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
505 //Setting context subject to WILDCARD_SUBJECT_ID
506 //TODO: change ProcessAccessRequest method signature to
507 //ProcessAccessRequest(context, subject) so that context
508 //subject is not tempered.
509 memset(&context->subject, 0, sizeof(context->subject));
510 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
511 ProcessAccessRequest(context); // TODO anonymous subj can result
512 // in confusing err code return.
515 //No local ACE found for the request so checking Amacl resource
516 if (ACCESS_GRANTED != context->retVal)
518 //If subject is not empty then restore the original subject
519 //else keep the subject to WILDCARD_SUBJECT_ID
522 memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
525 //FoundAmaclForRequest method checks for Amacl and fills up
526 //context->amsMgrContext->amsDeviceId with the AMS deviceId
527 //if Amacl was found for the requested resource.
528 if(FoundAmaclForRequest(context))
530 ProcessAMSRequest(context);
537 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
540 // Capture retVal before resetting state for next request.
541 retVal = context->retVal;
543 if (!context->amsProcessing)
545 OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
546 SetPolicyEngineState(context, AWAITING_REQUEST);
553 OCStackResult InitPolicyEngine(PEContext_t *context)
557 return OC_STACK_ERROR;
560 context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
561 if(NULL == context->amsMgrContext)
563 return OC_STACK_ERROR;
566 SetPolicyEngineState(context, AWAITING_REQUEST);
570 void DeInitPolicyEngine(PEContext_t *context)
574 SetPolicyEngineState(context, STOPPED);
575 OICFree(context->amsMgrContext);