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;
100 FreeCARequestInfo(context->amsMgrContext->requestInfo);
101 OICFree(context->amsMgrContext->endpoint);
102 memset(context->amsMgrContext, 0, sizeof(AmsMgrContext_t));
105 context->state = state;
109 * @brief Compare the request's subject to DevOwner.
111 * @return true if context->subjectId == GetDoxmDevOwner(), else false
113 bool IsRequestFromDevOwner(PEContext_t *context)
120 return OC_STACK_ERROR;
123 if(OC_STACK_OK == GetDoxmDevOwnerId(&owner))
125 retVal = UuidCmp(&context->subject, &owner);
132 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
134 OicUuid_t emptySubject = {.id={}};
141 return (memcmp(&context->subject, &emptySubject, sizeof(OicUuid_t)) == 0) ?
147 * Bitwise check to see if 'permission' contains 'request'.
148 * @param permission The allowed CRUDN permission.
149 * @param request The CRUDN permission being requested.
150 * @return true if 'permission' bits include all 'request' bits.
152 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
153 const uint16_t request)
155 if(request == (request & permission))
166 * Compare the passed subject to the wildcard (aka anonymous) subjectId.
167 * @return true if 'subject' is the wildcard, false if it is not.
169 static inline bool IsWildCardSubject(OicUuid_t *subject)
176 // Because always comparing to string literal, use strcmp()
177 if(0 == memcmp(subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)))
188 * Copy the subject, resource and permission into the context fields.
190 void CopyParamsToContext(
191 PEContext_t *context,
192 const OicUuid_t *subjectId,
193 const char *resource,
194 const uint16_t requestedPermission)
198 if(NULL == context || NULL == subjectId || NULL == resource)
203 memcpy(&context->subject, subjectId, sizeof(OicUuid_t));
205 // Copy the resource string into context.
206 length = strlen(resource) + 1;
209 strncpy(context->resource, resource, length);
210 context->resource[length - 1] = '\0';
213 // Assign the permission field.
214 context->permission = requestedPermission;
219 * Check whether 'resource' is getting accessed within the valid time period.
220 * @param acl The ACL to check.
222 * true if access is within valid time period or if the period or recurrence is not present.
223 * false if period and recurrence present and the access is not within valid time period.
225 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
227 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
228 //lack of absolute time
229 if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
234 //periods & recurrences rules are paired.
235 if(NULL == acl->recurrences)
240 for(size_t i = 0; i < acl->prdRecrLen; i++)
242 if(IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(acl->periods[i],
243 acl->recurrences[i]))
245 OC_LOG(INFO, TAG, "Access request is in allowed time period");
249 OC_LOG(ERROR, TAG, "Access request is in invalid time period");
258 * Check whether 'resource' is in the passed ACL.
259 * @param resource The resource to search for.
260 * @param acl The ACL to check.
261 * @return true if 'resource' found, otherwise false.
263 bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
265 if(NULL== acl || NULL == resource)
270 for(size_t n = 0; n < acl->resourcesLen; n++)
272 if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
273 0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
283 * Find ACLs containing context->subject.
284 * Search each ACL for requested resource.
285 * If resource found, check for context->permission and period validity.
286 * If the ACL is not found locally and AMACL for the resource is found
287 * then sends the request to AMS service for the ACL
288 * Set context->retVal to result from first ACL found which contains
289 * correct subject AND resource.
293 void ProcessAccessRequest(PEContext_t *context)
295 OC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
298 const OicSecAcl_t *currentAcl = NULL;
299 OicSecAcl_t *savePtr = NULL;
301 // Start out assuming subject not found.
302 context->retVal = ACCESS_DENIED_SUBJECT_NOT_FOUND;
304 // Loop through all ACLs with a matching Subject searching for the right
305 // ACL for this request.
308 OC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
309 currentAcl = GetACLResourceData(&context->subject, &savePtr);
311 if(NULL != currentAcl)
313 // Found the subject, so how about resource?
314 OC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
316 // Subject was found, so err changes to Rsrc not found for now.
317 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
318 OC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
319 if(IsResourceInAcl(context->resource, currentAcl))
321 OC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
322 context->matchingAclFound = true;
324 // Found the resource, so it's down to valid period & permission.
325 context->retVal = ACCESS_DENIED_INVALID_PERIOD;
326 if(IsAccessWithinValidTime(currentAcl))
328 context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
329 if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
331 context->retVal = ACCESS_GRANTED;
338 OC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
341 while((NULL != currentAcl) && (false == context->matchingAclFound));
343 if(IsAccessGranted(context->retVal))
345 OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
349 OC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_DENIED)", __func__);
354 OC_LOG_V(ERROR, TAG, "%s:Leaving ProcessAccessRequest(context is NULL)", __func__);
359 * Check whether a request should be allowed.
360 * @param context Pointer to (Initialized) Policy Engine context to use.
361 * @param subjectId Pointer to Id of the requesting entity.
362 * @param resource Pointer to URI of Resource being requested.
363 * @param permission Requested permission.
364 * @return ACCESS_GRANTED if request should go through,
365 * otherwise some flavor of ACCESS_DENIED
367 SRMAccessResponse_t CheckPermission(
368 PEContext_t *context,
369 const OicUuid_t *subjectId,
370 const char *resource,
371 const uint16_t requestedPermission)
373 SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
375 VERIFY_NON_NULL(TAG, context, ERROR);
376 VERIFY_NON_NULL(TAG, subjectId, ERROR);
377 VERIFY_NON_NULL(TAG, resource, ERROR);
379 // Each state machine context can only be processing one request at a time.
380 // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
381 // state, return error. Otherwise, change to BUSY state and begin processing request.
382 if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
384 if(AWAITING_REQUEST == context->state)
386 SetPolicyEngineState(context, BUSY);
387 CopyParamsToContext(context, subjectId, resource, requestedPermission);
390 // Before doing any processing, check if request coming
391 // from DevOwner and if so, always GRANT.
392 if(IsRequestFromDevOwner(context))
394 context->retVal = ACCESS_GRANTED;
398 OicUuid_t saveSubject = {.id={}};
399 bool isSubEmpty = IsRequestSubjectEmpty(context);
401 ProcessAccessRequest(context);
403 // If matching ACL not found, and subject != wildcard, try wildcard.
404 if((false == context->matchingAclFound) && \
405 (false == IsWildCardSubject(&context->subject)))
407 //Saving subject for Amacl check
408 memcpy(&saveSubject, &context->subject,sizeof(OicUuid_t));
410 //Setting context subject to WILDCARD_SUBJECT_ID
411 //TODO: change ProcessAccessRequest method signature to
412 //ProcessAccessRequest(context, subject) so that context
413 //subject is not tempered.
414 memset(&context->subject, 0, sizeof(context->subject));
415 memcpy(&context->subject, &WILDCARD_SUBJECT_ID,sizeof(OicUuid_t));
416 ProcessAccessRequest(context); // TODO anonymous subj can result
417 // in confusing err code return.
420 //No local ACE found for the request so checking Amacl resource
421 if(ACCESS_GRANTED != context->retVal)
423 //If subject is not empty then restore the original subject
424 //else keep the subject to WILDCARD_SUBJECT_ID
427 memcpy(&context->subject, &saveSubject, sizeof(OicUuid_t));
430 //FoundAmaclForRequest method checks for Amacl and fills up
431 //context->amsMgrContext->amsDeviceId with the AMS deviceId
432 //if Amacl was found for the requested resource.
433 if(FoundAmaclForRequest(context))
435 ProcessAMSRequest(context);
442 context->retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
445 // Capture retVal before resetting state for next request.
446 retVal = context->retVal;
448 if(!context->amsProcessing)
450 OC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
451 SetPolicyEngineState(context, AWAITING_REQUEST);
459 * Initialize the Policy Engine. Call this before calling CheckPermission().
460 * @param context Pointer to Policy Engine context to initialize.
461 * @return OC_STACK_OK for Success, otherwise some error value
463 OCStackResult InitPolicyEngine(PEContext_t *context)
467 return OC_STACK_ERROR;
470 context->amsMgrContext = (AmsMgrContext_t *)OICCalloc(1, sizeof(AmsMgrContext_t));
471 if(NULL == context->amsMgrContext)
473 return OC_STACK_ERROR;
476 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);