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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 #include "oic_malloc.h"
22 #include "policyengine.h"
24 #include "resourcemanager.h"
25 #include "securevirtualresourcetypes.h"
26 #include "srmresourcestrings.h"
28 #include "aclresource.h"
29 #include "srmutility.h"
30 #include "doxmresource.h"
31 #include "iotvticalendar.h"
37 * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
39 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
45 perm = (uint16_t)PERMISSION_READ;
47 case CA_POST: // For now we treat all PUT & POST as Write
48 case CA_PUT: // because we don't know if resource exists yet.
49 perm = (uint16_t)PERMISSION_WRITE;
52 perm = (uint16_t)PERMISSION_DELETE;
54 default: // if not recognized, must assume requesting full control
55 perm = (uint16_t)PERMISSION_FULL_CONTROL;
62 * @brief Compares two OicUuid_t structs.
63 * @return true if the two OicUuid_t structs are equal, else false.
65 bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
67 // TODO use VERIFY macros to check for null when they are merged.
68 if(NULL == firstId || NULL == secondId)
72 for(int i = 0; i < UUID_LENGTH; i++)
74 if(firstId->id[i] != secondId->id[i])
83 * Set the state and clear other stateful context vars.
85 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
92 // Clear stateful context variables.
93 memset(&context->subject, 0, sizeof(context->subject));
94 memset(&context->resource, 0, sizeof(context->resource));
95 context->permission = 0x0;
96 context->matchingAclFound = false;
97 context->amsProcessing = false;
98 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
99 memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
102 context->state = state;
106 * @brief Compare the request's subject to DevOwner.
108 * @return true if context->subjectId == GetDoxmDevOwner(), else false
110 bool IsRequestFromDevOwner(PEContext_t *context)
117 return OC_STACK_ERROR;
120 if(OC_STACK_OK == GetDoxmDevOwnerId(&owner))
122 retVal = UuidCmp(&context->subject, &owner);
129 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
131 OicUuid_t emptySubject = {.id={}};
138 return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
144 * Bitwise check to see if 'permission' contains 'request'.
145 * @param permission The allowed CRUDN permission.
146 * @param request The CRUDN permission being requested.
147 * @return true if 'permission' bits include all 'request' bits.
149 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
150 const uint16_t request)
152 if(request == (request & permission))
163 * Compare the passed subject to the wildcard (aka anonymous) subjectId.
164 * @return true if 'subject' is the wildcard, false if it is not.
166 static inline bool IsWildCardSubject(OicUuid_t *subject)
173 // Because always comparing to string literal, use strcmp()
174 if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
185 * Copy the subject, resource and permission into the context fields.
187 void CopyParamsToContext(
188 PEContext_t *context,
189 const OicUuid_t *subjectId,
190 const char *resource,
191 const uint16_t requestedPermission)
195 if(NULL == context || NULL == subjectId || NULL == resource)
200 memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
202 // Copy the resource string into context.
203 length = strlen(resource) + 1;
206 strncpy(context->resource, resource, length);
207 context->resource[length - 1] = '\0';
210 // Assign the permission field.
211 context->permission = requestedPermission;
216 * Check whether 'resource' is getting accessed within the valid time period.
217 * @param acl The ACL to check.
219 * true if access is within valid time period or if the period or recurrence is not present.
220 * false if period and recurrence present and the access is not within valid time period.
222 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
224 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
225 //lack of absolute time
226 if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
231 //periods & recurrences rules are paired.
232 if(NULL == acl->recurrences)
237 for(size_t i = 0; i < acl->prdRecrLen; i++)
239 if(IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(acl->periods[i],
240 acl->recurrences[i]))
242 OC_LOG(INFO, TAG, "Access request is in allowed time period");
246 OC_LOG(ERROR, TAG, "Access request is in invalid time period");
255 * Check whether 'resource' is in the passed ACL.
256 * @param resource The resource to search for.
257 * @param acl The ACL to check.
258 * @return true if 'resource' found, otherwise false.
260 bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
262 if(NULL== acl || NULL == resource)
267 for(size_t n = 0; n < acl->resourcesLen; n++)
269 if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
270 0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
280 * Find ACLs containing context->subject.
281 * Search each ACL for requested resource.
282 * If resource found, check for context->permission and period validity.
283 * If the ACL is not found locally and AMACL for the resource is found
284 * then sends the request to AMS service for the ACL
285 * Set context->retVal to result from first ACL found which contains
286 * correct subject AND resource.
290 void ProcessAccessRequest(PEContext_t *context)
292 OC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
295 const OicSecAcl_t *currentAcl = NULL;
296 OicSecAcl_t *savePtr = NULL;
298 // Start out assuming subject not found.
299 context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
301 // Loop through all ACLs with a matching Subject searching for the right
302 // ACL for this request.
305 OC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
306 currentAcl = GetACLResourceData(&context->subject, &savePtr);
308 if(NULL != currentAcl)
310 // Found the subject, so how about resource?
311 OC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
313 // Subject was found, so err changes to Rsrc not found for now.
314 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
315 OC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
316 if(IsResourceInAcl(context->resource, currentAcl))
318 OC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
319 context->matchingAclFound = true;
321 // Found the resource, so it's down to valid period & permission.
322 context->retVal = ACCESS_DENIED_INVALID_PERIOD;
323 if(IsAccessWithinValidTime(currentAcl))
325 context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
326 if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
328 context->retVal = ACCESS_GRANTED;
335 OC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
338 while((NULL != currentAcl) && (false == context->matchingAclFound));
340 if(IsAccessGranted(context->retVal))
342 OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
346 OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
351 OC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
356 * Check whether a request should be allowed.
357 * @param context Pointer to (Initialized) Policy Engine context to use.
358 * @param subjectId Pointer to Id of the requesting entity.
359 * @param resource Pointer to URI of Resource being requested.
360 * @param permission Requested permission.
361 * @return ACCESS_GRANTED if request should go through,
362 * otherwise some flavor of ACCESS_DENIED
364 SRMAccessResponse_t CheckPermission(
365 PEContext_t *context,
366 const OicUuid_t *subjectId,
367 const char *resource,
368 const uint16_t requestedPermission)
370 SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
372 VERIFY_NON_NULL(TAG, context, ERROR);
373 VERIFY_NON_NULL(TAG, subjectId, ERROR);
374 VERIFY_NON_NULL(TAG, resource, ERROR);
376 // Each state machine context can only be processing one request at a time.
377 // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
378 // state, return error. Otherwise, change to BUSY state and begin processing request.
379 if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
381 if(AWAITING_REQUEST == context->state)
383 SetPolicyEngineState(context, BUSY);
384 CopyParamsToContext(context, subjectId, resource, requestedPermission);
387 // Before doing any processing, check if request coming
388 // from DevOwner and if so, always GRANT.
389 if(IsRequestFromDevOwner(context))
391 context->retVal = ACCESS_GRANTED;
395 OicUuid_t saveSubject = {.id={}};
396 bool isSubEmpty = IsRequestSubjectEmpty(context);
398 ProcessAccessRequest(context);
400 // If matching ACL not found, and subject != wildcard, try wildcard.
401 if((false == context->matchingAclFound) && \
402 (false == IsWildCardSubject(&context->subject)))
404 //Saving subject for Amacl check
405 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
407 //Setting context subject to WILDCARD_SUBJECT_ID
408 //TODO: change ProcessAccessRequest method signature to
409 //ProcessAccessRequest(context, subject) so that context
410 //subject is not tempered.
411 memset(&context->subject, 0, sizeof(context->subject));
412 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
413 ProcessAccessRequest(context); // TODO anonymous subj can result
414 // in confusing err code return.
417 //No local ACE found for the request so checking Amacl resource
418 if(ACCESS_GRANTED != context->retVal)
420 //If subject is not empty then restore the original subject
421 //else keep the subject to WILDCARD_SUBJECT_ID
424 memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
427 //FoundAmaclForRequest method checks for Amacl and fills up
428 //context->amsMgrContext->amsDeviceId with the AMS deviceId
429 //if Amacl was found for the requested resource.
430 if(FoundAmaclForRequest(context))
432 ProcessAMSRequest(context);
439 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
442 // Capture retVal before resetting state for next request.
443 retVal = context->retVal;
445 //Change the state of PE to "AWAITING_AMS_RESPONSE", if waiting
446 //for response from AMS service else to "AWAITING_REQUEST"
447 if(ACCESS_WAITING_FOR_AMS == retVal)
449 OC_LOG(INFO, TAG, "Setting PE State to AWAITING_AMS_RESPONSE");
450 context->state = AWAITING_AMS_RESPONSE;
452 else if(!context->amsProcessing)
454 OC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
455 SetPolicyEngineState(context, AWAITING_REQUEST);
463 * Initialize the Policy Engine. Call this before calling CheckPermission().
464 * @param context Pointer to Policy Engine context to initialize.
465 * @return OC_STACK_OK for Success, otherwise some error value
467 OCStackResult InitPolicyEngine(PEContext_t *context)
471 return OC_STACK_ERROR;
474 context->amsMgrContext = (AmsMgrContext_t *)OICMalloc(sizeof(AmsMgrContext_t));
475 SetPolicyEngineState(context, AWAITING_REQUEST);
481 * De-Initialize the Policy Engine. Call this before exiting to allow Policy
482 * Engine to do cleanup on context.
483 * @param context Pointer to Policy Engine context to de-initialize.
486 void DeInitPolicyEngine(PEContext_t *context)
490 SetPolicyEngineState(context, STOPPED);
491 OICFree(context->amsMgrContext);